text
stringlengths
15
267k
# 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()
# -*- coding: utf-8 -*- """ list asset dependencies """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = 'timmyliang' __email__ = '[email protected]' __date__ = '2021-07-08 11:26:32' import unreal asset_lib = unreal.EditorAssetLibrary asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() def ls_dependencies(path,data=None): data = data if data else asset_lib.find_asset_data(path) options = unreal.AssetRegistryDependencyOptions() dependencies = asset_registry.get_dependencies(data.package_name, options) return dependencies if dependencies else [] def ls_referencers(path, data=None): data = data if data else asset_lib.find_asset_data(path) options = unreal.AssetRegistryDependencyOptions() refs = asset_registry.get_referencers(data.package_name, options) return refs if refs else [] asset, = unreal.EditorUtilityLibrary.get_selected_assets() depend =ls_referencers(asset.get_path_name()) print(depend)
import infrastructure.cross_cutting.ioc_container as ioc_container from mediatr import Mediator from infrastructure.cross_cutting.package_solver import PackageSolver import unreal from infrastructure.configuration.request import * ioc_container = ioc_container.Container() _PYTHON_INTERPRETER_PATH = unreal.get_interpreter_executable_path() class Bootstrapper(): def __init__(self, install_missing_packages: bool = False) -> None: if install_missing_packages: PackageSolver.install_missing_packages() mediator = Mediator() def get_mediator(self): return self.mediator @Mediator.handler def log_empty_folders_handler(request: LogEmptyFoldersRequest): ioc_container.maintenance_handler().log_empty_folders(request.delete_file) Mediator.register_handler(log_empty_folders_handler) @Mediator.handler def log_unused_assets_handler(request: LogUnusedAssetsRequest): ioc_container.maintenance_handler().log_unused_assets() Mediator.register_handler(log_unused_assets_handler) @Mediator.handler def log_redirects_handler(request: LogRedirectsRequest): ioc_container.maintenance_handler().log_redirects() Mediator.register_handler(log_redirects_handler) @Mediator.handler def log_power_of_two_textures_handler(request: LogPowerOfTwoTextures): ioc_container.texture_handler().log_power_of_two_textures() Mediator.register_handler(log_power_of_two_textures_handler) @Mediator.handler def log_textures_x_size_handler(request: LogTexturesXSize): ioc_container.texture_handler().log_textures_x_size(request.sizeOfTexToCheckAgainst) Mediator.register_handler(log_textures_x_size_handler) @Mediator.handler def log_materials_missing_phys_mats_handler(request: LogMaterialsMissingPhysMatRequest): ioc_container.material_handler().log_materials_missing_phys_mats() Mediator.register_handler(log_materials_missing_phys_mats_handler) @Mediator.handler def log_materials_using_translucency_handler(request: LogMaterialsUsingTranslucencyRequest): ioc_container.material_handler().log_materials_using_translucency() Mediator.register_handler(log_materials_using_translucency_handler) @Mediator.handler def log_materials_using_two_sided_handler(request: LogTwoSidedMaterialsRequest): ioc_container.material_handler().log_materials_using_two_sided() Mediator.register_handler(log_materials_using_two_sided_handler) @Mediator.handler def log_foliage_with_no_max_draw_distance_handler(request: LogFoliageWithNoMaxDrawDistanceRequest): ioc_container.foliage_handler().log_foliage_with_no_max_draw_distance() Mediator.register_handler(log_foliage_with_no_max_draw_distance_handler) @Mediator.handler def log_particles_with_no_lods_handler(request: LogParticlesWithNoLodRequest): ioc_container.particle_handler().log_particles_with_no_lods() Mediator.register_handler(log_particles_with_no_lods_handler) @Mediator.handler def log_sound_cue_missing_attenuation_handler(request: LogSoundCueMissingAttenuationRequest): ioc_container.sound_handler().log_sound_cue_missing_attenuation() Mediator.register_handler(log_sound_cue_missing_attenuation_handler) @Mediator.handler def log_sound_cue_missing_concurrency_handler(request: LogSoundCueMissingConcurrencyRequest): ioc_container.sound_handler().log_sound_cue_missing_concurrency() Mediator.register_handler(log_sound_cue_missing_concurrency_handler) @Mediator.handler def log_sound_cue_missing_sound_class_handler(request: LogSoundCueMissingSoundClassRequest): ioc_container.sound_handler().log_sound_cue_missing_sound_class() Mediator.register_handler(log_sound_cue_missing_sound_class_handler) @Mediator.handler def log_static_mesh_with_no_lod_handler(request: LogStaticMeshWithNoLodRequest): ioc_container.static_mesh_handler().log_static_mesh_with_no_lod() Mediator.register_handler(log_static_mesh_with_no_lod_handler) @Mediator.handler def log_static_mesh_with_no_collision_handler(request: LogStaticMeshWithNoCollisionRequest): ioc_container.static_mesh_handler().log_static_mesh_with_no_collision() Mediator.register_handler(log_static_mesh_with_no_collision_handler) @Mediator.handler def log_static_mesh_with_x_materials_handler(request: LogStaticMeshWithXMaterialsRequest): ioc_container.static_mesh_handler().log_static_mesh_with_x_materials(request.numOfMatsToCheckFor) Mediator.register_handler(log_static_mesh_with_x_materials_handler) @Mediator.handler def log_static_mesh_has_multiple_uv_channels_handler(request: LogStaticMeshHasMultipleUvChannelsRequest): ioc_container.static_mesh_handler().log_static_mesh_has_multiple_uv_channels(request.numOfChannelsToCheckFor) Mediator.register_handler(log_static_mesh_has_multiple_uv_channels_handler) @Mediator.handler def log_skel_mesh_with_no_lods_handler(request: LogSkelMeshWithNoLodRequest): ioc_container.skel_mesh_handler().log_skel_mesh_with_no_lods() Mediator.register_handler(log_skel_mesh_with_no_lods_handler) @Mediator.handler def log_skel_mesh_with_x_materials_handler(request: LogSkelMeshWithXMaterialsRequest): ioc_container.skel_mesh_handler().log_skel_mesh_with_x_materials(request.numOfMatsToCheckFor) Mediator.register_handler(log_skel_mesh_with_x_materials_handler) @Mediator.handler def log_skel_mesh_missing_physics_asset_handler(request: LogSkelkMeshMissingPhysicsAssetRequest): ioc_container.skel_mesh_handler().log_skel_mesh_missing_physics_asset() Mediator.register_handler(log_skel_mesh_missing_physics_asset_handler) @Mediator.handler def preview_assets_handler(request: ImportAssetRequest): return ioc_container.import_asset_handler().preview_assets(request.importAssetStruct) Mediator.register_handler(preview_assets_handler) @Mediator.handler def import_assets_handler(request: AssetsSelectedRequest): return ioc_container.import_asset_handler().import_assets(request.assetsToImport) Mediator.register_handler(import_assets_handler) @Mediator.behavior def refresh_behavior(request: object, next): import limeade limeade.refresh() return next()
#!/project/ python3 """ Script to explicitly check which animations are assigned to the character """ import unreal def log_message(message): """Print and log message""" print(message) unreal.log(message) def check_character_animation_assignments(): """Check exactly which animations are assigned to the character""" log_message("=== CHECKING CHARACTER ANIMATION ASSIGNMENTS ===") try: # Load character blueprint bp_path = "/project/" bp = unreal.EditorAssetLibrary.load_asset(bp_path) if not bp: log_message("✗ Could not load character blueprint") return False log_message("✓ Loaded character blueprint") # Get the generated class and default object bp_class = bp.generated_class() if not bp_class: log_message("✗ Blueprint has no generated class") return False default_obj = bp_class.get_default_object() if not default_obj: log_message("✗ Blueprint has no default object") return False log_message("✓ Got character default object") # Check sprite component if hasattr(default_obj, 'sprite'): sprite_comp = default_obj.sprite if sprite_comp: log_message("✓ Character has sprite component") # Check current flipbook assignment current_flipbook = sprite_comp.get_flipbook() if current_flipbook: flipbook_name = current_flipbook.get_name() flipbook_path = current_flipbook.get_path_name() frames = current_flipbook.get_num_frames() log_message(f"✓ Current assigned flipbook: {flipbook_name}") log_message(f" Path: {flipbook_path}") log_message(f" Frames: {frames}") else: log_message("⚠️ No flipbook currently assigned to sprite component") else: log_message("✗ Character sprite component is None") return False else: log_message("✗ Character has no sprite attribute") return False return True except Exception as e: log_message(f"✗ Error checking character assignments: {str(e)}") return False def check_c_plus_plus_animation_paths(): """Verify the animation paths that the C++ code expects""" log_message("\n=== CHECKING C++ EXPECTED ANIMATION PATHS ===") # These are the paths that WarriorCharacter.cpp LoadAnimations() function expects expected_animations = { "IdleAnimation": "/project/", "MoveAnimation": "/project/", "AttackUpAnimation": "/project/", "AttackDownAnimation": "/project/", "AttackSideAnimation": "/project/" } all_exist = True for var_name, path in expected_animations.items(): try: if unreal.EditorAssetLibrary.does_asset_exist(path): anim = unreal.EditorAssetLibrary.load_asset(path) if anim and isinstance(anim, unreal.PaperFlipbook): frames = anim.get_num_frames() fps = anim.get_editor_property("frames_per_second") log_message(f"✓ {var_name}: {path} ({frames} frames @ {fps} FPS)") else: log_message(f"✗ {var_name}: {path} - Not a valid PaperFlipbook") all_exist = False else: log_message(f"✗ {var_name}: {path} - Does not exist") all_exist = False except Exception as e: log_message(f"✗ {var_name}: {path} - Error: {str(e)}") all_exist = False return all_exist def check_all_available_animations(): """List all animations available in the Animations folder""" log_message("\n=== CHECKING ALL AVAILABLE ANIMATIONS ===") try: # Get all assets in the Animations folder animations_path = "/project/" asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() # Get all assets in the animations folder filter = unreal.ARFilter() filter.package_paths = [animations_path] filter.class_names = ["PaperFlipbook"] assets = asset_registry.get_assets(filter) log_message(f"Found {len(assets)} PaperFlipbook assets in /project/:") for asset in assets: asset_name = asset.asset_name asset_path = asset.object_path # Try to load the asset to get more details try: flipbook = unreal.EditorAssetLibrary.load_asset(str(asset_path)) if flipbook: frames = flipbook.get_num_frames() fps = flipbook.get_editor_property("frames_per_second") log_message(f" 📽️ {asset_name}: {frames} frames @ {fps} FPS") else: log_message(f" ❌ {asset_name}: Failed to load") except Exception as e: log_message(f" ❌ {asset_name}: Error loading - {str(e)}") return len(assets) except Exception as e: log_message(f"✗ Error listing animations: {str(e)}") return 0 def test_animation_loading_in_runtime(): """Test if animations can be loaded the same way the C++ code does""" log_message("\n=== TESTING RUNTIME ANIMATION LOADING ===") animation_paths = [ "/project/", "/project/", "/project/", "/project/", "/project/" ] loaded_count = 0 for path in animation_paths: try: # This simulates what LoadObject<UPaperFlipbook> does in C++ flipbook = unreal.EditorAssetLibrary.load_asset(path) if flipbook and isinstance(flipbook, unreal.PaperFlipbook): frames = flipbook.get_num_frames() log_message(f"✓ LoadObject simulation: {path} ({frames} frames)") loaded_count += 1 else: log_message(f"✗ LoadObject simulation failed: {path}") except Exception as e: log_message(f"✗ LoadObject simulation error: {path} - {str(e)}") log_message(f"Runtime loading test: {loaded_count}/{len(animation_paths)} animations loaded successfully") return loaded_count == len(animation_paths) def main(): """Main function to check all animation assignments""" log_message("=" * 80) log_message("CHARACTER ANIMATION ASSIGNMENT VERIFICATION") log_message("=" * 80) # Check 1: What's currently assigned to the character blueprint blueprint_ok = check_character_animation_assignments() # Check 2: Do the C++ expected animations exist cpp_paths_ok = check_c_plus_plus_animation_paths() # Check 3: What animations are available in total available_count = check_all_available_animations() # Check 4: Test runtime loading simulation runtime_ok = test_animation_loading_in_runtime() # Summary log_message("=" * 80) log_message("VERIFICATION SUMMARY:") log_message(f"✓ Character blueprint accessible: {'YES' if blueprint_ok else 'NO'}") log_message(f"✓ C++ expected animations exist: {'YES' if cpp_paths_ok else 'NO'}") log_message(f"✓ Total animations available: {available_count}") log_message(f"✓ Runtime loading simulation: {'YES' if runtime_ok else 'NO'}") if blueprint_ok and cpp_paths_ok and runtime_ok and available_count >= 5: log_message("\n🎉 ALL ANIMATION ASSIGNMENTS VERIFIED!") log_message("✅ Character should have fully working animations in game!") else: log_message("\n❌ Some animation assignment issues detected!") log_message("Check the details above for specific problems.") log_message("=" * 80) if __name__ == "__main__": main()
#coding:utf-8 import unreal import os @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass @unreal.uclass() class GetEditorFilterLibrary(unreal.EditorFilterLibrary): pass @unreal.uclass() class GetEditorUtilityLibrary(unreal.EditorUtilityLibrary): pass # --------------------------------------------------------------------------------------------------------- # def set_two_sided(): # UE里面暂时没有get_folder的选项,只能借助C++,但是对于编译版本的虚幻添加C++蓝图函数有问题 # 所以暂时只能用这种方式来处理双面材质 editorAssetLib = GetEditorAssetLibrary() editorUtil = GetEditorUtilityLibrary() editor_filter_lib = GetEditorFilterLibrary() workingPaths = os.path.dirname(editorUtil.get_selected_assets()[0].get_path_name()) + "/" if not workingPaths: return two_sided_count = 0 allAssets = editorAssetLib.list_assets(workingPaths, False) for asset in allAssets: loaded_asset = unreal.load_asset(asset) try: loaded_asset.get_editor_property("two_sided") except: continue loaded_asset.set_editor_property("two_sided", 1) editorAssetLib.save_asset(asset) two_sided_count += 1 print "materials two sided" print two_sided_count
#Glory. To mankind. import unreal import os import enum import json from math import * from typing import Tuple import re import time #Modify this section according to your desires UnrealNierBaseMaterialDirectory = '/project/' #your game folder UnrealMaterialsDirectory = '/project/' UnrealTexturesDirectory = '/project/' NierTextureDirectoryJpg = "/project/" #dds import not supported by unreal, only jpg or png NierTextureDirectoryPng = "/project/" #dds import not supported by unreal, only jpg or png MaterialsJsonPaths = ["/project/.json", "/project/-004\\materials.json", "/project/-014\\materials.json", ] #MaterialsJsonPaths = ["/project/.json"] #Nier material names. Better not to change NierBaseSimpleMaterialName = "MAT_NierBaseSimple" NierBaseComplexMaterialName = "MAT_NierBaseComplex" NierBaseComplex2MaterialName = "MAT_NierBaseComplex2" NierBaseAlbedoOnlyMaterialName = "MAT_NierBaseAlbedoOnly" NierBaseGrassMaterialName = "MAT_NierGrass" NierBaseLeavesMaterialName = "MAT_NierTreeLeaves" #Base Materials NierBaseSimpleMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseSimpleMaterialName])) NierBaseComplexMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseComplexMaterialName])) NierBaseComplex2MaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseComplex2MaterialName])) NierBaseAlbedoOnlyMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseAlbedoOnlyMaterialName])) NierBaseGrassMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseGrassMaterialName])) NierBaseLeavesMaterialAsset = unreal.EditorAssetLibrary.find_asset_data(unreal.Paths.combine([UnrealNierBaseMaterialDirectory, NierBaseLeavesMaterialName])) #Unreal's libraries AssetTools = unreal.AssetToolsHelpers.get_asset_tools() MaterialEditingLibrary = unreal.MaterialEditingLibrary EditorAssetLibrary = unreal.EditorAssetLibrary class NierMaterialType(enum.Enum): simple = 1 complex = 2 albedoOnly = 3 grass = 4 leaves = 5 complex2 = 6 def setMaterialInstanceTextureParameter(materialInstanceAsset, parameterName, texturePath): if not unreal.EditorAssetLibrary.does_asset_exist(texturePath): unreal.log_warning("Can't find texture: " + texturePath) return False textureAsset = unreal.EditorAssetLibrary.find_asset_data( texturePath ).get_asset() return unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(materialInstanceAsset, parameterName, textureAsset) #importing textures into UE into output path. NierMaterialType and isDecal variables are for defining if given material needs transparent textures. It was made to save disk space. def importTextures(fileNames: list[str], outputDirectory: str, materialType: NierMaterialType, isDecal: bool, pngOnly: bool) -> None: texturePaths = [] if pngOnly: for fileName in fileNames: filePath = os.path.join(NierTextureDirectoryPng, fileName + ".png" ) if os.path.exists(filePath): texturePaths.append(filePath) elif materialType is NierMaterialType.albedoOnly: texturePaths.append(os.path.join(NierTextureDirectoryPng, fileNames[0] + ".jpg" )) elif materialType is NierMaterialType.complex: for i in range(0, 3): texturePaths.append(os.path.join(NierTextureDirectoryPng, fileNames[i] + ".png" )) for i in range(3, len(fileNames)): texturePaths.append(os.path.join(NierTextureDirectoryJpg, fileNames[i] + ".jpg" )) elif materialType is NierMaterialType.simple and isDecal is False: for fileName in fileNames: texturePaths.append(os.path.join(NierTextureDirectoryJpg, fileName + ".jpg" )) elif materialType is NierMaterialType.simple and isDecal is True: texturePaths.append(os.path.join(NierTextureDirectoryPng, fileNames[0] + ".png" )) for i in range(1, len(fileNames)): texturePaths.append(os.path.join(NierTextureDirectoryJpg, fileNames[i] + ".jpg" )) assetImportData = unreal.AutomatedAssetImportData() # set assetImportData attributes assetImportData.destination_path = outputDirectory assetImportData.filenames = texturePaths assetImportData.replace_existing = False AssetTools.import_assets_automated(assetImportData) def getMaterialSlotNames(staticMesh) -> list[str]: staticMeshComponent = unreal.StaticMeshComponent() staticMeshComponent.set_static_mesh(staticMesh) return unreal.StaticMeshComponent.get_material_slot_names(staticMeshComponent) def getNierMaterialType(material: dict[str], materialName: str) -> NierMaterialType: if "weed" in materialName: return NierMaterialType.grass elif "tree" in materialName: return NierMaterialType.leaves elif material.get("g_AlbedoMap") is not None and material.get("g_MaskMap") is None and material.get("g_NormalMap") is None: return NierMaterialType.albedoOnly elif material.get("g_AlbedoMap") is not None and material.get("g_MaskMap") is not None and material.get("g_NormalMap") is not None: return NierMaterialType.simple elif (material.get("g_AlbedoMap1") is not None) and (material.get("g_AlbedoMap2") is not None) and (material.get("g_AlbedoMap3") is not None): return NierMaterialType.complex elif (material.get("g_AlbedoMap1") is not None) and (material.get("g_AlbedoMap2") is not None) and (material.get("g_AlbedoMap3") is None): return NierMaterialType.complex2 def swapToOriginalMaterials() -> None: selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for selectedAsset in selectedAssets: for matIndex in range(0, selectedAsset.get_num_sections(0)): if selectedAsset.get_class().get_name() != "StaticMesh": continue selectedAssetMaterialName = str(selectedAsset.get_material(matIndex).get_name()) assetFolder = unreal.Paths.get_path(selectedAsset.get_path_name()) originalMaterial = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([assetFolder, selectedAssetMaterialName[:-5]])).get_asset() selectedAsset.set_material(matIndex, originalMaterial) def getNierMaterialDict(materialName: str) -> dict: for MaterialsJsonPath in MaterialsJsonPaths: with open(MaterialsJsonPath, 'r') as file: materialsDict = json.load(file) if materialsDict.get(materialName) is not None: return materialsDict[materialName] for dict in materialsDict: strDict = str(dict) if strDict.find(':') != -1: if strDict[strDict.find(':') + 1:] == materialName: return dict return None def getUniqueMats(): mats = [] selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for selectedAsset in selectedAssets: for matIndex in range(0, selectedAsset.get_num_sections(0)): if selectedAsset.get_material(matIndex).get_name() not in mats: mats.append(selectedAsset.get_material(matIndex).get_name()) print(len(mats)) print(mats) def syncNierMaterials(pngOnly: bool) -> None: selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() postfix = "_Inst" #with open(MaterialsJsonPaths, 'r') as file: # materialsDict = json.load(file) materialsFolder = UnrealMaterialsDirectory texturesFolder = UnrealTexturesDirectory if not unreal.EditorAssetLibrary.does_directory_exist(materialsFolder): unreal.EditorAssetLibrary.make_directory(materialsFolder) if not unreal.EditorAssetLibrary.does_directory_exist(texturesFolder): unreal.EditorAssetLibrary.make_directory(texturesFolder) for selectedAsset in selectedAssets: if selectedAsset.get_class().get_name() != "StaticMesh": continue if selectedAsset.get_material(0) is None: continue for matIndex in range(0, selectedAsset.get_num_sections(0)): selectedAssetMaterialName = str(selectedAsset.get_material(matIndex).get_name()) if "_ncl" in selectedAssetMaterialName: selectedAssetMaterialName = selectedAssetMaterialName[0 : selectedAssetMaterialName.find("_ncl")] if postfix in selectedAssetMaterialName: print("Nier material is already assigned, skipping Material in " + selectedAsset.get_name()) continue else: if unreal.EditorAssetLibrary.does_asset_exist(unreal.Paths.combine([materialsFolder, selectedAssetMaterialName + postfix])): #check, if Nier _Inst asset exist if EditorAssetLibrary.find_asset_data(unreal.Paths.combine([materialsFolder, selectedAssetMaterialName + postfix])).get_class().get_name() == "ObjectRedirector": print("Redirector asset found instead of material, skipping " + selectedAsset.get_name()) continue print("Existing Nier material Inst found, assigning " + selectedAssetMaterialName + postfix + " to " + selectedAsset.get_name()) newMaterial = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([materialsFolder, selectedAssetMaterialName + postfix])).get_asset() selectedAsset.set_material(matIndex, newMaterial) else: #if Nier material doesn't exist, create it and import textures, then assign if getNierMaterialDict(selectedAssetMaterialName) is None: unreal.log_warning(selectedAssetMaterialName +" not found in materials.json, skipping asset") continue material = getNierMaterialDict(selectedAssetMaterialName) textures = material['Textures'] newMaterial = AssetTools.create_asset(selectedAssetMaterialName + postfix, materialsFolder, unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) materialType = getNierMaterialType(textures, selectedAssetMaterialName) if materialType == NierMaterialType.simple or materialType == NierMaterialType.grass or materialType == NierMaterialType.leaves: variables = material['Variables'] isDecal = bool(variables['g_Decal']) or "decal" in selectedAssetMaterialName importTextures( [ textures["g_AlbedoMap"], textures["g_MaskMap"], textures["g_NormalMap"], textures["g_DetailNormalMap"] ], texturesFolder, NierMaterialType.simple, isDecal, pngOnly) if materialType == NierMaterialType.simple: parentMaterialAsset = NierBaseSimpleMaterialAsset.get_asset() elif materialType == NierMaterialType.grass: parentMaterialAsset = NierBaseGrassMaterialAsset.get_asset() elif materialType == NierMaterialType.leaves: parentMaterialAsset = NierBaseLeavesMaterialAsset.get_asset() MaterialEditingLibrary.set_material_instance_parent( newMaterial, parentMaterialAsset ) # set parent material setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_MaskMap", unreal.Paths.combine( [ texturesFolder, textures["g_MaskMap"]] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap"] ] ) ) if (EditorAssetLibrary.does_asset_exist(unreal.Paths.combine( [ texturesFolder, textures["g_DetailNormalMap"] ] ) )): MaterialEditingLibrary.set_material_instance_scalar_parameter_value( newMaterial, "bUseDetailMap", 1) setMaterialInstanceTextureParameter(newMaterial, "g_DetailNormalMap", unreal.Paths.combine( [ texturesFolder, textures["g_DetailNormalMap"] ] ) ) elif materialType == NierMaterialType.complex: if "testsea" in selectedAssetMaterialName: continue importTextures( [ textures["g_AlbedoMap1"], textures["g_AlbedoMap2"], textures["g_AlbedoMap3"], textures["g_MaskMap"], textures["g_NormalMap1"], textures["g_NormalMap2"], textures["g_NormalMap3"] ], texturesFolder, NierMaterialType.complex, False, pngOnly) MaterialEditingLibrary.set_material_instance_parent( newMaterial, NierBaseComplexMaterialAsset.get_asset() ) # set parent material setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap1", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap1"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap2", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap2"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap3", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap3"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_MaskMap", unreal.Paths.combine( [ texturesFolder, textures["g_MaskMap"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap1", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap1"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap2", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap2"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap3", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap3"] ] ) ) elif materialType == NierMaterialType.albedoOnly: importTextures( [ textures["g_AlbedoMap"] ], texturesFolder, NierMaterialType.albedoOnly, False, pngOnly) MaterialEditingLibrary.set_material_instance_parent( newMaterial, NierBaseAlbedoOnlyMaterialAsset.get_asset() ) # set parent material if EditorAssetLibrary.does_asset_exist(unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap"] ] ) ): setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap"] ] ) ) else: print("No textures found for " + newMaterial.get_name()) continue elif materialType == NierMaterialType.complex2: importTextures( [ textures["g_AlbedoMap1"], textures["g_AlbedoMap2"], textures["g_MaskMap"], textures["g_NormalMap1"], textures["g_NormalMap2"] ], texturesFolder, NierMaterialType.complex2, False, pngOnly) MaterialEditingLibrary.set_material_instance_parent( newMaterial, NierBaseComplex2MaterialAsset.get_asset() ) # set parent material setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap1", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap1"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_AlbedoMap2", unreal.Paths.combine( [ texturesFolder, textures["g_AlbedoMap2"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_MaskMap", unreal.Paths.combine( [ texturesFolder, textures["g_MaskMap"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap1", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap1"] ] ) ) setMaterialInstanceTextureParameter(newMaterial, "g_NormalMap2", unreal.Paths.combine( [ texturesFolder, textures["g_NormalMap2"] ] ) ) selectedAsset.set_material(matIndex, newMaterial) print("Nier Materials syncing end") def setMobilityForSelectedActors(mobilityType: unreal.ComponentMobility): actors = unreal.EditorLevelLibrary.get_selected_level_actors() for actor in actors: if (actor.get_class().get_name() == "StaticMeshActor"): actor.set_mobility(mobilityType) def test(): selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selectedAssets: if asset.get_class().get_name() == "Material" and "_Inst" not in asset.get_name(): asset.rename(asset.get_name()+"_Inst") def test2(): selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for selectedAsset in selectedAssets: if selectedAsset.get_class().get_name() != "StaticMesh": continue for matIndex in range(0, selectedAsset.get_num_sections(0)): selectedAssetMaterialName = str(selectedAsset.get_material(matIndex).get_name()) assetFolder = unreal.Paths.get_path(selectedAsset.get_path_name()) originalMaterial = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([assetFolder, selectedAssetMaterialName[:-5]])).get_asset() currentMaterial = selectedAsset.get_material(matIndex) if currentMaterial.get_class().get_name() == "MaterialInstanceConstant": if currentMaterial.parent is None: selectedAsset.set_material(matIndex, originalMaterial) # asset.rename(asset.get_name()+"_Inst") #Original Blender script by RaiderB def fixNierMapPosition(): centerX = 11 centerY = 10 hexRadius = 100 hexCenterToEdge = 50 * sqrt(3) def getCoords(x, y) -> Tuple[float, float]: x -= 1 y -= 1 yOff = floor((23 - x) / 2) x -= centerX y -= centerY + yOff return x * hexRadius*1.5, (-y + x%2/2) * hexCenterToEdge * 2 def getCoordsFromName(name: str) -> Tuple[int, int]: x = int(name[2:4]) y = int(name[4:6]) return x, y def fixObjPos(obj): if obj.get_actor_label()[:2] == "g5": obj.set_actor_transform(new_transform=unreal.Transform(location=[0, 0, 0], rotation=[0, 0, 0], scale=[1, 1, 1]), sweep = False, teleport = False) return nX, nY = getCoordsFromName(obj.get_actor_label()) oX, oY = getCoords(nX, nY) obj.set_actor_transform(new_transform=unreal.Transform(location=[oX*100, -(oY*100), 0], rotation=[0, 0, 0], scale=[1, 1, 1]), sweep = False, teleport = False ) print(oX*100, oY*100) selectedAssets = unreal.EditorLevelLibrary.get_selected_level_actors() for obj in selectedAssets: print(obj.get_actor_label()) if not re.match(r"^g\d{5}", obj.get_actor_label()): continue fixObjPos(obj) print("Fixing Nier map position end") def generateSimpleCollision(): selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() step = 100 for i in range(0, len(selectedAssets), step): print(i) time.sleep(3) unreal.EditorStaticMeshLibrary.bulk_set_convex_decomposition_collisions(selectedAssets[i:i + step], 20, 20, 400000) unreal.EditorAssetLibrary.save_loaded_assets(selectedAssets[i:i + step], False) def fixBadConvexCollisionForNierStaticMeshes(pathToLogFile: str, searchMask: str): pathList = [] with open(pathToLogFile, "r") as log_file: err_gen = (st for st in log_file if searchMask in st) for item in err_gen: index = item.find(searchMask) indexEnd = item.find(".", index) path = item[index:indexEnd] if path not in pathList: print(path) pathList.append(path) assets = [] for path in pathList: asset = unreal.EditorAssetLibrary.find_asset_data(path).get_asset() assets.append(asset) unreal.EditorStaticMeshLibrary.remove_collisions(asset) body_setup = asset.get_editor_property('body_setup') collision_trace_flag = unreal.CollisionTraceFlag.CTF_USE_COMPLEX_AS_SIMPLE body_setup.set_editor_property('collision_trace_flag', collision_trace_flag) asset.set_editor_property('body_setup', body_setup) print("Fixed Collisions for " + len(pathList) + " objects") def test3(): selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selectedAssets: unreal.EditorStaticMeshLibrary.remove_collisions(asset) def multipleAttenuationRadiusForSelectedLights(): actors = unreal.EditorLevelLibrary.get_selected_level_actors() for actor in actors: print(actor.get_class().get_name()) if actor.get_class().get_name() == "PointLight": actor.point_light_component.attenuation_radius = 1 def removeLods() -> None: selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selectedAssets: if asset.get_class().get_name() == "StaticMesh": unreal.EditorStaticMeshLibrary.remove_lods(asset) class NierLight: m_flag = 0 m_pos = [0, 0, 0, 0] m_color = [1, 1, 1, 1] m_DirAng = [0, 0, 0] #blender X Y Z = Nier X -Z Y nierLights = [] lightTypes = ['POINT', 'SPOT'] def isUniqueSpot(targetNierLight: NierLight): for nierLight in nierLights: if nierLight.m_pos == targetNierLight.m_pos: return False return True def createLights(gadFilesDirectory: str, bImportPointLights: bool, bImportSpotLights: bool, bSkipDuplicatedLights: bool) -> None: def spawnLight(nierLight: NierLight) -> None: if nierLight.m_flag > 2: print("Unknown light type found, ID = " + str(nierLight.m_flag)) nierLight.m_flag = 0 if nierLight.m_flag == 0: nierLightLocation = unreal.Vector( nierLight.m_pos[0] * 100, nierLight.m_pos[2] * 100, nierLight.m_pos[1] * 100 ) nierLightRotation = [ 0, 0, 0 ] lightObj = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PointLight, nierLightLocation, nierLightRotation) lightObj.set_actor_label("NierLight") lightObj.point_light_component.set_light_color(unreal.LinearColor(r=nierLight.m_color[0], g=nierLight.m_color[1], b=nierLight.m_color[2], a=0.0)) lightObj.point_light_component.set_intensity(nierLight.m_color[3] * 10) lightObj.point_light_component.set_cast_shadows(False) elif nierLight.m_flag == 1: nierLightLocation = unreal.Vector( nierLight.m_pos[0] * 100, nierLight.m_pos[2] * 100, nierLight.m_pos[1] * 100 ) #nierLightRotation = [ nierLight.m_DirAng[0], nierLight.m_DirAng[2], nierLight.m_DirAng[1] ] nierLightRotation = [ 0, 0, 0 ] lightObj = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.SpotLight, nierLightLocation, nierLightRotation) lightObj.set_actor_label("NierLight") lightObj.spot_light_component.set_light_color(unreal.LinearColor(r=nierLight.m_color[0], g=nierLight.m_color[1], b=nierLight.m_color[2], a=0.0)) lightObj.spot_light_component.set_intensity(nierLight.m_color[3] * 10) lightObj.spot_light_component.set_cast_shadows(False) #lightObj.add_actor_world_rotation(delta_rotation=[-90, 0, 0], sweep=False, teleport=True) import xml.etree.ElementTree as ET print("begin") files = os.listdir(gadFilesDirectory) for file in files: if file.endswith(".gad.xml"): tree = ET.parse(os.path.join(gadFilesDirectory, file)) work = tree.find("Work") light = work.find("light") props = light.findall("prop") for prop in props: if prop.attrib["name"] == "m_RoomLightWork": values = prop.findall("value") for value in values: lightProps = value.findall("prop") nierLight = NierLight() for lightProp in lightProps: if lightProp.attrib["name"] == "m_flag": nierLight.m_flag = int(lightProp.text) elif lightProp.attrib["name"] == "m_pos": nierLight.m_pos = [float(num) for num in lightProp.text.split(' ')] elif lightProp.attrib["name"] == "m_color": nierLight.m_color = [float(num) for num in lightProp.text.split(' ')] elif lightProp.attrib["name"] == "m_DirAng": nierLight.m_DirAng = [float(num) for num in lightProp.text.split(' ')] if nierLight.m_pos != [0, 0, 0, 1]: #default light position (?) skip if not isUniqueSpot(nierLight) and bSkipDuplicatedLights: continue if nierLight.m_flag == 0 and bImportPointLights: spawnLight(nierLight) if nierLight.m_flag == 1 and bImportSpotLights: spawnLight(nierLight) if bSkipDuplicatedLights: nierLights.append(nierLight) def cosolidate(): print("1") assetsDirForReplace = "/project/" assetsDirOriginal = "/project/" folders = ["g11517_MainArea", "g11617_MainCorridor", "g11716_Theatre", "g11717_TankArea", "g31418_CityRuins1"] asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() for folder in folders: assetsForReplace = asset_reg.get_assets_by_path(unreal.Paths.combine([assetsDirForReplace, folder])) for asset in assetsForReplace: assetToReplace = asset.get_asset() assetOriginal = EditorAssetLibrary.find_asset_data(unreal.Paths.combine([assetsDirOriginal, folder, assetToReplace.get_name()])).get_asset() #print(unreal.Paths.combine([assetsDirForReplace,folder, assetToReplace.get_name()])) #print(unreal.Paths.combine([assetsDirForReplace,folder, assetToReplace.get_name()])) #print(unreal.Paths.combine([assetsDirOriginal, folder, assetToReplace.get_name()])) print(assetOriginal.get_name()) EditorAssetLibrary.consolidate_assets(assetToReplace, [assetOriginal]) def removeSimpleCollision(): selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selectedAssets: unreal.EditorStaticMeshLibrary.remove_collisions(asset) def exp(): actorsList = unreal.EditorLevelLibrary.get_all_level_actors() actors = [] for actor in actorsList: actorLabel = actor.get_actor_label() actorPos = actor.get_actor_location() if actorLabel == 'Actor' or actorLabel == 'Actor2': actors.append(actor) actors[1].attach_to_actor(actors[0], "NAME_None", unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False) UnrealMapAssetsFolder = "/project/" UnrealMapLayFolder = "/project/" UnrealMapColFolder = "/project/" def importNierClusters(baseDirPath: str, fileNamesToImport: list, levelToLoad: str) -> None: #we receive file path to folder with meshes and lay assets files def importNierCluster(targetFilePath: str) -> bool: #we receive fbx file to import def importMeshes(filePath: str, destinationAssetPath: str, bCreateSingleBlueprint: bool) -> bool: assetName = os.path.basename(filePath).replace(".fbx", '') if unreal.EditorAssetLibrary.does_directory_exist(destinationAssetPath): print("Found destination path: " + destinationAssetPath + ", skipping file") return False else: unreal.EditorAssetLibrary.make_directory(destinationAssetPath) # create asset import data object assetImportData = unreal.AutomatedAssetImportData() # set assetImportData attributes assetImportData.destination_path = destinationAssetPath assetImportData.filenames = [filePath] sceneImportFactory = unreal.FbxSceneImportFactory() assetImportData.factory = sceneImportFactory assetImportData.level_to_load = levelToLoad assetImportData.group_name = assetName fbxImportDataOptions = unreal.FbxSceneImportOptions() sceneImportFactory.scene_import_options = fbxImportDataOptions if bCreateSingleBlueprint: fbxImportDataOptions.set_editor_property('hierarchy_type', unreal.FBXSceneOptionsCreateHierarchyType.FBXSOCHT_CREATE_BLUEPRINT) else: fbxImportDataOptions.set_editor_property('hierarchy_type', unreal.FBXSceneOptionsCreateHierarchyType.FBXSOCHT_CREATE_LEVEL_ACTORS) AssetTools.import_assets_automated(assetImportData) return True res = True assetName = os.path.basename(targetFilePath) filePath = os.path.join(targetFilePath, assetName + ".fbx") if os.path.exists(filePath): destinationAssetPath = unreal.Paths.combine([UnrealMapAssetsFolder, assetName]) res = importMeshes(filePath=filePath, destinationAssetPath=destinationAssetPath, bCreateSingleBlueprint=False) #importedAssets.append(assets) else: print(filePath + " does not exist") return False filePath = os.path.join(targetFilePath, assetName + "-Lay.fbx") if os.path.exists(filePath): destinationAssetPath = unreal.Paths.combine([UnrealMapLayFolder, assetName]) importMeshes(filePath=filePath, destinationAssetPath=destinationAssetPath, bCreateSingleBlueprint=True) #importedAssets.extend(assets) else: print(filePath + " does not exist") return res print("importNierClusters begin") for fileName in fileNamesToImport: targetPath = os.path.join(baseDirPath, fileName) result = importNierCluster(targetFilePath = targetPath) if not result: continue mapClusterParentActorClass = EditorAssetLibrary.find_asset_data("/project/").get_asset() parent = unreal.EditorLevelLibrary.spawn_actor_from_object(mapClusterParentActorClass, unreal.Vector(0, 0, 0), [ 0, 0, 0 ]) parent.set_actor_label(fileName) #root_component actorsList = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actorsList: #actorLabel = actor.get_actor_label() actorLocation = actor.get_actor_location() if actorLocation.x == 0 and actorLocation.y == 0 and actorLocation.z == 0: if "Lay" in actor.get_class().get_name(): actor.root_component.set_mobility(unreal.ComponentMobility.STATIC) actor.attach_to_actor(parent, "NAME_None", unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False) unreal.EditorLevelLibrary.set_selected_level_actors([parent]) fixNierMapPosition() def getImportOptions() -> unreal.FbxImportUI: options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_mesh', True) options.set_editor_property('import_textures', False) options.set_editor_property('import_materials', False) options.set_editor_property('import_as_skeletal', False) # Static Mesh # unreal.FbxMeshImportData options.static_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_uniform_scale', 1.0) # unreal.FbxStaticMeshImportData options.static_mesh_import_data.set_editor_property('combine_meshes', False) options.static_mesh_import_data.set_editor_property('generate_lightmap_u_vs', False) options.static_mesh_import_data.set_editor_property('auto_generate_collision', False) return options def getImportTask(importOptions: unreal.FbxImportUI, destinationPath: str, sourceFileName: str) -> unreal.AssetImportTask: task = unreal.AssetImportTask() task.set_editor_property('automated', True) task.set_editor_property('destination_name', '') task.set_editor_property('destination_path', destinationPath) task.set_editor_property('filename', sourceFileName) task.set_editor_property('replace_existing', True) task.set_editor_property('save', True) task.set_editor_property('options', importOptions) return task #def getAssetsInDirectory(directoryPath: str) -> list: def executeImportTasks(tasks=[]): unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks) imported_asset_paths = [] for task in tasks: for path in task.get_editor_property('imported_object_paths'): imported_asset_paths.append(path) return imported_asset_paths def findActor(actorName: str) -> unreal.Actor: for actor in unreal.EditorLevelLibrary.get_all_level_actors(): if actor.get_actor_label() == actorName: return actor return None def importClusterCollisions(baseDirPath: str, fileNamesToImport: list) -> None: parentActor = None try: for fileName in fileNamesToImport: sourcePath = os.path.join(baseDirPath, fileName, fileName + "-Col.fbx") if not os.path.exists(sourcePath): print("Path does not exist, skipping " + sourcePath) continue assetName = os.path.basename(sourcePath).replace("-Col.fbx", "") parentActor = findActor(assetName) if parentActor is None: print("Parent actor is None, skipping " + sourcePath) continue destinationAssetPath = unreal.Paths.combine([UnrealMapColFolder, assetName + "_Col"]) if not EditorAssetLibrary.does_directory_exist(destinationAssetPath): EditorAssetLibrary.make_directory(destinationAssetPath) importTask = getImportTask(getImportOptions(), destinationAssetPath, sourcePath) importedCollisions = executeImportTasks([importTask]) if len(importedCollisions) == 0: print("No collisions were imported, skipping " + sourcePath) continue parentActor.set_actor_location(unreal.Vector(0, 0, 0), False, False) #importedCollisionWrappers = importCollisionWrapper(destinationAssetPath, len(importedCollisions)) for i in range(len(importedCollisions)): colBaseName = os.path.basename(importedCollisions[i]) colBaseName = colBaseName[0:colBaseName.index('.')] print(colBaseName) colWrapper = importCollisionWrapper(destinationAssetPath, "ColWrapper_" + colBaseName)[0] colWrapperAsset = EditorAssetLibrary.find_asset_data(colWrapper).get_asset() colStaticMesh = EditorAssetLibrary.find_asset_data(importedCollisions[i]).get_asset() colWrapperAsset.set_editor_property('complex_collision_mesh', colStaticMesh) #spawn col actor if "after" not in colBaseName: colWrapperActor = unreal.EditorLevelLibrary.spawn_actor_from_object(colWrapperAsset, unreal.Vector(0, 0, 0), [ 0, 0, 0 ]) #colWrapperActor.set_actor_label("ColWrapper_" + colBaseName) colWrapperActor.attach_to_actor(parentActor, "NAME_None", unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, unreal.AttachmentRule.KEEP_WORLD, False) unreal.EditorLevelLibrary.set_selected_level_actors([parentActor]) fixNierMapPosition() except: if parentActor is not None: unreal.EditorLevelLibrary.set_selected_level_actors([parentActor]) fixNierMapPosition() def getClusterNames(filePath: str) -> list: fileNames = [] with open(filePath, 'r') as file: for line in file.readlines(): fileNames.append(line.replace(' ', '').replace('\n', '')) return fileNames def importCollisionWrapper2(destinationPath: str, amount: int) -> list: filePath = "/project/.fbx" if not unreal.EditorAssetLibrary.does_directory_exist(destinationPath): unreal.EditorAssetLibrary.make_directory(destinationPath) importedFiles = [] for i in range(amount): oldPath = filePath filePath = filePath.replace(os.path.basename(filePath), os.path.basename(filePath).replace(str(i)+".fbx", str(i+1)+".fbx")) print(i) print(filePath) os.rename(oldPath, filePath) #importTasks.append(getImportTask(getImportOptions(), destinationPath, renamedFilePath)) importedPaths = executeImportTasks([getImportTask(getImportOptions(), destinationPath, filePath)]) importedFiles.append(importedPaths[0]) os.rename(filePath, filePath.replace(os.path.basename(filePath), "CollisionWrapper0.fbx")) return importedFiles def importCollisionWrapper(destinationPath: str, collisionFileName: str) -> list: if not unreal.EditorAssetLibrary.does_directory_exist(destinationPath): unreal.EditorAssetLibrary.make_directory(destinationPath) filePath = "/project/.fbx" newFilePath = filePath.replace("CollisionWrapper", collisionFileName) os.rename(filePath, newFilePath) importedPath = executeImportTasks([getImportTask(getImportOptions(), destinationPath, newFilePath)]) os.rename(newFilePath, filePath) return importedPath #print(os.path.basename(os.path.normpath('/project/'))) filePath = "/project/.txt" #filePath = "/project/.txt" #filePath = "/project/.txt" #clusterNames = getClusterNames(filePath) clusterNames = ["g11221", "g11418", "g11419", "g11420"] clusterNames = ["g11221"] gFilesPath = os.path.join("/project/") #levelName = "NierOverworld" #levelName = "NierOverworldBeforePart" #levelName = "NierOverworldAfterPart" #importNierClusters(gFilesPath, clusterNames, levelName) #importClusterCollisions(gFilesPath, clusterNames) #fixNierMapPosition() #importCollisionWrapper("/project/", "testCol2") #dirPath = "/project/.cpk_unpacked\\st1\\nier2blender_extracted\\r130.dat" #createLights(dirPath, True, True, True) #createLights("/project/.cpk_unpacked\\st1\\nier2blender_extracted\\r130.dat") #removeLods() #multipleAttenuationRadiusForSelectedLights() #swapToOriginalMaterials() #setMobilityForSelectedActors(unreal.ComponentMobility.MOVABLE) #swapToOriginalMaterials() #generateSimpleCollision() #getUniqueMats() #test3() #removeSimpleCollision() #fixNierMapPosition() #syncNierMaterials(pngOnly=True)
import os import unreal SYS_ROOT = unreal.SystemLibrary.convert_to_absolute_path( unreal.Paths.project_content_dir()) UNREAL_ROOT = '/Game/' def normalize_path(path): """ Normalize path string to an uniform format that Unreal can read :param path: str. input path of directory/folder :return: str. formatted path """ return os.path.normpath(path).replace('\\', '/') def is_unreal_path(path): """ Determines if path string is an relative Unreal path :param path: str. input path of directory/folder :return: bool. whether the path is an Unreal path """ path = normalize_path(path) return True if UNREAL_ROOT in path else False def is_sys_path(path): """ Determines if path string is an absolute system path :param path: str. input path of directory/folder :return: bool. whether the path is a system path """ path = normalize_path(path) return True if SYS_ROOT in path else False def to_unreal_path(path): """ Format an absolute system path to a relative Unreal path, the path can either be a directory or a file. Example: file: in: "C:/project/.uasset" out: "/project/.MetaHuman" directory: in: "C:/project/" out: "/project/" :param path: str. input path of directory/folder :return: str. path in Unreal format """ if is_unreal_path(path): return normalize_path(path) path = normalize_path(path) if os.path.isfile(path): no_extension_path = os.path.splitext(path)[0] root = no_extension_path.split(SYS_ROOT)[-1] path = os.path.join(UNREAL_ROOT, root) asset = unreal.EditorAssetLibrary.find_asset_data(path).get_asset() return asset.get_path_name() root = path.split(SYS_ROOT)[-1] return os.path.join(UNREAL_ROOT, root) def to_sys_path(path): """ Format a relative unreal path to an absolute system path, the path can either be a directory or a file. Example: file: in: "/project/.MetaHuman" out: "C:/project/.uasset" directory: in: "/project/" out: "C:/project/" :param path: str. input path of directory/folder :return: str. path in system format """ if is_sys_path(path): return normalize_path(path) path = normalize_path(path) # symbol '.' is not allowed in regular Unreal path # thus this determines a path points to an asset not a folder if '.' in path: no_extension_path = os.path.splitext(path)[0] root = no_extension_path.split(UNREAL_ROOT)[-1] return os.path.join(SYS_ROOT, root+'.uasset') root = path.split(UNREAL_ROOT)[-1] return os.path.join(SYS_ROOT, root)
import unreal def check_and_load_asset(source_path:str, target_path:str): loaded_asset:unreal.Object does_exist = unreal.EditorAssetLibrary.does_asset_exist(target_path) if(does_exist): print(target_path + " Asset already exists, loading...") loaded_asset = unreal.EditorAssetLibrary.load_asset(target_path) else: print(target_path + " Asset does not exist, duplicating...") loaded_asset = unreal.EditorAssetLibrary.duplicate_asset(source_path, target_path) return loaded_asset selected_assets = unreal.EditorUtilityLibrary.get_selected_assets() if(len(selected_assets) == 0 or len(selected_assets) >1): print("Please select a single material") exit() selected_asset = selected_assets[0] if(selected_assets[0].get_class().get_name() != "StaticMesh"): print("Please select a static mesh") exit() static_mesh: unreal.StaticMesh = selected_assets[0] mi_cell_path:str = "/project/.MI_Body" selected_sm_path:str = selected_asset.get_path_name() selected_dir_path:str = selected_sm_path.rsplit("/", 1)[0] + "/" print(selected_dir_path) static_materials: list[unreal.StaticMaterial] = static_mesh.get_editor_property("static_materials") new_static_materials: list[unreal.StaticMaterial] = [] for material_interface in static_materials: duplicated_mi_cell_name = str(material_interface.material_slot_name) + "_cell" duplicated_mi_cell_path = selected_dir_path + duplicated_mi_cell_name duplicated_mi_cell = check_and_load_asset(mi_cell_path, duplicated_mi_cell_path) material_interface.set_editor_property("material_interface", duplicated_mi_cell) new_static_materials.append(material_interface) static_mesh.set_editor_property("static_materials", new_static_materials) unreal.EditorAssetLibrary.save_asset(static_mesh.get_path_name()) # outline mi_outline_path:str = "/project/.MI_Chloe_Outline" target_outline_path:str = selected_dir_path + "/MI_Outline" loaded_mi_outline = check_and_load_asset(mi_outline_path, target_outline_path) new_duplicated_static_mesh_path:str = selected_dir_path + "/" + static_mesh.get_name() + "_Outline" loaded_static_mesh = check_and_load_asset(selected_sm_path, new_duplicated_static_mesh_path) static_materials_outline: list[unreal.StaticMaterial] = loaded_static_mesh.get_editor_property("static_materials") new_static_materials_outline: list[unreal.StaticMaterial] = [] for material_interface in static_materials_outline: material_interface.set_editor_property("material_interface", loaded_mi_outline) new_static_materials_outline.append(material_interface) loaded_static_mesh.set_editor_property("static_materials", new_static_materials_outline) unreal.EditorAssetLibrary.save_asset(loaded_static_mesh.get_path_name()) #Mi_Clear mi_clear_path:str = "/project/.MI_Clear" target_mi_clear_path:str = selected_dir_path + "/__MI_Clear" check_and_load_asset(mi_clear_path, target_mi_clear_path) #MI_Eye_shadow mi_eyeshadow:str = "/project/.MI_EyeShadow" target_mi_eyeshadow_path:str = selected_dir_path + "/__MI_EyeShadow" check_and_load_asset(mi_eyeshadow, target_mi_eyeshadow_path)
import unreal import math def spawn_cube(location = unreal.Vector(), rotation = unreal.Rotator()): # Get the system to control the actors editor_actor_subs = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # We want to create a StaticMeshActor actor_class = unreal.StaticMeshActor # Place it in the level static_mesh_actor = editor_actor_subs.spawn_actor_from_class(actor_class, location, rotation) # Load and add the cube to it static_mesh = unreal.EditorAssetLibrary.load_asset("/project/.Cube") static_mesh_actor.static_mesh_component.set_static_mesh(static_mesh) def run(): cube_count = 30 circle_radius = 1000 circle_center = unreal.Vector(0, 0, 0) for i in range(cube_count): circle_x_location = circle_radius * math.cos(math.radians(i * 360 / cube_count)) circle_y_location = circle_radius * math.sin(math.radians(i * 360 / cube_count)) location = unreal.Vector(circle_x_location, circle_y_location, 0) location_to_circle_center = location - circle_center rotation = location_to_circle_center.quaternion().rotator() spawn_cube(location, rotation) with unreal.ScopedEditorTransaction("Place cubes in a circle") as trans: run()
import unreal selected_assets: list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets() loaded_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) ## set sm materials selected_sm:unreal.SkeletalMesh = selected_assets[0] sm_mats_length = len(selected_sm.materials) # set data asset destination_path_array = selected_sm.get_path_name().split('/') new_da_path = '/'.join(destination_path_array[:-1]) + '/DA_' + selected_sm.get_name() does_da_exist = loaded_subsystem.does_asset_exist(new_da_path) if(does_da_exist == False): ## set data asset target_da_path = "/project/" ## duplicate and save loaded_subsystem.duplicate_asset(target_da_path, new_da_path) loaded_subsystem.save_asset(new_da_path) blueprint_asset = unreal.EditorAssetLibrary.load_asset(new_da_path) sm_path = selected_sm.get_path_name() sm_folder = '/'.join(sm_path.split('/')[:-1]) outlines_folder_path = sm_folder + '/project/' + selected_sm.get_name() + '_Outline_Vambo' outline_material = unreal.load_asset(outlines_folder_path) ### set outline materials to data asset property_info = {'BasicOutlineMaterial': outline_material} blueprint_asset.set_editor_properties(property_info) loaded_subsystem.save_asset(new_da_path)
import unreal # print("ok") class ueScreenShot(): frameRange = None frame = 1 sequeue = None ass = "" def createScreenshot(self): # unreal.SoftObjectPath('/project/.NewLevelSequence') # level = unreal.load_asset('/project/.NewLevelSequence', unreal.LevelSequence) # sequeue = unreal.LevelSequencePlaybackController() # sequeue.set_active_level_sequence(level) if self.frame > self.frameRange[-1]: return None self.sequeue.jump_to_playback_position(unreal.FrameNumber(self.frame)) unreal.AutomationLibrary.take_high_res_screenshot(3840, 2560, "test_shot_{:0>4d}.png".format(self.frame)) self.frame = self.frame + 1 def setRange(self): # unreal.SoftObjectPath('/project/.NewLevelSequence') level = unreal.load_asset(self.ass, unreal.LevelSequence) self.sequeue = unreal.LevelSequencePlaybackController() self.sequeue.set_active_level_sequence(level) self.frameRange = range(level.get_playback_start(), level.get_playback_end(), 1) self.frame = self.frameRange[1] @staticmethod def getAss(_ass): ueScreenShot.ass = "'{}'".format(_ass.split("'")[-2]) ueScreenShotObj = ueScreenShot()
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) #print(sk.bone_tree) # #kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss"); #kk.name = "" #kk.type = 1; #print(h_mod.get_bone(kk)) #print(h_mod.get_elements()) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] #for e in reversed(h_mod.get_elements()): # if (e.type != unreal.RigElementType.BONE): # h_mod.remove_element(e) for e in h_mod.get_elements(): if (e.type == unreal.RigElementType.BONE): modelBoneListAll.append(e) modelBoneNameList.append("{}".format(e.name).lower()) # else: # h_mod.remove_element(e) print(modelBoneListAll[0]) #exit #print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode")) #print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index")) #unreal.select #vrmlist = unreal.VrmAssetListObject #vrmmeta = vrmlist.vrm_meta_object #print(vrmmeta.humanoid_bone_table) #selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() #selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class()) #static_meshes = np.array([]) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv #v:unreal.VrmAssetListObject = None #if (True): # a = reg.get_assets_by_path(args.vrm) # a = reg.get_all_assets(); # for aa in a: # if (aa.get_editor_property("object_path") == args.vrm): # v:unreal.VrmAssetListObject = aa #v = unreal.VrmAssetListObject.cast(v) #print(v) #unreal.VrmAssetListObject.vrm_meta_object #meta = v.vrm_meta_object() #meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class()) print (meta) #print(meta[0].humanoid_bone_table) ### モデル骨のうち、ヒューマノイドと同じもの ### 上の変換テーブル humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() ### modelBoneでループ #for bone_h in meta.humanoid_bone_table: for bone_h_base in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == bone_h_base): bone_h = e; break; print("{}".format(bone_h)) if (bone_h==None): continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m.lower()) except: i = -1 if (i < 0): continue if ("{}".format(bone_h).lower() == "upperchest"): continue; humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower() if ("{}".format(bone_h).lower() == "chest"): #upperchestがあれば、これの次に追加 bh = 'upperchest' print("upperchest: check begin") for e in meta.humanoid_bone_table: if ("{}".format(e).lower() != 'upperchest'): continue bm = "{}".format(meta.humanoid_bone_table[e]).lower() if (bm == ''): continue humanoidBoneToModel[bh] = bm humanoidBoneParentList[10] = "upperchest" humanoidBoneParentList[12] = "upperchest" humanoidBoneParentList[13] = "upperchest" print("upperchest: find and insert parent") break print("upperchest: check end") parent=None control_to_mat={None:None} count = 0 ### 骨名からControlへのテーブル name_to_control = {"dummy_for_table" : None} print("loop begin") ###### root key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'root_s') space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space('root_s', space_type=unreal.RigSpaceType.SPACE) else: space = key key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c') control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control('root_c', space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) else: control = key h_mod.reparent_element(control, space) parent = control cc = h_mod.get_control(control) cc.set_editor_property('gizmo_visible', False) h_mod.set_control(cc) for ee in humanoidBoneToModel: element = humanoidBoneToModel[ee] humanoidBone = ee modelBoneNameSmall = element # 対象の骨 #modelBoneNameSmall = "{}".format(element.name).lower() #humanoidBone = modelBoneToHumanoid[modelBoneNameSmall]; boneNo = humanoidBoneList.index(humanoidBone) print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo])) # 親 if count != 0: parent = name_to_control[humanoidBoneParentList[boneNo]] # 階層作成 bIsNew = False name_s = "{}_s".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.SPACE, name_s) space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space(name_s, space_type=unreal.RigSpaceType.SPACE) bIsNew = True else: space = key name_c = "{}_c".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) #h_mod.get_control(control).gizmo_transform = gizmo_trans if (24<=boneNo & boneNo<=53): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1]) else: gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) if (17<=boneNo & boneNo<=18): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) cc = h_mod.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_mod.set_control(cc) #h_mod.set_control_value_transform(control,gizmo_trans) bIsNew = True else: control = key if (bIsNew == True): h_mod.reparent_element(control, space) # テーブル登録 name_to_control[humanoidBone] = control print(humanoidBone) # ロケータ 座標更新 # 不要な上層階層を考慮 gTransform = h_mod.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)]) if count == 0: bone_initial_transform = gTransform else: #bone_initial_transform = h_mod.get_initial_transform(element) bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse()) h_mod.set_initial_transform(space, bone_initial_transform) control_to_mat[control] = gTransform # 階層修正 h_mod.reparent_element(space, parent) count += 1 if (count >= 500): break
import os.path import unreal import json with open("C:/project/ Projects/project/.json", "r") as f: migration_data = json.load(f) game_folder = "/project/" for k, v in migration_data.items(): src = os.path.join(game_folder, k.replace(".uasset", "")) target = os.path.join(game_folder, v.replace(".uasset", "")) unreal.EditorAssetLibrary.rename_asset(src, target)
import unreal dirAnimBP = '/project/' dirNew = dirAnimBP.replace('CH_M_NA_10','Master') dirAnimBP = str(dirAnimBP) print(dirAnimBP.replace('CH_M_NA_10','Master')) bpAnimBP = unreal.EditorAssetLibrary.load_asset(dirAnimBP) bpCloned = unreal.EditorAssetLibrary.duplicate_asset(dirAnimBP,dirNew) #bpCloned1 = unreal.EditorAssetLibrary.load_asset(dirNew) A = bpCloned.get_editor_property("target_skeleton") #bpCloneAnimBP = unreal.EditorAssetLibrary.load_asset(bpAnimBP) #for i in bs_assets_list: # num_sample = i.get_editor_property("sample_data") # num_count = len(num_sample) # if num_count == 0: # print (num_count)
import unreal import sys asset_path = sys.argv[1] asset_property = sys.argv[2] asset_value = sys.argv[3] is_texture = sys.argv[4] in_scene = sys.argv[5] asset_class = sys.argv[6] method = sys.argv[7] world = unreal.EditorLevelLibrary.get_editor_world if is_texture == "1": # Load texture value = unreal.EditorAssetLibrary.load_asset(asset_value) else: value = asset_value if in_scene == "0": # print(in_scene) # Asset to be loaded from Editor Content # from that, get the class default object ( the actual template for the blueprint ) blueprint_generated = unreal.EditorAssetLibrary.load_blueprint_class(asset_path) my_act = unreal.get_default_object(blueprint_generated) if in_scene == "1": lst_actors = unreal.EditorLevelLibrary.get_all_level_actors() for act in lst_actors: act_label = act.get_actor_label() if asset_class in act_label: my_act = act if asset_property != "/": my_act.set_editor_property(asset_property,value) if method == "import_tile": my_act.import_tile(my_act) if method == "match_landscape_size": my_act.match_landscape_size(my_act) # print('tets') # if(len(method) == 0): # print(method) # Asset to be loaded from Scene # print(asset_path) # asset = unreal.find_object(None, asset_path) # print (type(asset)) # blueprint_class_default = unreal.get_default_object(asset) # print (type(blueprint_class_default)) # print(dir(blueprint_class_default)) # blueprint_class_default.set_editor_property('height_map',value) # m = unreal.find_object("EarthLandscapeClip") # m = unreal.load_object(Blueprint, asset_path) # act = unreal.load_class(Class, ' + asset_class + ') # print(act) # # set or get properties # blueprint_class_default.set_editor_property(asset_property, value) # unreal.EditorAssetLibrary.save_asset(asset_path)
from threading import Thread import pandas as pd import unreal x = [] y = [] time = [] def reading_data(file_name): df = pd.read_csv('/project/.txt') global x, y, time x = df["x [mm]"].tolist() y = df["y [mm]"].tolist() time = df["Time Step [s]"].tolist() @unreal.uclass() class GetMovementData(unreal.BlueprintFunctionLibrary): @unreal.ufunction(static = True, params =[], ret = bool) def GenerateData(): reading_data("None") @unreal.ufunction(static = True, params = [], ret = unreal.Array(float)) def GetXPositions(): global x new_x = [round(num / 10, 2) for num in x] return new_x @unreal.ufunction(static = True, params = [], ret = unreal.Array(float)) def GetYPositions(): global y new_y = [round(num / 10, 2) for num in y] return new_y @unreal.ufunction(static = True, params = [], ret = unreal.Array(float)) def GetTime(): global time new_time = [round(num, 4) for num in time] return new_time
# -*- coding: utf-8 -*- """Loader for layouts.""" import json import collections from pathlib import Path import unreal from unreal import ( EditorAssetLibrary, EditorLevelLibrary, EditorLevelUtils, AssetToolsHelpers, FBXImportType, MovieSceneLevelVisibilityTrack, MovieSceneSubTrack, LevelSequenceEditorBlueprintLibrary as LevelSequenceLib, ) import ayon_api from ayon_core.pipeline import ( discover_loader_plugins, loaders_from_representation, load_container, get_representation_path, AYON_CONTAINER_ID, get_current_project_name, ) from ayon_core.pipeline.context_tools import get_current_project_folder from ayon_core.settings import get_current_project_settings from ayon_core.hosts.unreal.api import plugin from ayon_core.hosts.unreal.api.pipeline import ( generate_sequence, set_sequence_hierarchy, create_container, imprint, ls, ) class LayoutLoader(plugin.Loader): """Load Layout from a JSON file""" product_types = {"layout"} representations = ["json"] label = "Load Layout" icon = "code-fork" color = "orange" ASSET_ROOT = "/project/" def _get_asset_containers(self, path): ar = unreal.AssetRegistryHelpers.get_asset_registry() asset_content = EditorAssetLibrary.list_assets( path, recursive=True) asset_containers = [] # Get all the asset containers for a in asset_content: obj = ar.get_asset_by_object_path(a) if obj.get_asset().get_class().get_name() == 'AyonAssetContainer': asset_containers.append(obj) return asset_containers @staticmethod def _get_fbx_loader(loaders, family): name = "" if family == 'rig': name = "SkeletalMeshFBXLoader" elif family == 'model': name = "StaticMeshFBXLoader" elif family == 'camera': name = "CameraLoader" if name == "": return None for loader in loaders: if loader.__name__ == name: return loader return None @staticmethod def _get_abc_loader(loaders, family): name = "" if family == 'rig': name = "SkeletalMeshAlembicLoader" elif family == 'model': name = "StaticMeshAlembicLoader" if name == "": return None for loader in loaders: if loader.__name__ == name: return loader return None def _transform_from_basis(self, transform, basis): """Transform a transform from a basis to a new basis.""" # Get the basis matrix basis_matrix = unreal.Matrix( basis[0], basis[1], basis[2], basis[3] ) transform_matrix = unreal.Matrix( transform[0], transform[1], transform[2], transform[3] ) new_transform = ( basis_matrix.get_inverse() * transform_matrix * basis_matrix) return new_transform.transform() def _process_family( self, assets, class_name, transform, basis, sequence, inst_name=None ): ar = unreal.AssetRegistryHelpers.get_asset_registry() actors = [] bindings = [] for asset in assets: obj = ar.get_asset_by_object_path(asset).get_asset() if obj.get_class().get_name() == class_name: t = self._transform_from_basis(transform, basis) actor = EditorLevelLibrary.spawn_actor_from_object( obj, t.translation ) actor.set_actor_rotation(t.rotation.rotator(), False) actor.set_actor_scale3d(t.scale3d) if class_name == 'SkeletalMesh': skm_comp = actor.get_editor_property( 'skeletal_mesh_component') skm_comp.set_bounds_scale(10.0) actors.append(actor) if sequence: binding = None for p in sequence.get_possessables(): if p.get_name() == actor.get_name(): binding = p break if not binding: binding = sequence.add_possessable(actor) bindings.append(binding) return actors, bindings def _import_animation( self, asset_dir, path, instance_name, skeleton, actors_dict, animation_file, bindings_dict, sequence ): anim_file = Path(animation_file) anim_file_name = anim_file.with_suffix('') anim_path = f"{asset_dir}/animations/{anim_file_name}" folder_entity = get_current_project_folder() # Import animation task = unreal.AssetImportTask() task.options = unreal.FbxImportUI() task.set_editor_property( 'filename', str(path.with_suffix(f".{animation_file}"))) task.set_editor_property('destination_path', anim_path) task.set_editor_property( 'destination_name', f"{instance_name}_animation") task.set_editor_property('replace_existing', False) task.set_editor_property('automated', True) 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', FBXImportType.FBXIT_SKELETAL_MESH) task.options.set_editor_property( 'mesh_type_to_import', 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.set_editor_property('skeleton', skeleton) 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) AssetToolsHelpers.get_asset_tools().import_asset_tasks([task]) asset_content = unreal.EditorAssetLibrary.list_assets( anim_path, recursive=False, include_folder=False ) animation = None for a in asset_content: unreal.EditorAssetLibrary.save_asset(a) imported_asset_data = unreal.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: actor = None if actors_dict.get(instance_name): for a in actors_dict.get(instance_name): if a.get_class().get_name() == 'SkeletalMeshActor': actor = a break 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) if sequence: # Add animation to the sequencer bindings = bindings_dict.get(instance_name) ar = unreal.AssetRegistryHelpers.get_asset_registry() for binding in bindings: tracks = binding.get_tracks() track = None track = tracks[0] if tracks else binding.add_track( unreal.MovieSceneSkeletalAnimationTrack) sections = track.get_sections() section = None if not sections: section = track.add_section() else: section = sections[0] sec_params = section.get_editor_property('params') curr_anim = sec_params.get_editor_property('animation') if curr_anim: # Checks if the animation path has a container. # If it does, it means that the animation is # already in the sequencer. anim_path = str(Path( curr_anim.get_path_name()).parent ).replace('\\', '/') _filter = unreal.ARFilter( class_names=["AyonAssetContainer"], package_paths=[anim_path], recursive_paths=False) containers = ar.get_assets(_filter) if len(containers) > 0: return section.set_range( sequence.get_playback_start(), sequence.get_playback_end()) sec_params = section.get_editor_property('params') sec_params.set_editor_property('animation', animation) def _get_repre_entities_by_version_id(self, data): version_ids = { element.get("version") for element in data if element.get("representation") } version_ids.discard(None) output = collections.defaultdict(list) if not version_ids: return output project_name = get_current_project_name() repre_entities = ayon_api.get_representations( project_name, representation_names={"fbx", "abc"}, version_ids=version_ids, fields={"id", "versionId", "name"} ) for repre_entity in repre_entities: version_id = repre_entity["versionId"] output[version_id].append(repre_entity) return output def _process(self, lib_path, asset_dir, sequence, repr_loaded=None): ar = unreal.AssetRegistryHelpers.get_asset_registry() with open(lib_path, "r") as fp: data = json.load(fp) all_loaders = discover_loader_plugins() if not repr_loaded: repr_loaded = [] path = Path(lib_path) skeleton_dict = {} actors_dict = {} bindings_dict = {} loaded_assets = [] repre_entities_by_version_id = self._get_repre_entities_by_version_id( data ) for element in data: repre_id = None repr_format = None if element.get('representation'): version_id = element.get("version") repre_entities = repre_entities_by_version_id[version_id] if not repre_entities: self.log.error( f"No valid representation found for version" f" {version_id}") continue repre_entity = repre_entities[0] repre_id = repre_entity["id"] repr_format = repre_entity["name"] # This is to keep compatibility with old versions of the # json format. elif element.get('reference_fbx'): repre_id = element.get('reference_fbx') repr_format = 'fbx' elif element.get('reference_abc'): repre_id = element.get('reference_abc') repr_format = 'abc' # If reference is None, this element is skipped, as it cannot be # imported in Unreal if not repre_id: continue instance_name = element.get('instance_name') skeleton = None if repre_id not in repr_loaded: repr_loaded.append(repre_id) product_type = element.get("product_type") if product_type is None: product_type = element.get("family") loaders = loaders_from_representation( all_loaders, repre_id) loader = None if repr_format == 'fbx': loader = self._get_fbx_loader(loaders, product_type) elif repr_format == 'abc': loader = self._get_abc_loader(loaders, product_type) if not loader: self.log.error( f"No valid loader found for {repre_id}") continue options = { # "asset_dir": asset_dir } assets = load_container( loader, repre_id, namespace=instance_name, options=options ) container = None for asset in assets: obj = ar.get_asset_by_object_path(asset).get_asset() if obj.get_class().get_name() == 'AyonAssetContainer': container = obj if obj.get_class().get_name() == 'Skeleton': skeleton = obj loaded_assets.append(container.get_path_name()) instances = [ item for item in data if ((item.get('version') and item.get('version') == element.get('version')) or item.get('reference_fbx') == repre_id or item.get('reference_abc') == repre_id)] for instance in instances: # transform = instance.get('transform') transform = instance.get('transform_matrix') basis = instance.get('basis') inst = instance.get('instance_name') actors = [] if product_type == 'model': actors, _ = self._process_family( assets, 'StaticMesh', transform, basis, sequence, inst ) elif product_type == 'rig': actors, bindings = self._process_family( assets, 'SkeletalMesh', transform, basis, sequence, inst ) actors_dict[inst] = actors bindings_dict[inst] = bindings if skeleton: skeleton_dict[repre_id] = skeleton else: skeleton = skeleton_dict.get(repre_id) animation_file = element.get('animation') if animation_file and skeleton: self._import_animation( asset_dir, path, instance_name, skeleton, actors_dict, animation_file, bindings_dict, sequence) return loaded_assets @staticmethod def _remove_family(assets, components, class_name, prop_name): ar = unreal.AssetRegistryHelpers.get_asset_registry() objects = [] for a in assets: obj = ar.get_asset_by_object_path(a) if obj.get_asset().get_class().get_name() == class_name: objects.append(obj) for obj in objects: for comp in components: if comp.get_editor_property(prop_name) == obj.get_asset(): comp.get_owner().destroy_actor() def _remove_actors(self, path): asset_containers = self._get_asset_containers(path) # Get all the static and skeletal meshes components in the level components = EditorLevelLibrary.get_all_level_actors_components() static_meshes_comp = [ c for c in components if c.get_class().get_name() == 'StaticMeshComponent'] skel_meshes_comp = [ c for c in components if c.get_class().get_name() == 'SkeletalMeshComponent'] # For all the asset containers, get the static and skeletal meshes. # Then, check the components in the level and destroy the matching # actors. for asset_container in asset_containers: package_path = asset_container.get_editor_property('package_path') family = EditorAssetLibrary.get_metadata_tag( asset_container.get_asset(), "family") assets = EditorAssetLibrary.list_assets( str(package_path), recursive=False) if family == 'model': self._remove_family( assets, static_meshes_comp, 'StaticMesh', 'static_mesh') elif family == 'rig': self._remove_family( assets, skel_meshes_comp, 'SkeletalMesh', 'skeletal_mesh') def load(self, context, name, namespace, options): """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. options (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 """ data = get_current_project_settings() create_sequences = data["unreal"]["level_sequences_for_layouts"] # Create directory for asset and Ayon container folder_entity = context["folder"] folder_path = folder_entity["path"] hierarchy = folder_path.lstrip("/").split("/") # Remove folder name folder_name = hierarchy.pop(-1) root = self.ASSET_ROOT hierarchy_dir = root hierarchy_dir_list = [] for h in hierarchy: hierarchy_dir = f"{hierarchy_dir}/{h}" hierarchy_dir_list.append(hierarchy_dir) suffix = "_CON" asset_name = f"{folder_name}_{name}" if folder_name else name tools = unreal.AssetToolsHelpers().get_asset_tools() asset_dir, container_name = tools.create_unique_asset_name( "{}/{}/{}".format(hierarchy_dir, folder_name, name), suffix="" ) container_name += suffix EditorAssetLibrary.make_directory(asset_dir) master_level = None shot = None sequences = [] level = f"{asset_dir}/{folder_name}_map.{folder_name}_map" EditorLevelLibrary.new_level(f"{asset_dir}/{folder_name}_map") if create_sequences: # Create map for the shot, and create hierarchy of map. If the # maps already exist, we will use them. if hierarchy: h_dir = hierarchy_dir_list[0] h_asset = hierarchy[0] master_level = f"{h_dir}/{h_asset}_map.{h_asset}_map" if not EditorAssetLibrary.does_asset_exist(master_level): EditorLevelLibrary.new_level(f"{h_dir}/{h_asset}_map") if master_level: EditorLevelLibrary.load_level(master_level) EditorLevelUtils.add_level_to_world( EditorLevelLibrary.get_editor_world(), level, unreal.LevelStreamingDynamic ) EditorLevelLibrary.save_all_dirty_levels() EditorLevelLibrary.load_level(level) # Get all the sequences in the hierarchy. It will create them, if # they don't exist. frame_ranges = [] for (h_dir, h) in zip(hierarchy_dir_list, hierarchy): root_content = EditorAssetLibrary.list_assets( h_dir, recursive=False, include_folder=False) existing_sequences = [ EditorAssetLibrary.find_asset_data(asset) for asset in root_content if EditorAssetLibrary.find_asset_data( asset).get_class().get_name() == 'LevelSequence' ] if not existing_sequences: sequence, frame_range = generate_sequence(h, h_dir) sequences.append(sequence) frame_ranges.append(frame_range) else: for e in existing_sequences: sequences.append(e.get_asset()) frame_ranges.append(( e.get_asset().get_playback_start(), e.get_asset().get_playback_end())) shot = tools.create_asset( asset_name=folder_name, package_path=asset_dir, asset_class=unreal.LevelSequence, factory=unreal.LevelSequenceFactoryNew() ) # sequences and frame_ranges have the same length for i in range(0, len(sequences) - 1): set_sequence_hierarchy( sequences[i], sequences[i + 1], frame_ranges[i][1], frame_ranges[i + 1][0], frame_ranges[i + 1][1], [level]) project_name = get_current_project_name() folder_attributes = ( ayon_api.get_folder_by_path(project_name, folder_path)["attrib"] ) shot.set_display_rate( unreal.FrameRate(folder_attributes.get("fps"), 1.0)) shot.set_playback_start(0) shot.set_playback_end( folder_attributes.get('clipOut') - folder_attributes.get('clipIn') + 1 ) if sequences: set_sequence_hierarchy( sequences[-1], shot, frame_ranges[-1][1], folder_attributes.get('clipIn'), folder_attributes.get('clipOut'), [level]) EditorLevelLibrary.load_level(level) path = self.filepath_from_context(context) loaded_assets = self._process(path, asset_dir, shot) for s in sequences: EditorAssetLibrary.save_asset(s.get_path_name()) EditorLevelLibrary.save_current_level() # Create Asset Container create_container( container=container_name, path=asset_dir) data = { "schema": "ayon:container-2.0", "id": AYON_CONTAINER_ID, "asset": folder_name, "folder_path": folder_path, "namespace": asset_dir, "container_name": container_name, "asset_name": asset_name, "loader": str(self.__class__.__name__), "representation": context["representation"]["id"], "parent": context["representation"]["versionId"], "family": context["product"]["productType"], "loaded_assets": loaded_assets } imprint( "{}/{}".format(asset_dir, container_name), data) save_dir = hierarchy_dir_list[0] if create_sequences else asset_dir asset_content = EditorAssetLibrary.list_assets( save_dir, recursive=True, include_folder=False) for a in asset_content: EditorAssetLibrary.save_asset(a) if master_level: EditorLevelLibrary.load_level(master_level) return asset_content def update(self, container, context): data = get_current_project_settings() create_sequences = data["unreal"]["level_sequences_for_layouts"] ar = unreal.AssetRegistryHelpers.get_asset_registry() curr_level_sequence = LevelSequenceLib.get_current_level_sequence() curr_time = LevelSequenceLib.get_current_time() is_cam_lock = LevelSequenceLib.is_camera_cut_locked_to_viewport() editor_subsystem = unreal.UnrealEditorSubsystem() vp_loc, vp_rot = editor_subsystem.get_level_viewport_camera_info() root = "/project/" asset_dir = container.get('namespace') folder_entity = context["folder"] repre_entity = context["representation"] hierarchy = folder_entity["path"].lstrip("/").split("/") first_parent_name = hierarchy[0] sequence = None master_level = None if create_sequences: h_dir = f"{root}/{first_parent_name}" h_asset = first_parent_name master_level = f"{h_dir}/{h_asset}_map.{h_asset}_map" filter = unreal.ARFilter( class_names=["LevelSequence"], package_paths=[asset_dir], recursive_paths=False) sequences = ar.get_assets(filter) sequence = sequences[0].get_asset() prev_level = None if not master_level: curr_level = unreal.LevelEditorSubsystem().get_current_level() curr_level_path = curr_level.get_outer().get_path_name() # If the level path does not start with "/Game/", the current # level is a temporary, unsaved level. if curr_level_path.startswith("/Game/"): prev_level = curr_level_path # Get layout level filter = unreal.ARFilter( class_names=["World"], package_paths=[asset_dir], recursive_paths=False) levels = ar.get_assets(filter) layout_level = levels[0].get_asset().get_path_name() EditorLevelLibrary.save_all_dirty_levels() EditorLevelLibrary.load_level(layout_level) # Delete all the actors in the level actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: unreal.EditorLevelLibrary.destroy_actor(actor) if create_sequences: EditorLevelLibrary.save_current_level() EditorAssetLibrary.delete_directory(f"{asset_dir}/animations/") source_path = get_representation_path(repre_entity) loaded_assets = self._process(source_path, asset_dir, sequence) data = { "representation": repre_entity["id"], "parent": repre_entity["versionId"], "loaded_assets": loaded_assets, } imprint( "{}/{}".format(asset_dir, container.get('container_name')), data) EditorLevelLibrary.save_current_level() save_dir = f"{root}/{first_parent_name}" if create_sequences else asset_dir asset_content = EditorAssetLibrary.list_assets( save_dir, recursive=True, include_folder=False) for a in asset_content: EditorAssetLibrary.save_asset(a) if master_level: EditorLevelLibrary.load_level(master_level) elif prev_level: EditorLevelLibrary.load_level(prev_level) if curr_level_sequence: LevelSequenceLib.open_level_sequence(curr_level_sequence) LevelSequenceLib.set_current_time(curr_time) LevelSequenceLib.set_lock_camera_cut_to_viewport(is_cam_lock) editor_subsystem.set_level_viewport_camera_info(vp_loc, vp_rot) def remove(self, container): """ Delete the layout. First, check if the assets loaded with the layout are used by other layouts. If not, delete the assets. """ data = get_current_project_settings() create_sequences = data["unreal"]["level_sequences_for_layouts"] root = "/project/" path = Path(container.get("namespace")) containers = ls() layout_containers = [ c for c in containers if (c.get('asset_name') != container.get('asset_name') and c.get('family') == "layout")] # Check if the assets have been loaded by other layouts, and deletes # them if they haven't. for asset in eval(container.get('loaded_assets')): layouts = [ lc for lc in layout_containers if asset in lc.get('loaded_assets')] if not layouts: EditorAssetLibrary.delete_directory(str(Path(asset).parent)) # Delete the parent folder if there aren't any more # layouts in it. asset_content = EditorAssetLibrary.list_assets( str(Path(asset).parent.parent), recursive=False, include_folder=True ) if len(asset_content) == 0: EditorAssetLibrary.delete_directory( str(Path(asset).parent.parent)) master_sequence = None master_level = None sequences = [] if create_sequences: # Remove the Level Sequence from the parent. # We need to traverse the hierarchy from the master sequence to # find the level sequence. namespace = container.get('namespace').replace(f"{root}/", "") ms_asset = namespace.split('/')[0] ar = unreal.AssetRegistryHelpers.get_asset_registry() _filter = unreal.ARFilter( class_names=["LevelSequence"], package_paths=[f"{root}/{ms_asset}"], recursive_paths=False) sequences = ar.get_assets(_filter) master_sequence = sequences[0].get_asset() _filter = unreal.ARFilter( class_names=["World"], package_paths=[f"{root}/{ms_asset}"], recursive_paths=False) levels = ar.get_assets(_filter) master_level = levels[0].get_asset().get_path_name() sequences = [master_sequence] parent = None for s in sequences: tracks = s.get_master_tracks() subscene_track = None visibility_track = None for t in tracks: if t.get_class() == MovieSceneSubTrack.static_class(): subscene_track = t if (t.get_class() == MovieSceneLevelVisibilityTrack.static_class()): visibility_track = t if subscene_track: sections = subscene_track.get_sections() for ss in sections: if (ss.get_sequence().get_name() == container.get('asset')): parent = s subscene_track.remove_section(ss) break sequences.append(ss.get_sequence()) # Update subscenes indexes. i = 0 for ss in sections: ss.set_row_index(i) i += 1 if visibility_track: sections = visibility_track.get_sections() for ss in sections: if (unreal.Name(f"{container.get('asset')}_map") in ss.get_level_names()): visibility_track.remove_section(ss) # Update visibility sections indexes. i = -1 prev_name = [] for ss in sections: if prev_name != ss.get_level_names(): i += 1 ss.set_row_index(i) prev_name = ss.get_level_names() if parent: break assert parent, "Could not find the parent sequence" # Create a temporary level to delete the layout level. EditorLevelLibrary.save_all_dirty_levels() EditorAssetLibrary.make_directory(f"{root}/tmp") tmp_level = f"{root}/project/" if not EditorAssetLibrary.does_asset_exist(f"{tmp_level}.temp_map"): EditorLevelLibrary.new_level(tmp_level) else: EditorLevelLibrary.load_level(tmp_level) # Delete the layout directory. EditorAssetLibrary.delete_directory(str(path)) if create_sequences: EditorLevelLibrary.load_level(master_level) EditorAssetLibrary.delete_directory(f"{root}/tmp") # Delete the parent folder if there aren't any more layouts in it. asset_content = EditorAssetLibrary.list_assets( str(path.parent), recursive=False, include_folder=True ) if len(asset_content) == 0: EditorAssetLibrary.delete_directory(str(path.parent))
import unreal import os import argparse def convertWindowsToLinux(windowsPath): drive, rest = windowsPath.split(':', 1) drive = drive.lower() # Replace backslashes with forward slashes rest = rest.replace('\\', '/') # Combine the components and add "/mnt" at the beginning unix_path = f'/mnt/{drive}{rest}' return unix_path def convert_unix_to_windows_path(unix_path): # Replace forward slashes with the appropriate separator for the current OS windows_path = unix_path.replace('/', os.sep) # Check if the path starts with '/mnt/' and convert it to the corresponding drive letter if windows_path.startswith('\mnt\\'): drive_letter = windows_path[5].upper() # Assuming the drive letter is always single character windows_path = drive_letter + ':' + windows_path[6:] return windows_path def main(): args = parse_arguments() output_base_name = os.path.splitext(os.path.basename(convertWindowsToLinux(args.inputImage)))[0] unreal.log(convertWindowsToLinux(args.outputPath)) output_location = convertWindowsToLinux(args.outputPath) output_dir_path = convert_unix_to_windows_path(os.path.join(output_location, output_base_name)) output_mesh_path = os.path.join(output_dir_path, output_base_name+".obj") unreal.log(output_mesh_path) unreal.log(os.path.exists(output_mesh_path)) objPath = os.path.join(output_dir_path, output_base_name+".obj") unreal.log(f"importing {objPath} to {args.outputDirectoryName}") # importAssets(os.path.join(output_dir_path, output_base_name+".obj"), args.outputDirectoryName) def parse_arguments(): parser = argparse.ArgumentParser(description='Uploads Output') parser.add_argument('--inputImage', required=True, help='Path to the input image') parser.add_argument('--outputPath', required=True, help='Path to the DECA results') parser.add_argument('--outputDirectoryName', default='FaceMesh', help='Optional output directory name (default: FaceMesh)') return parser.parse_args() def importAssets(objFilePath, destination_folder_name): # need to change this # ./../../../../../project/.py --inputImage "C:/project/.png" --outputPath "C:/project/" # Create an instance of InterchangeGenericAssetsPipeline pipeline = unreal.InterchangeGenericAssetsPipeline() # Configure the pipeline settings pipeline.import_offset_rotation = unreal.Rotator(90, 0, 0) pipeline.import_offset_translation = unreal.Vector(0, 0, 0) pipeline.import_offset_uniform_scale = 400.0 pipeline.use_source_name_for_asset = True # Replace 'obj_file_path' with the actual path to your OBJ file # Specify the destination folder path destination_folder_path = os.path.join("/Game/", destination_folder_name) # Change this to your desired destination path source_data = unreal.InterchangeManager.create_source_data(objFilePath) import_asset_parameters = unreal.ImportAssetParameters() # import_asset_parameters.is_automated = True eas = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) import_asset_parameters.override_pipelines.append(pipeline) ic_mng = unreal.InterchangeManager.get_interchange_manager_scripted() # can try aasync ic_mng.import_scene(destination_folder_path, source_data, import_asset_parameters) main() # args = parse_arguments() # # unreal.log("hello")
# This script was generated with the addons Blender for UnrealEngine : https://github.com/project/-For-UnrealEngine-Addons # It will import into Unreal Engine all the assets of type StaticMesh, SkeletalMesh, Animation and Pose # The script must be used in Unreal Engine Editor with Python plugins : https://docs.unrealengine.com/en-US/project/ # Use this command in Unreal cmd consol: py "[ScriptLocation]\ImportSequencerScript.py" import sys import os.path import json try: # TO DO: Found a better way to check that. import unreal except ImportError: import unreal_engine as unreal def CheckTasks(): if GetUnrealVersion() >= 4.20: # TO DO: EditorAssetLibrary was added in witch version exactly? if not hasattr(unreal, 'EditorAssetLibrary'): print('--------------------------------------------------') print('WARNING: Editor Scripting Utilities should be activated.') print('Edit > Plugin > Scripting > Editor Scripting Utilities.') return False if not hasattr(unreal.MovieSceneSequence, 'set_display_rate'): print('--------------------------------------------------') print('WARNING: Editor Scripting Utilities should be activated.') print('Edit > Plugin > Scripting > Sequencer Scripting.') return False return True def JsonLoad(json_file): # Changed in Python 3.9: The keyword argument encoding has been removed. if sys.version_info >= (3, 9): return json.load(json_file) else: return json.load(json_file, encoding="utf8") def JsonLoadFile(json_file_path): if sys.version_info[0] < 3: with open(json_file_path, "r") as json_file: return JsonLoad(json_file) else: with open(json_file_path, "r", encoding="utf8") as json_file: return JsonLoad(json_file) def GetUnrealVersion(): version = unreal.SystemLibrary.get_engine_version().split(".") float_version = int(version[0]) + float(float(version[1])/100) return float_version def CreateSequencer(): # Prepare process import json_data_file = 'ImportSequencerData.json' dir_path = os.path.dirname(os.path.realpath(__file__)) sequence_data = JsonLoadFile(os.path.join(dir_path, json_data_file)) spawnable_camera = sequence_data['spawnable_camera'] startFrame = sequence_data['startFrame'] endFrame = sequence_data['endFrame']+1 render_resolution_x = sequence_data['render_resolution_x'] render_resolution_y = sequence_data['render_resolution_y'] frameRateDenominator = sequence_data['frameRateDenominator'] frameRateNumerator = sequence_data['frameRateNumerator'] secureCrop = sequence_data['secureCrop'] # add end crop for avoid section overlay unreal_import_location = sequence_data['unreal_import_location'] ImportedCamera = [] # (CameraName, CameraGuid) def AddSequencerSectionTransformKeysByIniFile(sequencer_section, track_dict): for key in track_dict.keys(): value = track_dict[key] # (x,y,z x,y,z x,y,z) frame = unreal.FrameNumber(int(key)) sequencer_section.get_channels()[0].add_key(frame, value["location_x"]) sequencer_section.get_channels()[1].add_key(frame, value["location_y"]) sequencer_section.get_channels()[2].add_key(frame, value["location_z"]) sequencer_section.get_channels()[3].add_key(frame, value["rotation_x"]) sequencer_section.get_channels()[4].add_key(frame, value["rotation_y"]) sequencer_section.get_channels()[5].add_key(frame, value["rotation_z"]) sequencer_section.get_channels()[6].add_key(frame, value["scale_x"]) sequencer_section.get_channels()[7].add_key(frame, value["scale_y"]) sequencer_section.get_channels()[8].add_key(frame, value["scale_z"]) def AddSequencerSectionFloatKeysByIniFile(sequencer_section, track_dict): for key in track_dict.keys(): frame = unreal.FrameNumber(int(key)) value = track_dict[key] sequencer_section.get_channels()[0].add_key(frame, value) def AddSequencerSectionBoolKeysByIniFile(sequencer_section, track_dict): for key in track_dict.keys(): frame = unreal.FrameNumber(int(key)) value = track_dict[key] sequencer_section.get_channels()[0].add_key(frame, value) print("Warning this file already exists") # ??? 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' print("Sequencer reference created", seq) # Process import print("========================= Import started ! =========================") # Set frame rate myFFrameRate = unreal.FrameRate() myFFrameRate.denominator = frameRateDenominator myFFrameRate.numerator = frameRateNumerator seq.set_display_rate(myFFrameRate) # Set playback range seq.set_playback_end_seconds((endFrame-secureCrop)/float(frameRateNumerator)) seq.set_playback_start_seconds(startFrame/float(frameRateNumerator)) # set_playback_end_seconds camera_cut_track = seq.add_master_track(unreal.MovieSceneCameraCutTrack) camera_cut_track.set_editor_property('display_name', 'Imported Camera Cuts') if GetUnrealVersion() >= 4.26: camera_cut_track.set_color_tint(unreal.Color(b=200, g=0, r=0, a=0)) else: pass for x, camera_data in enumerate(sequence_data["cameras"]): # import camera print("Start camera import " + str(x+1) + "/" + str(len(sequence_data["cameras"])) + " :" + camera_data["name"]) # Import camera tracks transform camera_tracks = JsonLoadFile(camera_data["additional_tracks_path"]) # Create spawnable camera and add camera in sequencer cine_camera_actor = unreal.EditorLevelLibrary().spawn_actor_from_class(unreal.CineCameraActor, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 0)) # Import additional tracks (camera_component) camera_component_binding = seq.add_possessable(cine_camera_actor.get_cine_camera_component()) # Get the last TrackFocalLength = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TrackFocalLength.set_property_name_and_path('CurrentFocalLength', 'CurrentFocalLength') TrackFocalLength.set_editor_property('display_name', 'Current Focal Length') sectionFocalLength = TrackFocalLength.add_section() sectionFocalLength.set_end_frame_bounded(False) sectionFocalLength.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionFocalLength, camera_tracks['Camera FocalLength']) TrackSensorWidth = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TrackSensorWidth.set_property_name_and_path('Filmback.SensorWidth', 'Filmback.SensorWidth') TrackSensorWidth.set_editor_property('display_name', 'Sensor Width (Filmback)') sectionSensorWidth = TrackSensorWidth.add_section() sectionSensorWidth.set_end_frame_bounded(False) sectionSensorWidth.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionSensorWidth, camera_tracks['Camera SensorWidth']) TrackSensorHeight = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TrackSensorHeight.set_property_name_and_path('Filmback.SensorHeight', 'Filmback.SensorHeight') TrackSensorHeight.set_editor_property('display_name', 'Sensor Height (Filmback)') sectionSensorHeight = TrackSensorHeight.add_section() sectionSensorHeight.set_end_frame_bounded(False) sectionSensorHeight.set_start_frame_bounded(False) crop_camera_sensor_height = {} for key in camera_tracks['Camera SensorHeight'].keys(): original_width = float(camera_tracks['Camera SensorWidth'][key]) original_height = float(camera_tracks['Camera SensorHeight'][key]) res_x = float(sequence_data['render_resolution_x']) res_y = float(sequence_data['render_resolution_y']) pixel_x = float(sequence_data['pixel_aspect_x']) pixel_y = float(sequence_data['pixel_aspect_y']) res_ratio = res_x / res_y pixel_ratio = pixel_x / pixel_y crop_camera_sensor_height[key] = (original_width / (res_ratio * pixel_ratio)) AddSequencerSectionFloatKeysByIniFile(sectionSensorHeight, crop_camera_sensor_height) TrackFocusDistance = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) if GetUnrealVersion() >= 4.24: TrackFocusDistance.set_property_name_and_path('FocusSettings.ManualFocusDistance', 'FocusSettings.ManualFocusDistance') TrackFocusDistance.set_editor_property('display_name', 'Manual Focus Distance (Focus Settings)') else: print(GetUnrealVersion()) TrackFocusDistance.set_property_name_and_path('ManualFocusDistance', 'ManualFocusDistance') TrackFocusDistance.set_editor_property('display_name', 'Current Focus Distance') sectionFocusDistance = TrackFocusDistance.add_section() sectionFocusDistance.set_end_frame_bounded(False) sectionFocusDistance.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionFocusDistance, camera_tracks['Camera FocusDistance']) TracknAperture = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) TracknAperture.set_property_name_and_path('CurrentAperture', 'CurrentAperture') TracknAperture.set_editor_property('display_name', 'Current Aperture') sectionAperture = TracknAperture.add_section() sectionAperture.set_end_frame_bounded(False) sectionAperture.set_start_frame_bounded(False) AddSequencerSectionFloatKeysByIniFile(sectionAperture, camera_tracks['Camera Aperture']) # add a binding for the camera camera_binding = seq.add_possessable(cine_camera_actor) if spawnable_camera: # Transfer to spawnable camera camera_spawnable = seq.add_spawnable_from_class(unreal.CineCameraActor) # Add camera in sequencer camera_component_binding.set_parent(camera_spawnable) # Import transform tracks if spawnable_camera: transform_track = camera_spawnable.add_track(unreal.MovieScene3DTransformTrack) else: 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['Camera transform']) # Set property binding if spawnable_camera: current_camera_binding = camera_spawnable else: current_camera_binding = camera_binding if GetUnrealVersion() >= 4.26: current_camera_binding.set_display_name(camera_data["name"]) else: pass tracksSpawned = current_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']) # Set property actor if spawnable_camera: current_cine_camera_actor = camera_spawnable.get_object_template() else: current_cine_camera_actor = cine_camera_actor current_cine_camera_actor.set_actor_label(camera_data["name"]) camera_component = cine_camera_actor.camera_component camera_component.aspect_ratio = render_resolution_x/render_resolution_y camera_component.lens_settings.min_f_stop = 0 camera_component.lens_settings.max_f_stop = 1000 # Clean the created assets if spawnable_camera: cine_camera_actor.destroy_actor() camera_binding.remove() if spawnable_camera: ImportedCamera.append((camera_data["name"], camera_spawnable)) else: ImportedCamera.append((camera_data["name"], camera_binding)) # Import camera cut section for section in sequence_data['marker_sections']: camera_cut_section = camera_cut_track.add_section() if section["has_camera"] is not None: for camera in ImportedCamera: if camera[0] == section["camera_name"]: camera_binding_id = unreal.MovieSceneObjectBindingID() if GetUnrealVersion() >= 4.26: camera_binding_id = seq.make_binding_id(camera[1], unreal.MovieSceneObjectBindingSpace.LOCAL) else: camera_binding_id = seq.make_binding_id(camera[1]) camera_cut_section.set_camera_binding_id(camera_binding_id) camera_cut_section.set_end_frame_seconds((section["end_time"]-secureCrop)/float(frameRateNumerator)) camera_cut_section.set_start_frame_seconds(section["start_time"]/float(frameRateNumerator)) # Import result print('========================= Imports completed ! =========================') ImportedCameraStr = [] for cam in ImportedCamera: ImportedCameraStr.append(cam[0]) print(ImportedCameraStr) print('=========================') # Select and open seq in content browser if GetUnrealVersion() >= 4.26: unreal.AssetEditorSubsystem.open_editor_for_assets(unreal.AssetEditorSubsystem(), [unreal.load_asset(seq.get_path_name())]) else: unreal.AssetToolsHelpers.get_asset_tools().open_editor_for_assets([unreal.load_asset(seq.get_path_name())]) unreal.EditorAssetLibrary.sync_browser_to_objects([seq.get_path_name()]) return 'Sequencer created with success !' print("Start importing sequencer.") if CheckTasks(): print(CreateSequencer()) print("Importing sequencer finished.")
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() #print(args.vrm) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() ###### rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() #print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller()#rig.controller else: c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() # print(a) # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items' or node.get_node_title() == 'Collection from Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object #print(vv) meta = vv # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] print(items_forControl) print(items_forBone) humanoidBoneTable = {"dummy" : "dummy"} humanoidBoneTable.clear() for h in meta.humanoid_bone_table: bone_h = "{}".format(h).lower() bone_m = "{}".format(meta.humanoid_bone_table[h]).lower() try: i = list(humanoidBoneTable.values()).index(bone_m) except: i = -1 if (bone_h!="" and bone_m!="" and i==-1): humanoidBoneTable[bone_h] = bone_m for bone_h in humanoidBoneList: bone_m = humanoidBoneTable.get(bone_h, None) if bone_m == None: continue #for bone_h in meta.humanoid_bone_table: # bone_m = meta.humanoid_bone_table[bone_h] # try: # i = humanoidBoneList.index(bone_h.lower()) # except: # i = -1 # if (i >= 0): if (True): tmp = '(Type=Bone,Name=' #tmp += "{}".format(bone_m).lower() tmp += bone_m tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) #print(bone_m) tmp = '(Type=Control,Name=' #tmp += "{}".format(bone_h).lower() + '_c' tmp += bone_h + '_c' tmp += ')' #print(c) c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # if (e.type == unreal.RigElementType.CONTROL): # tmp = '(Type=Control,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
import unreal def spawn_draw_path_actor(): # Percorso della classe Blueprint blueprint_path = "/project/" actor_class = unreal.EditorAssetLibrary.load_blueprint_class(blueprint_path) if not actor_class: unreal.log_error(f"Blueprint class '{blueprint_path}' non trovata.") return False # Ottenere il mondo dell'editor editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) world = editor_subsystem.get_editor_world() # Controllare se esiste già un attore DrawPath nel mondo all_actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in all_actors: if actor.get_class() == actor_class: unreal.log("DrawPath actor esiste già nel mondo.") return True # Specifica la posizione e la rotazione dell'attore actor_location = unreal.Vector(0.0, 0.0, 0.0) actor_rotation = unreal.Rotator(0.0, 0.0, 0.0) # Piazzare l'attore nella scena actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, actor_location, actor_rotation) if not actor: unreal.log_error("Attore non è stato creato.") return False unreal.log("DrawPath actor creato con successo.") return True # Esegui la funzione spawn_draw_path_actor()
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() #print(args.vrm) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() ###### rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() #print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller()#rig.controller else: c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() # print(a) # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items' or node.get_node_title() == 'Collection from Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object #print(vv) meta = vv # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] print(items_forControl) print(items_forBone) humanoidBoneTable = {"dummy" : "dummy"} humanoidBoneTable.clear() for h in meta.humanoid_bone_table: bone_h = "{}".format(h).lower() bone_m = "{}".format(meta.humanoid_bone_table[h]).lower() try: i = list(humanoidBoneTable.values()).index(bone_m) except: i = -1 if (bone_h!="" and bone_m!="" and i==-1): humanoidBoneTable[bone_h] = bone_m for bone_h in humanoidBoneList: bone_m = humanoidBoneTable.get(bone_h, None) if bone_m == None: continue #for bone_h in meta.humanoid_bone_table: # bone_m = meta.humanoid_bone_table[bone_h] # try: # i = humanoidBoneList.index(bone_h.lower()) # except: # i = -1 # if (i >= 0): if (True): tmp = '(Type=Bone,Name=' #tmp += "{}".format(bone_m).lower() tmp += bone_m tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) #print(bone_m) tmp = '(Type=Control,Name=' #tmp += "{}".format(bone_h).lower() + '_c' tmp += bone_h + '_c' tmp += ')' #print(c) c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # if (e.type == unreal.RigElementType.CONTROL): # tmp = '(Type=Control,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
# py "/project/ SDK\SquadEditor\Squad\Content\Python\squadwiki\extractWeapons.py" # ----- Imports ----- import unreal import os import json # ----- Settings ----- # Install Path of the SDK installDirectory = "/project/ SDK\\" # Directory to export to exportDirectory = "/project/ SDK\\" # Dict that contains directory and folders. Modders can add a new dict under vanilla with a directory and one set of sub-folders to look through. # Note that the file structure needs to be the same as vanilla. If you're having issues, reach out on GitHub or Discord. # "GrenadeLaunchers", "RocketLaunchers", "Shotguns", "SubmachineGuns" weaponsDirectoryObject = { "vanilla": { "weaponDirectory": f"{installDirectory}SquadEditor\\Squad\\Content\\Blueprints\\Items\\", "factionsDirectory": f"{installDirectory}SquadEditor\\Squad\\Content\\Settings\\FactionSetups\\", "folders": ["MachineGuns", "Pistols", "Rifles"], "factionBlacklist": ["Templates", "TestFactionSetups", "UI", "Tutorials", "Units"] }, } # ----- Exception Classes ----- class InvalidWeaponFolder(OSError): def __init__(self, folder): raise OSError(f"Invalid Weapon Folder Listed: {folder}") class InvalidAttribute(AttributeError): def __init__(self, weapon): raise AttributeError(f"Invalid Weapon: {weapon}") class InvalidDirectoryKeySetup(KeyError): def __init__(self, type, key): raise KeyError(f"Key {key} is missing in {type} in the weaponsDirectoryObject") def searchFolderForFactions(baseFolder, directoryType): # Blacklist for folders/files to not check CASE SENSITIVE blacklist = weaponsDirectoryObject[directoryType]["factionBlacklist"] weapons = {} ''' "name": { "factions": [] } ''' for item in os.listdir(baseFolder): # If the item is blacklisted, skip if not any(x == item for x in blacklist): # If it's a folder, we need to search it so recursively search if os.path.isdir(baseFolder + item): returnWeapons = searchFolderForFactions(baseFolder + item + "\\", directoryType) # Merge returned weapon and current weapons for attr, value in returnWeapons.items(): if attr not in weapons: weapons[attr] = value else: for faction in value["factions"]: if faction not in weapons[attr]["factions"]: weapons[attr]["factions"].append(faction) # If it's a file, we need to extract the data from it elif os.path.isfile(baseFolder + item): # Adjust path to load object based on where the file is located. Base game, expansions, and mods all are in different locations, so we need to cut and add accordingly.' newBaseFolder = "" if "content" in weaponsDirectory or "Content" in weaponsDirectory: pathToCutSearch = f"{installDirectory}SquadEditor\\Squad\\Content\\" newBaseFolder = "/Game/" + baseFolder[len(pathToCutSearch):] elif "expansions" in weaponsDirectory or "Expansions" in weaponsDirectory: pathToCutSearch = f"{installDirectory}SquadEditor\\Squad\\Plugins\\Expansions\\" newBaseFolder = "/" + baseFolder[len(pathToCutSearch):] elif "mods" in weaponsDirectory or "Mods" in weaponsDirectory: pathToCutSearch = f"{installDirectory}SquadEditor\\Squad\\Plugins\\Mods\\" newBaseFolder = "/" + baseFolder[len(pathToCutSearch):] # Remove .uasset from asset name itemName = item.split(".")[0] unrealFaction = unreal.load_object(None, f"{newBaseFolder}{itemName}.{itemName}") # Create a shorthand less descriptive version # Check to see if the item is a faction setup, if it is then we can get the info we need from it if unrealFaction.get_class().get_name() == "BP_SQFactionSetup_C": factionID = unrealFaction.faction_id # Loop through every role in the roles array for roleSetting in unrealFaction.roles: role = roleSetting.setting # Loop through the inventory slots for inventorySlot in role.inventory: slotWeapons = inventorySlot.weapon_items # Loop through the weapons in the slot for slotWeapon in slotWeapons: weaponInSlotName = str(slotWeapon.equipable_item.get_name()) # If the weapon slot is in the array then append to the factions list otherwise just add the dict in if weaponInSlotName in weapons: # If the faction is not present yet, then add it if str(factionID) not in weapons[weaponInSlotName]["factions"]: weapons[weaponInSlotName]["factions"].append(str(factionID)) else: weapons[weaponInSlotName] = { "factions": [str(factionID)] } return weapons # ----- Code ----- weaponsJSON = {} print("Squad Wiki Pipeline: Weapons and Vehicles") for attr, value in weaponsDirectoryObject.items(): # --- Loading Files --- # Try saving the directories, if there is an issue then raise an exception try: weaponsDirectory = value["weaponDirectory"] except KeyError: raise InvalidDirectoryKeySetup(attr, "weaponDirectory") try: factionsDirectory = value["factionsDirectory"] except KeyError: raise InvalidDirectoryKeySetup(attr, "factionsDirectory") try: listOfWeaponFolders = value["folders"] except KeyError: raise InvalidDirectoryKeySetup(attr, "folders") try: test = value["factionBlacklist"] except KeyError: raise InvalidDirectoryKeySetup(attr, "factionBlacklist") # --- Get Faction Info --- print(f"Searching through {attr} factions...") weaponFactions = searchFolderForFactions(factionsDirectory, attr) # --- Get Weapon Info --- print(f"Searching through {attr} weapons...") for weaponFolder in listOfWeaponFolders: print(f"Searching in {weaponFolder}...", flush=True) # Verify weapon folder is valid pathToSearch = weaponsDirectory + weaponFolder if not os.path.isdir(pathToSearch): raise InvalidWeaponFolder(weaponFolder) # Loop through each file/dir in the folder for weapon in os.listdir(weaponsDirectory + weaponFolder): # -- Setup -- weaponName = weapon.split(".")[0] # Only look at files, not child directories if not os.path.isfile(pathToSearch + "\\" + weapon): continue # Skip any generic weapons. These are not setup as real weapons and have invalid values if "Generic" in weaponName: continue # Create new path for unreal reference if "content" in weaponsDirectory or "Content" in weaponsDirectory: pathToCut = f"{installDirectory}SquadEditor\\Squad\\Content\\" newPath = "/Game/" + pathToSearch[len(pathToCut):] elif "expansions" in weaponsDirectory or "Expansions" in weaponsDirectory: pathToCut = f"{installDirectory}SquadEditor\\Squad\\Plugins\\Expansions\\" newPath = "/" + pathToSearch[len(pathToCut):] elif "mods" in weaponsDirectory or "Mods" in weaponsDirectory: pathToCut = f"{installDirectory}SquadEditor\\Squad\\Plugins\\Mods\\" newPath = "/" + pathToSearch[len(pathToCut):] # Get unreal version of the file unrealWeapon = unreal.load_object(None, f"{newPath}/{weaponName}.{weaponName}_C") unrealWeaponDefault = unreal.get_default_object(unrealWeapon) # Create a shorthand less descriptive version uWD = unrealWeaponDefault # -- Tracers -- # Check to see if the tracer projectile class is present, if it is grab the name of it, otherwise leave as None tracerProjectileClass = uWD.weapon_config.tracer_projectile_class if tracerProjectileClass is not None: tracerProjectileClass = uWD.weapon_config.tracer_projectile_class.get_name() # -- Curves -- # Damage Curve damageFallOffTimeRange = uWD.weapon_config.damage_falloff_curve.get_time_range() # Get max and min of time (distance) range damageFOTFarDistance = damageFallOffTimeRange[1] damageFOTCloseDistance = damageFallOffTimeRange[0] damageFOMaxDamage = uWD.weapon_config.damage_falloff_curve.get_float_value(damageFOTCloseDistance) damageFOMinDamage = uWD.weapon_config.damage_falloff_curve.get_float_value(damageFOTFarDistance) # -- Faction -- # Get faction info for the weapon factions = [] if weaponName + "_C" in weaponFactions: factions = weaponFactions[weaponName + "_C"]["factions"] # -- Attachments -- attachments = uWD.attachment_classes attachmentNames = [] for attachment in attachments: if attachment is not None: attachmentName = attachment.get_name() attachmentNames.append(attachmentName) # -- ICO Static Info staticInfoClass = unreal.get_default_object(uWD.item_static_info_class) staticInfo = { "sway": { "dynamic": { "lowStaminaSwayFactor": round(staticInfoClass.sway_data.dynamic_group.stamina.low_stamina_sway_factor, 5), "fullStaminaSwayFactor": round(staticInfoClass.sway_data.dynamic_group.stamina.full_stamina_sway_factor, 5), "holdingBreathSwayFactor": round(staticInfoClass.sway_data.dynamic_group.breath.holding_breath_sway_factor, 5), "addMoveSway": round(staticInfoClass.sway_data.dynamic_group.movement.add_move_sway, 5), "minMoveSwayFactor": round(staticInfoClass.sway_data.dynamic_group.movement.min_move_sway_factor, 5), "maxMoveSwayFactor": round(staticInfoClass.sway_data.dynamic_group.movement.max_move_sway_factor, 5), }, "stance": { "proneADSSwayMin": round(staticInfoClass.sway_data.stance_group.prone.ads_sway_min, 5), "proneSwayMin": round(staticInfoClass.sway_data.stance_group.prone.sway_min, 5), "crouchADSSwayMin": round(staticInfoClass.sway_data.stance_group.crouch.ads_sway_min, 5), "crouchSwayMin": round(staticInfoClass.sway_data.stance_group.crouch.sway_min, 5), "standingADSSwayMin": round(staticInfoClass.sway_data.stance_group.standing.ads_sway_min, 5), "standingSwayMin": round(staticInfoClass.sway_data.stance_group.standing.sway_min, 5), "bipodADSSwayMin": round(staticInfoClass.sway_data.stance_group.bipod.ads_sway_min, 5), "bipodSwayMin": round(staticInfoClass.sway_data.stance_group.bipod.sway_min, 5), }, "maxSway": round(staticInfoClass.sway_data.limits.final_sway_clamp, 5), }, "swayAlignment": { "dynamic": { "lowStaminaSwayFactor": round(staticInfoClass.sway_alignment_data.dynamic_group.stamina.low_stamina_sway_factor, 5), "fullStaminaSwayFactor": round(staticInfoClass.sway_alignment_data.dynamic_group.stamina.full_stamina_sway_factor, 5), "holdingBreathSwayFactor": round(staticInfoClass.sway_alignment_data.dynamic_group.breath.holding_breath_sway_factor, 5), "addMoveSway": round(staticInfoClass.sway_alignment_data.dynamic_group.movement.add_move_sway, 5), "minMoveSwayFactor": round(staticInfoClass.sway_alignment_data.dynamic_group.movement.min_move_sway_factor, 5), "maxMoveSwayFactor": round(staticInfoClass.sway_alignment_data.dynamic_group.movement.max_move_sway_factor, 5), }, "stance": { "proneADSSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.prone.ads_sway_min, 5), "proneSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.prone.sway_min, 5), "crouchADSSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.crouch.ads_sway_min, 5), "crouchSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.crouch.sway_min, 5), "standingADSSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.standing.ads_sway_min, 5), "standingSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.standing.sway_min, 5), "bipodADSSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.bipod.ads_sway_min, 5), "bipodSwayMin": round(staticInfoClass.sway_alignment_data.stance_group.bipod.sway_min, 5), }, "maxSway": round(staticInfoClass.sway_alignment_data.limits.final_sway_clamp, 5), }, "spring": { "weaponSpringSide": round(staticInfoClass.weapon_spring_side, 5), "weaponSpringStiffness": round(staticInfoClass.weapon_spring_stiffness, 5), "weaponSpringDamping": round(staticInfoClass.weapon_spring_critical_damping_factor, 5), "weaponSpringMass": round(staticInfoClass.weapon_spring_mass, 5) }, "recoil": { "camera": { "recoilCameraOffsetFactor": round(staticInfoClass.recoil_camera_offset_factor, 5), "recoilCameraOffsetInterpSpeed": round(staticInfoClass.recoil_camera_offset_interp_speed, 5), "recoilLofCameraOffsetLimit": round(staticInfoClass.recoil_lof_camera_offset_limit, 5), "recoilLofAttackInterpSpeed": round(staticInfoClass.recoil_lof_attack_interp_speed, 5), "recoilCanReleaseInterpSpeed": round(staticInfoClass.recoil_can_release_interp_speed, 5), "recoilLofReleaseInterpSpeed": round(staticInfoClass.recoil_lof_release_interp_speed, 5), "recoilAdsCameraShotInterpSpeed": round(staticInfoClass.recoil_ads_camera_shot_interp_speed, 5) }, "dynamic": { "movement": { "moveRecoilFactorRelease": round(staticInfoClass.move_recoil_factor_release, 5), "addMoveRecoil": round(staticInfoClass.add_move_recoil, 5), "maxMoveRecoilFactor": round(staticInfoClass.max_move_recoil_factor, 5), "minMoveRecoilFactor": round(staticInfoClass.min_move_recoil_factor, 5), "recoilAlignmentMovementAddative": round(staticInfoClass.recoil_alignment_movement_addative, 5), "recoilAlignmentMovementExponent": round(staticInfoClass.recoil_alignment_movement_exponent, 5) }, "stamina": { "lowStaminaRecoilFactor": round(staticInfoClass.low_stamina_recoil_factor, 5), "fullStaminaRecoilFactor": round(staticInfoClass.full_stamina_recoil_factor, 5), "recoilAlignmentStaminaAddative": round(staticInfoClass.recoil_alignment_stamina_addative, 5), "recoilAlignmentStaminaExponent": round(staticInfoClass.recoil_alignment_stamina_exponent, 5) }, "shoulder": { "recoilAlignmentShoulderMax": { "x": round(staticInfoClass.recoil_alignment_shoulder_max.x, 5), "y" : round(staticInfoClass.recoil_alignment_shoulder_max.y, 5) }, "recoilAlignmentShoulderAngleLimits": { "x": round(staticInfoClass.recoil_alignment_shoulder_angle_limits.x, 5), "y" : round(staticInfoClass.recoil_alignment_shoulder_angle_limits.y, 5) } }, "grip": { "recoilAlignmentGripMax": { "x": round(staticInfoClass.recoil_alignment_grip_max.x, 5), "y" : round(staticInfoClass.recoil_alignment_grip_max.y, 5) }, "recoilAlignmentGripAngleLimits": { "x": round(staticInfoClass.recoil_alignment_grip_angle_limits.x, 5), "y" : round(staticInfoClass.recoil_alignment_grip_angle_limits.y, 5) } }, "recoilAlignmentMultiplierMax": round(staticInfoClass.recoil_alignment_multiplier_max, 5), } } } # Need to add: ICO # -- Dict Creation -- try: weaponInfo = { "displayName": str(uWD.display_name), "rawName": f"{weaponName}.{weaponName}_C", "folder": weaponFolder, "factions": factions, # Inventory Info "inventoryInfo": { "description": str(uWD.item_description), "HUDTexture": str(uWD.hud_selected_texture.get_name()), "inventoryTexture": str(uWD.hud_texture.get_name()), "ammoPerRearm": round(uWD.ammo_per_rearm_item, 5), "showItemCount": bool(uWD.show_item_count_in_inventory), "showMagCount": bool(uWD.show_mag_count_in_inventory), }, # Weapon info "weaponInfo": { # Mag info "maxMags": round(uWD.weapon_config.max_mags, 5), "roundsPerMag": round(uWD.weapon_config.rounds_per_mag, 5), "roundInChamber": bool(uWD.weapon_config.allow_round_in_chamber), "allowSingleLoad": bool(uWD.weapon_config.allow_single_load), # Shooting "firemodes": list(uWD.weapon_config.firemodes), "timeBetweenShots": round(uWD.weapon_config.time_between_shots, 5), # Burst, auto fire "timeBetweenSingleShots": round(uWD.weapon_config.time_between_single_shots, 5), # Semi-Auto "avgFireRate": bool(uWD.weapon_config.average_fire_rate), "resetBurstOnTriggerRelease": bool(uWD.weapon_config.reset_burst_on_trigger_release), # Reloading "reloadCancelGracePeriod": round(uWD.weapon_config.finish_reload_grace_period, 5), # "Finish reload grace period for cancelling reload close to finishing the reload process" "tacticalReloadDuration": round(uWD.weapon_config.tactical_reload_duration, 5), "dryReloadDuration": round(uWD.weapon_config.dry_reload_duration, 5), "tacticalReloadBipodDuration": round(uWD.weapon_config.tactical_reload_bipod_duration, 5), "dryReloadBipodDuration": round(uWD.weapon_config.reload_dry_bipod_duration, 5), # ADS "ADSPostTransitionRation": round(uWD.weapon_config.ads_post_transition_ratio, 5), "allowZoom": bool(uWD.weapon_config.allow_zoom), # Allow ADS "ADSMoveSpeedMultiplier": round(uWD.ads_move_speed_multiplier, 5), # Projectile "projectileClass": str(uWD.weapon_config.projectile_class.get_name()), "tracerProjectileClass": tracerProjectileClass, "roundsBetweenTracer": round(uWD.weapon_config.rounds_between_tracer, 5), "muzzleVelocity": round(uWD.weapon_config.muzzle_velocity, 5), # Damage "damageFallOffMinDamage": damageFOMinDamage, "damageFallOffMinDamageDistance": damageFOTFarDistance, "damageFallOffMaxDamage": damageFOMaxDamage, "damageFallOffMaxDamageDistance": damageFOTCloseDistance, "armorPenetrationDepthMM": round(uWD.weapon_config.armor_penetration_depth_millimeters, 5), "traceDistanceAfterPen": round(uWD.weapon_config.trace_distance_after_penetration_meters, 5), # Accuracy "MOA": round(uWD.weapon_config.moa), "emptyMagReload": bool(uWD.weapon_config.empty_mag_to_reload), # Equipping "equipDuration": round(uWD.equip_duration, 5), "unequipDuration": round(uWD.unequip_duration, 5), }, # Focus info # Physical info of the gun "physicalInfo": { "skeletalMesh": str(uWD.mesh1p.skeletal_mesh.get_name()), "attachments": attachmentNames, }, "staticInfo": staticInfo } '''"focusInfo": { "focusDistanceHipfire": round(uWD.dof_focus_distance_hipfire), "focusDistanceADS": round(uWD.dof_focus_distance_ads), "apertureHipfire": round(uWD.dof_aperture_hipfire), "apertureADS": round(uWD.dof_aperture_ads), "aimTimeMultiplier": round(uWD.aim_time_multiplier), "transitionCurve": "TOBEADDED", "recoilRampUpSpeed": round(uWD.dof_recoil_ramp_up_speed), "recoilDecaySpeed": round(uWD.dof_recoild_decay_speed), "recoilRandomMin": round(uWD.dof_recoil_random_min), "recoilRandomMax": round(uWD.dof_recoil_random_max) },''' except AttributeError: raise InvalidAttribute(weaponName) weaponsJSON[weaponName] = weaponInfo # Write file with open(f"{installDirectory}weaponInfo.json", "w") as f: json.dump(weaponsJSON, f, indent=4) print(f"File exported at {installDirectory}weaponInfo.json") '''['recoil_alignment_new_shoulder_alignment', 'recoil_alignment_shoulder_target_offset', 'recoil_alignment_shoulder_current_offset', 'recoil_alignment_new_grip_alignment', 'recoil_alignment_grip_target_offset', 'recoil_alignment_grip_current_offset', 'recoil_alignment_mult', 'recoil_magnitude', 'is_holding_breath', 'holding_breath_sway_factor', 'bul let_count_incrementer', 'hold_breath_ease_timeline', 'recoil_grip_alignment_timeline', 'recoil_shoulder_alignment_timeline', '__doc__', 'recoil_alignment_target_offset_setup', 'recoil_alignment_multiplier_setup', 'get_owner_soldier ', 'blueprint_is_animation_system_valid', '_wrapper_meta_data', 'weapon_config', 'current_state', 'cached_pip_scope', 'ads_move_s peed_multiplier', 'aiming_down_sights', 'fire_input', 'pending_fire', 'max_time_to_loop_sounds_after_last_fire', 'modified_tactical_reload_duration', 'modified_dry_reload_duration', 'current_fire_mode', 'magazines', ' attachment_classes', 'attachments', 'ads_post_process_settings', 'dynamic_first_person_mesh_materials', 'fov_shader_name', 'focus_zoom_alpha', 'simulated_ads_alpha', 'use_stop_adspp_drawing', 'stop_adspp_drawing', 'holding_zoom_easing', 'holding_zoom_easing_alpha', 'fixed_zoom_fov', 'current_fov', 'zoomed_fov', 'focus_zoom_time', 'focus_additional_zoom', 'time_since_last_zoom_toggle', 'last_zoom_progress_at_toggle', 'adjust_ads_sight_item_anim_pos', 'cached_adjust_ads_sight_item_anim_pos', 'new_adj ust_ads_sight_item_anim_pos', 'adjust_ads_sight_item_anim_pos_alpha', 'is_modifying_zeroing', 'adjustable_sight_item_pos', 'suppression_info_class_override', 'calculated_ads_time', 'cached_last_zeroing_time', ' cached_last_zeroing_play_time', 'cached_last_zeroing_position', 'cached_is_bipod_deployed', 'cached_aim_prone_bobbing', 'finished_ads_transition', 'la st_new_zoom', 'fire_sway_selector', 'pre_fire_sway_selector', 'update_bipod', 'update_aim_prone_bobbing', 'toggle_firemode', 'stop_modify_zeroing', 'start_reload', 'start_modify_zeroing', 'set_zoom', 'play_impact_effect', ' play_firing_sound', 'magazine_has_ammo', 'is_zoomed', 'is_reloading', 'is_pulling_trigger', 'is_pending_fire', 'is_fully_zoomed', 'is_aim ing_down_sights', 'get_zoom_progress', 'get_weapon_static_info', 'get_moa_adjusted_aim_direction_from_rotator', 'get_moa_adjusted_aim_direction', 'get_current_moa', 'get_aim_location', 'get_aim_direction', 'can_toggle_firemode', ' blueprint_on_zoom', 'blueprint_on_toggle_firemode', 'blueprint_on_reloaded', 'blueprint_on_reload', 'blueprint_on_pre_reload', 'bl ueprint_on_fire', 'item_static_info_class', 'debug_item_static_info_class', 'on_pawn_owner_changed_event', 'display_name', 'item_description', 'rearm_types_allowed', 'use_owner_as_master_pose', 'ammo_per_rearm_item', ' unequipped_net_update_rate', 'action_state', 'sprint_blendspace', 'walk_forward_anim', 'idle_anim', 'use_anim', 'stand_anim', 'equip_anim', 'u nequip_anim', 'alt_use_anim', 'custom1_anim', 'custom2_anim', 'custom3_anim', 'pre_use_anim', 'post_use_anim', 'pre_alt_use_anim', 'post_alt_use_anim', 'hud_selected_texture', 'hud_texture', 'item_count_icon_texture', ' show_item_count_in_inventory', 'show_mag_count_in_inventory', 'show_ammo_data_in_hud', 'change_dormancy_on_equip_state', 'item_count', 'max_i tem_count', 'cannot_rearm', 'equip_duration', 'unequip_duration', 'rearm_counter_multiplier', 'mesh1p', 'mesh3p', 'pawn_owner', 'cached_weapon1p_anim_instance', 'cached_weapon3p_anim_instance', 'cached_soldier1p_anim_instance', ' cached_soldier3p_anim_instance', 'cached_equip_duration', 'cached_unequip_duration', 'equip_state', 'cached_move_bobbing', 'cached_ sprint_bobbing', 'cached_has_movement', 'cached_is_pulling_trigger', 'cached_is_leaning_right', 'cached_is_leaning_left', 'cached_delta_time', 'update_sprint_bobbing', 'update_move_inputs', 'update_move_bobbing', 'update_lean_right ', 'update_lean_left', 'update_first_person_visibility', 'shovel_hit_deployable', 'set_raising_animation', 'set_lowering_animatio n', 'server_consume_item', 'reinitialize_equip', 'reinitialize_anim_instances', 'rearm', 'play_unequip_animation', 'play_sound_attached_to_weapon', 'play_equip_animation', 'pickup', 'is_first_person_view_target', 'is_equipped', ' is_being_used', 'is_ammo_full', 'initialize_ammo_values', 'hide', 'has_ammo', 'get_rearm_max_item_count', 'get_rearm_item_count', ' get_owner_pawn', 'get_mesh', 'get_item_static_info', 'get_fire_direction', 'get_controller', 'end_use', 'end_alt_use', 'drop', 'create_persisting_ammo_count', 'can_use', 'can_shovel', 'can_rearm_from_type', 'can_rearm', ' can_alt_use', 'calculate_rearm_ammo_cost', 'calculate_missing_rearm_items', 'calculate_missing_ammo_cost', 'calculate_max_ammo_cost', 'bp_e nd_use', 'bp_end_alt_use', 'bp_begin_use', 'bp_begin_alt_use', 'blueprint_update_first_person_visibility', 'blueprint_on_unequipped', 'blueprint_on_unequip', 'blueprint_on_equipped', 'blueprint_on_equip', 'blueprint_draw_hud', ' begin_use', 'begin_alt_use', 'only_relevant_to_owner', 'always_relevant', 'hidden', 'net_use_owner_relevancy', 'auto_destroy_when_fi nished', 'can_be_damaged', 'find_camera_component_when_view_target', 'generate_overlap_events_during_level_streaming', 'enable_auto_lod_generation', 'replicates', 'initial_life_span', 'life_span', 'custom_time_dilation', ' net_dormancy', 'spawn_collision_handling_method', 'net_cull_distance_squared', 'net_update_frequency', 'min_net_update_frequency', 'net_pr iority', 'instigator', 'root_component', 'pivot_offset', 'sprite_scale', 'tags', 'on_take_any_damage', 'on_take_point_damage', 'on_take_radial_damage', 'on_actor_begin_overlap', 'on_actor_touch', 'on_actor_end_overlap', ' on_actor_un_touch', 'on_begin_cursor_over', 'on_end_cursor_over', 'on_clicked', 'on_released', 'on_input_touch_begin', 'on_input_touch_end' , 'on_input_touch_enter', 'on_input_touch_leave', 'on_actor_hit', 'on_destroyed', 'on_end_play', 'was_recently_rendered', 'tear_off', 'set_tick_group', 'set_tickable_when_paused', 'set_replicates', 'set_replicate_movement', 'set_owner', 'set_net_dormancy', 'set_life_span', 'set_is_temporarily_hidden_in_editor', 'set_folder_path', 'set_actor_tick_interval', ' set_actor_tick_enabled', 'set_tick_enabled', 'set_actor_scale3d', 'set_actor_relative_scale3d', 'set_actor_label', 'set_actor_hidden_in_game', 'set_actor_hidden', 'set_actor_enable_collision', 'remove_tick_prerequisite_component ', 'remove_tick_prerequisite_actor', 'receive_tick', 'receive_radial_damage', 'receive_point_damage', 'receive_hit', 'receive_end_pl ay', 'receive_destroyed', 'receive_begin_play', 'receive_any_damage', 'receive_actor_on_released', 'receive_actor_on_input_touch_leave', 'receive_actor_on_input_touch_enter', 'receive_actor_on_input_touch_end', ' receive_actor_on_input_touch_begin', 'receive_actor_on_clicked', 'receive_actor_end_overlap', 'receive_actor_untouch', 'receive_actor_end_cursor_ove r', 'receive_actor_begin_overlap', 'receive_actor_touch', 'receive_actor_begin_cursor_over', 'prestream_textures', 'make_noise', 'make_mid_for_material', 'teleport', 'set_actor_transform', 'set_actor_rotation', ' set_actor_relative_transform', 'set_actor_relative_rotation', 'set_actor_relative_location', 'set_actor_location_and_rotation', 'set_actor_location' , 'on_reset', 'on_end_view_target', 'on_become_view_target', 'get_components_by_class', 'get_actor_rotation', 'get_actor_location', 'detach_from_actor', 'destroy_component', 'destroy_actor', 'attach_to_component', 'attach_to_actor', 'add_actor_world_transform_keep_scale', 'add_actor_world_transform', 'add_actor_world_rotation', 'add_actor_world_offset', 'add _actor_local_transform', 'add_actor_local_rotation', 'add_actor_local_offset', 'is_temporarily_hidden_in_editor', 'is_selectable', 'is_overlapping_actor', 'is_hidden_ed_at_startup', 'is_hidden_ed', 'is_editable', 'is_child_actor ', 'is_actor_tick_enabled', 'is_actor_being_destroyed', 'has_authority', 'get_vertical_distance_to', 'get_velocity', 'get_actor_tran sform', 'get_tickable_when_paused', 'get_squared_horizontal_distance_to', 'get_squared_distance_to', 'get_remote_role', 'get_parent_component', 'get_parent_actor', 'get_owner', 'get_overlapping_components', 'get_touching_components ', 'get_overlapping_actors', 'get_touching_actors', 'get_local_role', 'get_life_span', 'get_instigator_controller', 'get_instigat or ', 'get_horizontal_dot_product_to', 'get_horizontal_distance_to', 'get_game_time_since_creation', 'get_folder_path', 'get_dot_product_to', 'get_distance_to', 'get_components_by_tag', 'get_components_by_interface', ' get_component_by_class', 'get_attach_parent_socket_name', 'get_attach_parent_actor', 'get_attached_actors', 'get_all_child_actors', 'get_actor_ up_vector', 'get_actor_time_dilation', 'get_actor_tick_interval', 'get_actor_scale3d', 'get_actor_right_vector', 'get_actor_relative_scale3d', 'get_actor_label', 'get_actor_forward_vector', 'get_actor_eyes_view_point', ' get_actor_enable_collision', 'get_actor_bounds', 'force_net_update', 'flush_net_dormancy', 'enable_input', 'disable_input', 'add_tick_prereq uisite_component', 'add_tick_prerequisite_actor', 'set_tick_prerequisite', 'actor_has_tag', 'has_tag', '__hash__', '__str__', '__init__', '__new__', '_post_init', 'cast', 'get_default_object', 'static_class', 'get_class', ' get_outer', 'get_typed_outer', 'get_outermost', 'get_name', 'get_fname', 'get_full_name', 'get_path_name', 'get_world', 'modify', 'rename ', 'get_editor_property', 'set_editor_property', 'set_editor_properties', 'call_method', '__repr__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__reduce_ex__', ' __reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']''' '''['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_post_init', '_wrapper_meta_data', 'call_met hod', 'cast', 'get_class', 'get_default_object', 'get_editor_property', 'get_float_value', 'get_fname', 'get_full_name', 'get_name', 'get_outer', 'get_outermost', 'get_path_name', 'get_time_range', 'get_typed_outer', 'get_value_range', 'get_world', 'modify', 'rename', 'set_editor_properties', 'set_editor_property', 'static_class']'''
""" Contains functions to fix failed TriMesh objects in the game engine. This module provides functions to parse a log file containing information about failed TriMesh objects and fix their build settings. The TriMesh objects are identified by their actor paths, and their scale is adjusted to a specified upscale factor. The fixed objects are then saved, and their scale is restored to the original value. Example: To fix failed TriMesh objects, call the `fix_level_failed_trimesh` function. fix_level_failed_trimesh() """ import os from typing import Iterable import unreal from Common import make_level_actors_dict, get_component_by_class from Extras import fixups_path, fixups_ext def parse_failed_trimesh_logfile(filepath: str) -> Iterable[str]: signature = "Failed to cook TriMesh: " assert os.path.isfile(filepath), f"Filepath with incorrect TriMesh isn't exist {filepath}" with open(filepath, "rt") as log_file: data = log_file.read() actor_paths = [] for line in data.splitlines(): line = line.strip() if not line: continue columns = line.split(maxsplit=2) message = columns[2] if not message.startswith(signature): continue path = message.lstrip(signature).rstrip(".") actor_paths.append(path) return actor_paths def get_actor_name_from_path(path: str): basename = os.path.basename(path) name, ext = os.path.splitext(basename) return name def fix_level_failed_trimesh(upscale: float = 10.0): world = unreal.EditorLevelLibrary.get_editor_world() level_name = world.get_fname() filepath = os.path.join(fixups_path, f"{level_name}.{fixups_ext}") failed_actor_paths = parse_failed_trimesh_logfile(filepath) level_actors = make_level_actors_dict() upscale3d = unreal.Vector(upscale, upscale, upscale) print(f"Upscale vector = {upscale3d}") actors = [] meshes = [] for actor_path in failed_actor_paths: name = get_actor_name_from_path(actor_path) actor = level_actors[name] print(f"Fix build settings of {actor}") # unreal.EditorLevelLibrary.set_actor_selection_state(actor, True) component = get_component_by_class(actor, unreal.StaticMeshComponent) static_mesh: unreal.StaticMesh = component.static_mesh build_settings = unreal.EditorStaticMeshLibrary.get_lod_build_settings(static_mesh, 0) build_settings.build_scale3d = upscale3d build_settings.remove_degenerates = False # According to documentation of EPIC this will make the same action as 'Apply Changes' unreal.EditorStaticMeshLibrary.set_lod_build_settings(static_mesh, 0, build_settings) actors.append(actor) meshes.append(static_mesh) unreal.EditorAssetLibrary.save_loaded_assets(meshes, only_if_is_dirty=False) for actor in actors: old_scale = actor.get_actor_scale3d() new_scale = old_scale / upscale actor.set_actor_scale3d(new_scale) print(f"Set actor scale name={actor.get_name()} -> old_scale={old_scale} new_scale={new_scale}") if __name__ == '__main__': fix_level_failed_trimesh()
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that uses the API to instantiate an HDA and then set the ramp points of a float ramp and a color ramp. """ import math import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.ramp_example_1_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def set_parameters(in_wrapper): print('set_parameters') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(set_parameters) # There are two ramps: heightramp and colorramp. The height ramp is a float # ramp. As an example we'll set the number of ramp points and then set # each point individually in_wrapper.set_ramp_parameter_num_points('heightramp', 6) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 0, 0.0, 0.1) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 1, 0.2, 0.6) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 2, 0.4, 1.0) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 3, 0.6, 1.4) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 4, 0.8, 1.8) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 5, 1.0, 2.2) # For the color ramp, as an example, we can set the all the points via an # array. in_wrapper.set_color_ramp_parameter_points('colorramp', ( unreal.HoudiniPublicAPIColorRampPoint(position=0.0, value=unreal.LinearColor.GRAY), unreal.HoudiniPublicAPIColorRampPoint(position=0.5, value=unreal.LinearColor.GREEN), unreal.HoudiniPublicAPIColorRampPoint(position=1.0, value=unreal.LinearColor.RED), )) def print_parameters(in_wrapper): print('print_parameters') in_wrapper.on_post_processing_delegate.remove_callable(print_parameters) # Print the ramp points directly print('heightramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('heightramp'))) heightramp_data = in_wrapper.get_float_ramp_parameter_points('heightramp') if not heightramp_data: print('\tNone') else: for idx, point_data in enumerate(heightramp_data): print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) print('colorramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('colorramp'))) colorramp_data = in_wrapper.get_color_ramp_parameter_points('colorramp') if not colorramp_data: print('\tNone') else: for idx, point_data in enumerate(colorramp_data): print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) # Print all parameter values param_tuples = in_wrapper.get_parameter_tuples() print('parameter tuples: {}'.format(len(param_tuples) if param_tuples else 0)) if param_tuples: for param_tuple_name, param_tuple in param_tuples.items(): print('parameter tuple name: {}'.format(param_tuple_name)) print('\tbool_values: {}'.format(param_tuple.bool_values)) print('\tfloat_values: {}'.format(param_tuple.float_values)) print('\tint32_values: {}'.format(param_tuple.int32_values)) print('\tstring_values: {}'.format(param_tuple.string_values)) if not param_tuple.float_ramp_points: print('\tfloat_ramp_points: None') else: print('\tfloat_ramp_points:') for idx, point_data in enumerate(param_tuple.float_ramp_points): print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) if not param_tuple.color_ramp_points: print('\tcolor_ramp_points: None') else: print('\tcolor_ramp_points:') for idx, point_data in enumerate(param_tuple.color_ramp_points): print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Set the float and color ramps on post instantiation, before the first # cook. _g_wrapper.on_post_instantiation_delegate.add_callable(set_parameters) # Print the parameter state after the cook and output creation. _g_wrapper.on_post_processing_delegate.add_callable(print_parameters) if __name__ == '__main__': run()
import unreal from Lib import __lib_topaz__ as topaz import importlib importlib.reload(topaz) origin = unreal.load_asset('/project/.A_Head_Brow') lodset = origin.hair_groups_lod HairGroupLOD = lodset[0] asset_list = topaz.get_selected_assets() for each in asset_list: isGroom = each.__class__ == unreal.GroomAsset eachname = each.get_full_name() sourceFilename = each.get_editor_property("asset_import_data").get_first_filename() unreal.log(sourceFilename) #print(eachname) if isGroom and sourceFilename != '': _hair_groups_lod_ = [] lodLength = len(each.hair_groups_lod) print(lodLength) for i in range(lodLength) : _hair_groups_lod_.append(HairGroupLOD) each.hair_groups_lod = _hair_groups_lod_ print(len(_hair_groups_lod_)) #unreal.EditorAssetLibrary.checkout_asset(eachname) ## 아직 버그있음
# coding: utf-8 import os import unreal # import AssetFunction_1 as af # reload(af) # af.importMyAssets() asset_folder = 'D:/project/' texture_jpg = os.path.join(asset_folder, 'dear.jpg').replace('\\','/') sound_mp3 = os.path.join(asset_folder, 'easy.mp3').replace('\\','/') def importMyAssets(): texture_task = bulidImportTask(texture_jpg, '/project/') sound_task = bulidImportTask(sound_mp3, '/project/') executeImportTasks([texture_task, sound_task]) # ! 设置导入资产属性 def bulidImportTask(filename, destination_path): task = unreal.AssetImportTask() task.set_editor_property('automated', True) task.set_editor_property('destination_name', '') task.set_editor_property('destination_path', destination_path) task.set_editor_property('filename', filename) task.set_editor_property('replace_existing', True) task.set_editor_property('save', True) return task def executeImportTasks(tasks): unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks) for task in tasks: for path in task.get_editor_property('imported_object_paths'): print 'Imported {}'.format(path)
import unreal print("This is for begining Unreal-Python script \n Type : from importlib import reload") # 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 : 함수 호출 테스트 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_reacting()
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-debugeachsave") args = parser.parse_args() #print(args.vrm) ###### rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller() else: c = rig.controller g = c.get_graph() n = g.get_nodes() mesh = rig.get_preview_mesh() morphList = mesh.get_all_morph_target_names() morphListWithNo = morphList[:] morphListRenamed = [] morphListRenamed.clear() for i in range(len(morphList)): morphListWithNo[i] = '{}'.format(morphList[i]) print(morphListWithNo) while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.remove_element(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) h_con.import_curves(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) dset = rig.get_editor_property('rig_graph_display_settings') dset.set_editor_property('node_run_limit', 0) rig.set_editor_property('rig_graph_display_settings', dset) ###### root key = unreal.RigElementKey(unreal.RigElementType.NULL, 'MorphControlRoot_s') space = hierarchy.find_null(key) if (space.get_editor_property('index') < 0): space = h_con.add_null('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE) else: space = key a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() print(a) # 配列ノード追加 values_forCurve:unreal.RigVMStructNode = [] items_forControl:unreal.RigVMStructNode = [] items_forCurve:unreal.RigVMStructNode = [] for node in n: print(node) print(node.get_node_title()) # set curve num if (node.get_node_title() == 'For Loop'): print(node) pin = node.find_pin('Count') print(pin) c.set_pin_default_value(pin.get_pin_path(), str(len(morphList)), True, False) # curve name array pin if (node.get_node_title() == 'Select'): print(node) pin = node.find_pin('Values') print(pin) print(pin.get_array_size()) print(pin.get_default_value()) values_forCurve.append(pin) # items if (node.get_node_title() == 'Collection from Items'): if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())): items_forCurve.append(node.find_pin('Items')) if (str(c.get_pin_default_value(node.find_pin('Items').get_pin_path())).find('_ALL_Angry_c') >= 0): items_forControl.append(node.find_pin('Items')) print(items_forControl) print(values_forCurve) # reset controller for e in reversed(hierarchy.get_controls()): if (len(hierarchy.get_parents(e)) == 0): continue if (hierarchy.get_parents(e)[0].name == 'MorphControlRoot_s'): #if (str(e.name).rstrip('_c') in morphList): # continue print('delete') #print(str(e.name)) h_con.remove_element(e) # curve array for v in values_forCurve: c.clear_array_pin(v.get_pin_path()) for morph in morphList: tmp = "{}".format(morph) c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False) # curve controller for morph in morphListWithNo: name_c = "{}_c".format(morph) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) settings = unreal.RigControlSettings() settings.shape_color = [1.0, 0.0, 0.0, 1.0] settings.control_type = unreal.RigControlType.FLOAT try: control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): k = h_con.add_control(name_c, space, settings, unreal.RigControlValue()) control = hierarchy.find_control(k) except: k = h_con.add_control(name_c, space, settings, unreal.RigControlValue()) control = hierarchy.find_control(k) shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) hierarchy.set_control_shape_transform(k, shape_t, True) morphListRenamed.append(control.key.name) if (args.debugeachsave == '1'): try: unreal.EditorAssetLibrary.save_loaded_asset(rig) except: print('save error') #unreal.SystemLibrary.collect_garbage() # eye controller eyeControllerTable = [ "VRM4U_EyeUD_left", "VRM4U_EyeLR_left", "VRM4U_EyeUD_right", "VRM4U_EyeLR_right", ] # eye controller for eyeCon in eyeControllerTable: name_c = "{}_c".format(eyeCon) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) settings = unreal.RigControlSettings() settings.shape_color = [1.0, 0.0, 0.0, 1.0] settings.control_type = unreal.RigControlType.FLOAT try: control = hierarchy.find_control(key) if (control.get_editor_property('index') < 0): k = h_con.add_control(name_c, space, settings, unreal.RigControlValue()) control = hierarchy.find_control(k) except: k = h_con.add_control(name_c, space, settings, unreal.RigControlValue()) control = hierarchy.find_control(k) shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) hierarchy.set_control_shape_transform(k, shape_t, True) # curve Control array for v in items_forControl: c.clear_array_pin(v.get_pin_path()) for morph in morphListRenamed: tmp = '(Type=Control,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False) # curve Float array for v in items_forCurve: c.clear_array_pin(v.get_pin_path()) for morph in morphList: tmp = '(Type=Curve,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False)
#레벨에 선택된 액터중 sm actor만 골라서 내부에 sm이 비어있으면 삭제 import unreal from Lib import __lib_topaz__ as topaz import importlib importlib.reload(topaz) selected_Level_Actors = topaz.get_selected_level_actors() for each in selected_Level_Actors : if each.__class__ == unreal.StaticMeshActor : static_mesh_component = each.static_mesh_component get_static_mesh = static_mesh_component.static_mesh if get_static_mesh == None : print(each.get_actor_label(),"Static Mesh is Empty") unreal.EditorLevelLibrary.destroy_actor(each) else : pass else : pass
import unreal actorsubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) assetsubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) layersubsystem = unreal.get_editor_subsystem(unreal.LayersSubsystem) sm = assetsubsystem.load_asset("/project/") world = layersubsystem.get_world() posToTest = unreal.Vector(0,0,0) listOfObjectTypeQuery = unreal.Array(unreal.ObjectTypeQuery) listOfObjectTypeQuery.append(unreal.ObjectTypeQuery.OBJECT_TYPE_QUERY1) listOfObjectTypeQuery.append(unreal.ObjectTypeQuery.OBJECT_TYPE_QUERY2) hit = unreal.SystemLibrary.line_trace_single_for_objects(world,unreal.Vector(posToTest.x,posToTest.y,500),unreal.Vector(posToTest.x,posToTest.y,0),listOfObjectTypeQuery,True,unreal.Array(unreal.Actor),unreal.DrawDebugTrace.NONE,True) if hit != None: print(hit) print(hit.to_tuple()) print(hit.to_tuple()[4]) print(hit.to_tuple()[5])#impact_point print(hit.to_tuple()[6]) actorsubsystem.spawn_actor_from_object(sm,hit.to_tuple()[5])
# coding: utf-8 import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## meta 取得 a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] for e in reversed(h_mod.get_elements()): if (e.type != unreal.RigElementType.BONE): h_mod.remove_element(e) name_to_control = {"dummy_for_table" : None} gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2]) for e in h_mod.get_elements(): print(e.name) if (e.type != unreal.RigElementType.BONE): continue bone = h_mod.get_bone(e) parentName = "{}".format(bone.get_editor_property('parent_name')) #print("parent==") #print(parentName) cur_parentName = parentName + "_c" name_s = "{}".format(e.name) + "_s" name_c = "{}".format(e.name) + "_c" space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL) control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[0.1, 0.1, 1.0, 1.0], ) h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e)) cc = h_mod.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) #cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_mod.set_control(cc) name_to_control[name_c] = cc c = None try: i = list(name_to_control.keys()).index(cur_parentName) except: i = -1 if (i >= 0): c = name_to_control[cur_parentName] if (cc != None): if ("{}".format(e.name) in meta.humanoid_bone_table.values() ): cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0)) h_mod.set_control(cc) else: cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0)) h_mod.set_control(cc) c = rig.controller g = c.get_graph() n = g.get_nodes() # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) if (collectionItem_forBone != None): items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) for bone_h in meta.humanoid_bone_table: bone_m = meta.humanoid_bone_table[bone_h] try: i = humanoidBoneList.index(bone_h.lower()) except: i = -1 if (i >= 0): tmp = '(Type=Bone,Name=' tmp += "{}".format(bone_m).lower() tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) for e in h_mod.get_elements(): print(e.name) if (e.type == unreal.RigElementType.CONTROL): tmp = '(Type=Control,Name=' tmp += "{}".format(e.name) tmp += ')' c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
import unreal import random,glob def buildMeshImportOptions(): options = unreal.FbxImportUI() skeleton = unreal.EditorAssetLibrary.load_asset('/project/') options.set_editor_property('import_as_skeletal',True) options.set_editor_property('import_materials',True) options.set_editor_property('import_mesh',True) options.set_editor_property('skeleton',skeleton) return options def texturefactory(): f = unreal.TextureFactory() f.set_editor_property('create_material',False) return f def importTextureTask(filename,destination_path="/project/"): task = unreal.AssetImportTask() task.set_editor_property('automated', True) task.set_editor_property('destination_path', destination_path) task.set_editor_property('filename', filename) task.set_editor_property('replace_existing', True) task.set_editor_property('save', True) task.set_editor_property('factory', texturefactory()) return task def importFBXTask(filename,destination_path='/project/'): task= unreal.AssetImportTask() task.set_editor_property('automated',True) task.set_editor_property('destination_path',destination_path) task.set_editor_property('filename',filename) task.set_editor_property('replace_existing',True) task.set_editor_property('save',True) task.set_editor_property('options', buildMeshImportOptions()) return task def executeImportTask(tasks): unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks) for task in tasks: print("File:" + task.get_editor_property('filename')) for path in task.get_editor_property('imported_object_paths'): print("Imported: "+ path) def mass_import_textures(start,end): #files = glob.glob("/project/*.jpg") files= glob.glob('/project/-co-parsing-master/ccp_patches/*.png') files.sort() tasks = [importTextureTask(f) for f in files[start:end]] executeImportTask(tasks) def mass_import_fbx(start,end): files = ['f:/project/{:04d}A.fbx'.format(i) for i in range(start,end+1)] tasks = [importFBXTask(f) for f in files] executeImportTask(tasks) def spawnActor(tps,x,mesh): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') loc = unreal.Vector(random.uniform(-1500,-1000),random.uniform(1200,7000),129) rotation = unreal.Rotator(0,0,random.uniform(0,360)) actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class,loc,rotation) actor.set_editor_property("Path",tps) actor.mesh.set_editor_property("skeletal_mesh",mesh) actor.set_actor_label(x) return actor def executeSpawnTask(start=1,end=1001): # laod skeletal mesh rpc=['uplow{:04d}A'.format(i) for i in range(start,end)] mesh_list = [] for i in range(len(rpc)): mesh = unreal.EditorAssetLibrary.load_asset("/project/"+rpc[i]) mesh_list.append(mesh) quantity = len(rpc) tp_list=[] allactors = unreal.EditorLevelLibrary.get_all_level_actors() for a in allactors: if type(a)==unreal.TargetPoint: tp_list.append(a) print(tp_list) with unreal.ScopedSlowTask(quantity,"actor spawning") as sst: sst.make_dialog(True) for x in range(quantity): tps = unreal.Array(unreal.TargetPoint) t = random.sample(tp_list, 5) for tcount in range(4,10): tps.append(tp_list[tcount]) for tcount in range(0,4): tps.append(tp_list[tcount]) if sst.should_cancel(): break sst.enter_progress_frame(1) spawnActor(tps,rpc[x],mesh_list[x]) def changeRoughnessToOne(start,end): rpc = ['uplow{:04d}A'.format(i) for i in range(start, end)] with unreal.ScopedSlowTask(1000, "actor spawning") as sst: for i in unreal.EditorUtilityLibrary.get_selected_assets(): mat=i ts_TextureNodeBc = unreal.MaterialEditingLibrary.create_material_expression(mat,unreal.MaterialExpressionConstant,0,0) ts_TextureNodeBc.r=1 unreal.MaterialEditingLibrary.connect_material_property(ts_TextureNodeBc,"",unreal.MaterialProperty.MP_ROUGHNESS) sst.enter_progress_frame(1) def ana_mesh_materials(): rpc = ['mhview_{:04d}A'.format(i) for i in range(1, 800)] mesh_mat=dict() for i in range(len(rpc)): mesh = unreal.EditorAssetLibrary.load_asset("/project/" + rpc[i]) if mesh is None:break materials = mesh.materials names=[] if len(materials) != 16: print("{} {}".format(rpc[i],len(materials))) def del_ana_mesh_materials(): rpc = ['mhmodel_view_{:04d}A'.format(i) for i in range(1, 800)] mesh_mat=dict() for i in range(len(rpc)): mesh = unreal.EditorAssetLibrary.load_asset("/project/" + rpc[i]) if mesh is None:break materials = mesh.materials names=[] if len(materials) != 16: print("{} {}".format(rpc[i],len(materials))) unreal.EditorAssetLibrary.delete_loaded_asset(mesh) def get_mesh_materials(): rpc = ['uplow{:04d}A'.format(i) for i in range(1, 1801)] mesh_mat=dict() for i in range(1000,1800): mesh = unreal.EditorAssetLibrary.load_asset("/project/" + rpc[i]) materials = mesh.materials names=[] for m in materials: name = str(m.material_slot_name) names.append(name) mesh_mat[rpc[i]]=names import json json.dump(mesh_mat,open("/project/.json",'w')) def set_shading_model(): with unreal.ScopedSlowTask(1000, " msm changing") as sst: for i in unreal.EditorUtilityLibrary.get_selected_assets(): m=i m.set_editor_property('shading_model', unreal.MaterialShadingModel.MSM_DEFAULT_LIT) sst.enter_progress_frame(1) def set_mhbp_randtexture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) mats = unreal.EditorUtilityLibrary.get_selected_assets() mat_a = unreal.Array(unreal.SkeletalMesh) for m in mats: mat_a.append(m) cdo.set_editor_property("mesh_list", mat_a) def set_mhbp_mesh_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) mats = unreal.EditorUtilityLibrary.get_selected_assets() mat_a = unreal.Array(unreal.SkeletalMesh) for m in mats: mat_a.append(m) cdo.set_editor_property("mesh_list", mat_a) def set_top_texture_list_for75(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob , random files = glob.glob("/project/*.png") mat_a = unreal.Array(str) mat_a.extend(files) print(files[:10]) cdo.set_editor_property("clo_texture", mat_a) def set_top_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob , random files = glob.glob("/project/*.png")+glob.glob("/project/*.png") files = random.sample(files,2000) tops = ['jacket','blouse','coat','sweater','blazer','cardigan','t-shirt','shirt','suit','sweatshirt', 'vest','jumper','bodysuit','top','romper'] for t in tops: files.extend(glob.glob("/project/{}*.png".format(t))) mat_a = unreal.Array(str) mat_a.extend(files) print(files[:10]) cdo.set_editor_property("top_texture", mat_a) def set_rnd_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob,random files = glob.glob("/project/*.png")+glob.glob("/project/*.png") files = random.sample(files,100) mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("rnd_texture", mat_a) def set_bag_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob,random files = [] downs = ['bag','purse'] for t in downs: files.extend(glob.glob("/project/{}*.png".format(t))) mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("bag_texture", mat_a) def set_scarf_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob,random files = [] downs = ['scarf'] for t in downs: files.extend(glob.glob("/project/{}*.png".format(t))) mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("scarf_texture", mat_a) def set_black_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob import glob, random files = glob.glob("/project/*.png") + glob.glob("/project/*.png") files = random.sample(files, 2000) tops = ['jacket', 'blouse', 'coat', 'sweater', 'blazer', 'cardigan', 't-shirt', 'shirt', 'suit', 'sweatshirt', 'vest', 'jumper', 'bodysuit', 'top', 'romper'] for t in tops: files.extend(glob.glob("/project/{}*.png".format(t))) files.extend(glob.glob("/project/*g")) mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("topblack_texture", mat_a) files = [] files = glob.glob("/project/*.png") files = random.sample(files,2000) files.extend(glob.glob("F:/project/*.png")+glob.glob("/project/*.png")) downs = ['pants','jeans','shorts','skirt','leggings','tights','stockings'] for t in downs: files.extend(glob.glob("/project/{}*.png".format(t))) files.extend(glob.glob("/project/*g")) mat_b = unreal.Array(str) mat_b.extend(files) cdo.set_editor_property("downblack_texture", mat_b) def set_rp_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob files = glob.glob("/project/*g") mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("black_texture", mat_a) def set_down_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob,random files = glob.glob("/project/*.png") files = random.sample(files,2000) files.extend(glob.glob("F:/project/*.png")+glob.glob("/project/*.png")) downs = ['pants','jeans','shorts','skirt','leggings','tights','stockings'] for t in downs: files.extend(glob.glob("/project/{}*.png".format(t))) mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("down_texture", mat_a) def set_ccp_texture_list(): actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') cdo = unreal.get_default_object(actor_class) import glob,random files = glob.glob("/project/*.png") mat_a = unreal.Array(str) mat_a.extend(files) cdo.set_editor_property("ccp_texture", mat_a) if __name__=='__main__': executeSpawnTask()
import sys import unreal def create_level_sequence_transform_track(asset_name, length_seconds=600, package_path='/Game/'): sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name, package_path, unreal.LevelSequence, unreal.LevelSequenceFactoryNew()) actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/project/') actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, [-450.0, 1030.0, 230.0], [0, 0, 0]) binding = sequence.add_possessable(actor) transform_track = binding.add_track(unreal.MovieScene3DTransformTrack) transform_section = transform_track.add_section() transform_section.set_start_frame_seconds(0) transform_section.set_end_frame_seconds(length_seconds) ## now do media track media_track = sequence.add_master_track(unreal.MovieSceneMediaTrack) media_track.set_editor_property("display_name", "Media") media_section = media_track.add_section() img_source = unreal.AssetToolsHelpers.get_asset_tools().create_asset("MS_" + asset_name, '/Game', unreal.ImgMediaSource, None) image_path = unreal.SystemLibrary.get_project_content_directory() + "/project/.png" img_source.set_sequence_path(image_path) media_section.media_source = img_source media_texture = unreal.AssetToolsHelpers.get_asset_tools().create_asset("MT_" + asset_name, '/Game/', unreal.MediaTexture, unreal.MediaTextureFactoryNew()) media_section.media_texture = media_texture media_section.set_range(0,30) # Now create a new material instance (from base chromakey bat) and apply to newly created actor material_instance = unreal.AssetToolsHelpers.get_asset_tools().create_asset("MI_" + asset_name, '/Game/', unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) base_material = unreal.load_asset('/project/') material_instance.set_editor_property('parent', base_material) media_texture = unreal.load_asset('/Game/'+"MT_" + asset_name) unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, 'Texture', media_texture) unreal.MaterialEditingLibrary.update_material_instance(material_instance) placeholder_mat = unreal.load_asset('/project/') unreal.EditorLevelLibrary.replace_mesh_components_materials_on_actors([actor], placeholder_mat, material_instance) return sequence def add_transform_keys(sequence): transforms = [] float_list = [] transform_path = unreal.SystemLibrary.get_project_content_directory() + '/project/.txt' with open(transform_path, 'r') as (f): for line in f: line.strip() line = line.split('|') for item in line: new_item = item.split(',') for i in new_item: i.strip() float_list.append(float(i)) n = 9 for i in xrange(0, len(float_list), n): transforms.append(float_list[i:i + n]) print transforms for binding in sequence.get_bindings(): for track in binding.get_tracks(): print track for section in track.get_sections(): print '\tSection: ' + section.get_name() for channel in section.get_channels(): print '\tChannel: ' + channel.get_name() name = channel.get_name() if name == 'Location.X': add_keys_to_transform_channel(0, transforms, channel) elif name == 'Location.Y': add_keys_to_transform_channel(1, transforms, channel) elif name == 'Location.Z': add_keys_to_transform_channel(2, transforms, channel) elif name == 'Rotation.X': add_keys_to_transform_channel(3, transforms, channel) elif name == 'Rotation.Y': add_keys_to_transform_channel(4, transforms, channel) elif name == 'Rotation.Z': add_keys_to_transform_channel(5, transforms, channel) elif name == 'Scale.X': add_keys_to_transform_channel(6, transforms, channel) elif name == 'Scale.Y': add_keys_to_transform_channel(7, transforms, channel) elif name == 'Scale.Z': add_keys_to_transform_channel(8, transforms, channel) def add_keys_to_transform_channel(transform_component, transforms, channel): frame_number = unreal.FrameNumber() idx = 0 for transform in transforms: val = transform[transform_component] channel.add_key(unreal.TimeManagementLibrary.add_frame_number_integer(frame_number, idx), val) idx += 1 if __name__ == "__main__": asset_name = sys.argv[1] sequence = create_level_sequence_transform_track(asset_name) add_transform_keys(sequence)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that uses the API to instantiate an HDA and then set the ramp points of a float ramp and a color ramp. """ import math import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.ramp_example_1_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def set_parameters(in_wrapper): print('set_parameters') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(set_parameters) # There are two ramps: heightramp and colorramp. The height ramp is a float # ramp. As an example we'll set the number of ramp points and then set # each point individually in_wrapper.set_ramp_parameter_num_points('heightramp', 6) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 0, 0.0, 0.1) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 1, 0.2, 0.6) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 2, 0.4, 1.0) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 3, 0.6, 1.4) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 4, 0.8, 1.8) in_wrapper.set_float_ramp_parameter_point_value('heightramp', 5, 1.0, 2.2) # For the color ramp, as an example, we can set the all the points via an # array. in_wrapper.set_color_ramp_parameter_points('colorramp', ( unreal.HoudiniPublicAPIColorRampPoint(position=0.0, value=unreal.LinearColor.GRAY), unreal.HoudiniPublicAPIColorRampPoint(position=0.5, value=unreal.LinearColor.GREEN), unreal.HoudiniPublicAPIColorRampPoint(position=1.0, value=unreal.LinearColor.RED), )) def print_parameters(in_wrapper): print('print_parameters') in_wrapper.on_post_processing_delegate.remove_callable(print_parameters) # Print the ramp points directly print('heightramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('heightramp'))) heightramp_data = in_wrapper.get_float_ramp_parameter_points('heightramp') if not heightramp_data: print('\tNone') else: for idx, point_data in enumerate(heightramp_data): print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) print('colorramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('colorramp'))) colorramp_data = in_wrapper.get_color_ramp_parameter_points('colorramp') if not colorramp_data: print('\tNone') else: for idx, point_data in enumerate(colorramp_data): print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) # Print all parameter values param_tuples = in_wrapper.get_parameter_tuples() print('parameter tuples: {}'.format(len(param_tuples) if param_tuples else 0)) if param_tuples: for param_tuple_name, param_tuple in param_tuples.items(): print('parameter tuple name: {}'.format(param_tuple_name)) print('\tbool_values: {}'.format(param_tuple.bool_values)) print('\tfloat_values: {}'.format(param_tuple.float_values)) print('\tint32_values: {}'.format(param_tuple.int32_values)) print('\tstring_values: {}'.format(param_tuple.string_values)) if not param_tuple.float_ramp_points: print('\tfloat_ramp_points: None') else: print('\tfloat_ramp_points:') for idx, point_data in enumerate(param_tuple.float_ramp_points): print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) if not param_tuple.color_ramp_points: print('\tcolor_ramp_points: None') else: print('\tcolor_ramp_points:') for idx, point_data in enumerate(param_tuple.color_ramp_points): print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format( idx, point_data.position, point_data.value, point_data.interpolation )) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Set the float and color ramps on post instantiation, before the first # cook. _g_wrapper.on_post_instantiation_delegate.add_callable(set_parameters) # Print the parameter state after the cook and output creation. _g_wrapper.on_post_processing_delegate.add_callable(print_parameters) if __name__ == '__main__': run()
# Should be used with internal UE API in later versions of UE """ Auto create materials of Layout System based on data from materials_layout.json """ import re import unreal import os import json DO_OVERWRITE_EXISTING_MATERIALS = True with open("C:/project/ Projects/project/" "MaterialAutoAssign/project/.json", "r") as f: materials_data = json.load(f) # CHANGE ME EC_PARENT_MATERIAL = "/project/.M_Eldar01" # CHANGE ME MY_PARENT_MATERIAL = "/project/" MATERIAL_LOC_PREFIX = "D:/project/" MATERIAL_FILTER_PREFIX = "/project/" materials_data = {k: v for k, v in materials_data.items() if "Parent" in v and EC_PARENT_MATERIAL in v["Parent"]} def set_material_instance_texture(material_instance_asset, material_parameter, texture_path): if texture_path is None: return if not unreal.EditorAssetLibrary.does_asset_exist(texture_path): unreal.log_warning("Can't find texture: " + texture_path) return False tex_asset = unreal.EditorAssetLibrary.find_asset_data(texture_path).get_asset() return unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance_asset, material_parameter, tex_asset) base_material = unreal.EditorAssetLibrary.find_asset_data(MY_PARENT_MATERIAL) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() def create_material_instance(material_path, parameters_names_to_values): print(" ".join([str(x) for x in parameters_names_to_values.values()])) material_instance_name = os.path.basename(material_path) material_instance_folder = os.path.dirname(material_path) if unreal.EditorAssetLibrary.does_asset_exist(material_path): print(f"Warning: {material_path} already exists") if DO_OVERWRITE_EXISTING_MATERIALS: # material_instance_asset = unreal.EditorAssetLibrary.find_asset_data(material_path).get_asset() unreal.EditorAssetLibrary.delete_asset(material_path) else: return material_instance_asset = asset_tools.create_asset(material_instance_name, material_instance_folder, unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) unreal.MaterialEditingLibrary.set_material_instance_parent(material_instance_asset, base_material.get_asset()) for parameter_name, parameter_value in parameters_names_to_values.items(): set_material_instance_texture(material_instance_asset, parameter_name, parameter_value) unreal.EditorAssetLibrary.save_asset(material_path) asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() def get_texture_data(material_data): result = {} texture_data_key = None for k, v in material_data.items(): if k.startswith("TextureParameterValues"): texture_data_key = k for _, data in material_data[texture_data_key].items(): result_key = data["ParameterName"] result_value = data["ParameterValue"] result_value = re.search(r"Texture2D'(?P<path>[/a-zA-Z0-9_-]+)\.[a-zA-Z0-9_-]+'", result_value) if not result_value: raise ValueError(f"{data['ParameterValue']} doesn't match regex") result_value = result_value.group("path") result_value = result_value.replace("/project/", "/Game/") result[result_key] = result_value return result for material_path, material_data in materials_data.items(): material_game_path = material_path.replace(MATERIAL_LOC_PREFIX, "/Game/").replace(".json", "") if not material_path.startswith(MATERIAL_FILTER_PREFIX): continue texture_data = get_texture_data(material_data) texture_data = {k: v.replace("/project/", "/Game/") for k, v in texture_data.items()} ec_opaque_parameter_data = {"BaseColor": texture_data.get("Base Color", None), "Normal": texture_data.get("Normal Map", None), "Roughness": texture_data.get("Roughness Map", None), "Metal": texture_data.get("Metallic Map", None), "Specular": None} ec_opaque_masked_parameter_data = {"BaseColor": texture_data.get("Base Color", None), "Normal": texture_data.get("Normal Map", None), "Roughness": texture_data.get("Roughness Map", None), "Metal": texture_data.get("Metallic Map", None), "OpacityMask": texture_data.get("Opacity Map", None)} vertex_parameter_data = { "Base Color 1": texture_data.get("Base Color_A", None), "Base Color 2": texture_data.get("Base Color_B", None), "Metallic 1": texture_data.get("Metallic_A", None), "Metallic 2": texture_data.get("Metallic_B", None), "Normal 1": texture_data.get("Normal_A", None), "Normal 2": texture_data.get("Normal_B", None), "Roughness 1": texture_data.get("R_A", None), "Roughness 2": texture_data.get("R_B", None) } ec_bodypart_parameter_data = { "BaseColor": None, "Mask": texture_data.get("Color_Mask", None), "Metal": texture_data.get("Metallic", None), "Roughness": texture_data.get("Roughness", None), "Normal": texture_data.get("Normal_Map", None) } ec_sm_unique_parameter_data = { "BaseColor": texture_data.get("Base_Color", None), "Mask": texture_data.get("Color_Mask", None), "Metal": texture_data.get("Metallic", None), "Roughness": texture_data.get("Roughness", None), "Normal": texture_data.get("Normal_Map", None) } create_material_instance(material_game_path, ec_sm_unique_parameter_data)
import unreal file_a = "/project/.fbx" file_b = "/project/.fbx" imported_scenes_path = "/project/" print 'Preparing import options...' advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions() advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512) advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64) advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True) advanced_mesh_options.set_editor_property('remove_degenerates', True) base_options = unreal.DatasmithImportBaseOptions() base_options.set_editor_property('include_geometry', True) base_options.set_editor_property('include_material', True) base_options.set_editor_property('include_light', True) base_options.set_editor_property('include_camera', True) base_options.set_editor_property('include_animation', True) base_options.set_editor_property('static_mesh_options', advanced_mesh_options) base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL) base_options.set_editor_property('asset_options', []) # Not used dg_options = unreal.DatasmithDeltaGenImportOptions() dg_options.set_editor_property('merge_nodes', False) dg_options.set_editor_property('optimize_duplicated_nodes', False) dg_options.set_editor_property('remove_invisible_nodes', False) dg_options.set_editor_property('simplify_node_hierarchy', False) dg_options.set_editor_property('import_var', True) dg_options.set_editor_property('var_path', "") dg_options.set_editor_property('import_pos', True) dg_options.set_editor_property('pos_path', "") dg_options.set_editor_property('import_tml', True) dg_options.set_editor_property('tml_path', "") dg_options.set_editor_property('textures_dir', "") dg_options.set_editor_property('intermediate_serialization', unreal.DatasmithDeltaGenIntermediateSerializationType.DISABLED) dg_options.set_editor_property('colorize_materials', False) dg_options.set_editor_property('generate_lightmap_u_vs', False) dg_options.set_editor_property('import_animations', True) # Direct import to scene and assets: print 'Importing directly to scene...' unreal.DeltaGenLibrary.import_(file_a, imported_scenes_path, base_options, None, False) #2-stage import step 1: print 'Parsing to scene object...' scene = unreal.DatasmithDeltaGenSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, dg_options) print 'Resulting datasmith scene: ' + str(scene) print '\tProduct name: ' + str(scene.get_product_name()) print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors())) print '\tLight actor count: ' + str(len(scene.get_all_light_actors())) print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors())) print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors())) print '\tMaterial count: ' + str(len(scene.get_all_materials())) print '\tAnimationTimeline count: ' + str(len(scene.get_all_animation_timelines())) print '\tVariant count: ' + str(len(scene.get_all_variants())) # Modify one of the Timelines # Warning: The Animation nested structure is all USTRUCTs, which are value types, and the Array accessor returns # a copy. Meaning something like timeline[0].name = 'new_name' will set the name on the COPY of anim_nodes[0] timelines = scene.get_all_animation_timelines() if len(timelines) > 0: tim_0 = timelines[0] old_name = tim_0.name print 'Timeline old name: ' + old_name tim_0.name += '_MODIFIED' modified_name = tim_0.name print 'Anim node modified name: ' + modified_name timelines[0] = tim_0 scene.set_all_animation_timelines(timelines) # Check modification new_timelines = scene.get_all_animation_timelines() print 'Anim node retrieved modified name: ' + new_timelines[0].name assert new_timelines[0].name == modified_name, "Node modification didn't work!" # Restore to previous state tim_0 = new_timelines[0] tim_0.name = old_name new_timelines[0] = tim_0 scene.set_all_animation_timelines(new_timelines) # 2-stage import step 2: print 'Importing assets and actors...' result = scene.import_scene() print 'Import results: ' print '\tImported actor count: ' + str(len(result.imported_actors)) print '\tImported mesh count: ' + str(len(result.imported_meshes)) print '\tImported level sequences: ' + str([a.get_name() for a in result.animations]) print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name()) if result.import_succeed: print 'Import succeeded!' else: print 'Import failed!'
import unreal def get_selected_assets(): return unreal.EditorAssetLibrary2.get_selected() def find_replace(assets, find_str, replace_str): for asset in assets: current_name = asset.get_name() new_name = current_name.replace(find_str, replace_str) unreal.EditorAssetLibrary2.rename(asset, new_name) find = 'SM_' replace = '' selected_assets = get_selected_assets() find_replace(selected_assets, find, replace)
import unreal def create_animation_sequence(skeleton, sequence_name, package_path): """Create a new animation sequence.""" factory = unreal.AnimationSequenceFactory() factory.set_editor_property('TargetSkeleton', skeleton) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() return asset_tools.create_asset(sequence_name, package_path, unreal.AnimationSequence, factory) def add_animation_notify(sequence, notify_class, time, notify_name): """Add an animation notify to a sequence.""" if isinstance(sequence, unreal.AnimationSequence): notify = sequence.add_notify(notify_class, time) notify.set_editor_property('NotifyName', notify_name) return notify return None def create_animation_montage(skeleton, montage_name, package_path): """Create a new animation montage.""" factory = unreal.AnimationMontageFactory() factory.set_editor_property('TargetSkeleton', skeleton) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() return asset_tools.create_asset(montage_name, package_path, unreal.AnimationMontage, factory) def add_section_to_montage(montage, section_name, start_time, end_time): """Add a section to an animation montage.""" if isinstance(montage, unreal.AnimationMontage): return montage.add_section(section_name, start_time, end_time) return None def create_animation_blendspace(skeleton, blendspace_name, package_path): """Create a new animation blendspace.""" factory = unreal.BlendSpaceFactory1D() factory.set_editor_property('TargetSkeleton', skeleton) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() return asset_tools.create_asset(blendspace_name, package_path, unreal.BlendSpace1D, factory) def add_animation_to_blendspace(blendspace, animation, position): """Add an animation to a blendspace.""" if isinstance(blendspace, unreal.BlendSpace1D): return blendspace.add_animation(animation, position) return None def create_animation_state_machine(skeleton, state_machine_name, package_path): """Create a new animation state machine.""" factory = unreal.AnimationStateMachineFactory() factory.set_editor_property('TargetSkeleton', skeleton) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() return asset_tools.create_asset(state_machine_name, package_path, unreal.AnimationStateMachine, factory) def add_state_to_state_machine(state_machine, state_name, animation): """Add a state to an animation state machine.""" if isinstance(state_machine, unreal.AnimationStateMachine): return state_machine.add_state(state_name, animation) return None def add_transition_to_state_machine(state_machine, from_state, to_state, transition_name): """Add a transition between states in a state machine.""" if isinstance(state_machine, unreal.AnimationStateMachine): return state_machine.add_transition(from_state, to_state, transition_name) return None def set_animation_sequence_length(sequence, length): """Set the length of an animation sequence.""" if isinstance(sequence, unreal.AnimationSequence): sequence.set_editor_property('SequenceLength', length) def set_animation_sequence_rate(sequence, rate): """Set the frame rate of an animation sequence.""" if isinstance(sequence, unreal.AnimationSequence): sequence.set_editor_property('FrameRate', rate)
# /project/ # @CBgameDev Optimisation Script - Log Sound Cues Missing a Sound Class # /project/ import unreal import os EditAssetLib = unreal.EditorAssetLibrary() SystemsLib = unreal.SystemLibrary StringLib = unreal.StringLibrary() workingPath = "/Game/" # Using the root directory notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt" allAssets = EditAssetLib.list_assets(workingPath, True, False) selectedAssetsPath = workingPath LogStringsArray = [] numOfOptimisations = 0 with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST: ST.make_dialog(True) for asset in allAssets: _assetData = EditAssetLib.find_asset_data(asset) _assetName = _assetData.get_asset().get_name() _assetPathName = _assetData.get_asset().get_path_name() _assetClassName = _assetData.get_asset().get_class().get_name() # unreal.log(_assetClassName) if _assetClassName == "SoundCue": _SCSoundClass = unreal.SoundCue.cast(_assetData.get_asset()).get_editor_property("sound_class_object") if not SystemsLib.is_valid(_SCSoundClass): # no Sound class asset plugged in LogStringsArray.append(" [No Asset Plugged in] %s ------------> At Path: %s \n" % (_assetName, _assetPathName)) # unreal.log("Asset Name: %s [No Asset Plugged In] Path: %s \n" % (_assetName, _assetPathName)) numOfOptimisations += 1 elif StringLib.contains(_SCSoundClass.get_path_name(), "Engine"): # Sound Class Asset Plugged in but its Engine Default LogStringsArray.append(" [Engine Default Used] %s ------------> At Path: %s \n" % (_assetName, _assetPathName)) # unreal.log("Asset Name: %s [Engine Default Being Used] Path: %s \n" % (_assetName, _assetPathName)) numOfOptimisations += 1 if ST.should_cancel(): break ST.enter_progress_frame(1, asset) # Write results into a log file # /project/ TitleOfOptimisation = "Log Sound Cues With Missing Sound Class" DescOfOptimisation = "Searches the entire project for Sound Cues that are missing Sound Class Asset or are using the Engines Default Sound class asset" SummaryMessageIntro = "-- Sound Cues With Missing Sound Class --" if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists os.remove(notepadFilePath) # if does remove it # Create new txt file and run intro text file = open(notepadFilePath, "a+") # we should only do this if have a count? file.write("OPTIMISING SCRIPT by @CBgameDev \n") file.write("==================================================================================================== \n") file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation) file.write(" DESCRIPTION: %s \n" % DescOfOptimisation) file.write("==================================================================================================== \n \n") if numOfOptimisations <= 0: file.write(" -- NONE FOUND -- \n \n") else: for i in range(len(LogStringsArray)): file.write(LogStringsArray[i]) # Run summary text file.write("\n") file.write("======================================================================================================= \n") file.write(" SUMMARY: \n") file.write(" %s \n" % SummaryMessageIntro) file.write(" Found: %s \n \n" % numOfOptimisations) file.write("======================================================================================================= \n") file.write(" Logged to %s \n" % notepadFilePath) file.write("======================================================================================================= \n") file.close() os.startfile(notepadFilePath) # Trigger the notepad file to open
# Copyright Epic Games, Inc. All Rights Reserved # Built-in import sys from pathlib import Path # Third-party import unreal import remote_executor import mrq_cli plugin_name = "MoviePipelineDeadline" # Add the actions path to sys path actions_path = Path(__file__).parent.joinpath("pipeline_actions").as_posix().lower() if actions_path not in sys.path: sys.path.append(actions_path) from pipeline_actions import render_queue_action # Register the menu from the render queue actions render_queue_action.register_menu_action() # The asset registry may not be fully loaded by the time this is called, # warn the user that attempts to look assets up may fail # unexpectedly. # Look for a custom commandline start key `-waitonassetregistry`. This key # is used to trigger a synchronous wait on the asset registry to complete. # This is useful in commandline states where you explicitly want all assets # loaded before continuing. asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() if asset_registry.is_loading_assets() and ("-waitonassetregistry" in unreal.SystemLibrary.get_command_line().split()): unreal.log_warning( f"Asset Registry is still loading. The {plugin_name} plugin will " f"be loaded after the Asset Registry is complete." ) asset_registry.wait_for_completion() unreal.log(f"Asset Registry is complete. Loading {plugin_name} plugin.")
import unreal class ActorActionEditor(object): editor_util = unreal.EditorUtiltyLibrary() LayerSubsystem = unreal.LayerSubsystem() editorFilterLib = unreal.editorFilterLibrary() materials = [] selected_assets = [] def __init__(self): if materials is not None: materials.empty() materials = editor_filter_lib.by_class(selected_assets, unreal.Material) selected_assets = editor_util.get_selected_assets() if editor_util is None: editor_util = unreal.EditorUtiltyLibrary() if editorFilterLib is None: editorFilterLib = unreal.editorFilterLibrary() main() def main(self): if len(materials) < 1: print("") # use the unreal log for this. if len(materials) == 1: material = materials[0] material_name = material.get_fname() for x in materials:
# -*- coding: utf-8 -*- import unreal import os from Utilities.Utils import Singleton from Utilities.Utils import cast import Utilities import QueryTools import re import types import collections from .import Utils global _r COLUMN_COUNT = 2 class DetailData(object): def __init__(self): self.filter_str = "" self.filteredIndexToIndex = [] self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)] self.attributes = None self.filtered_attributes = None self.plains = [] self.riches = [] self.selected = set() def check_line_id(self, line_id, column_count): from_line = line_id * column_count to_line = (line_id + 1) * column_count assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)" if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains): return True else: unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}") return False def get_plain(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.plains[line_id * 2 : line_id * 2 + 2] def get_rich(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.riches[line_id * 2: line_id * 2 + 2] class ObjectDetailViewer(metaclass=Singleton): def __init__(self, jsonPath): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_checkbox_single_mode = "CheckBoxSingleMode" self.ui_checkbox_compare_mode = "CheckBoxCompareMode" self.ui_left_group = "LeftDetailGroup" self.ui_right_group = "RightDetailGroup" self.ui_button_refresh = "RefreshCompareButton" self.ui_detailListLeft = "ListViewLeft" self.ui_detailListRight = "ListViewRight" self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft' self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight' # self.ui_headRowLeft = "HeaderRowLeft" # self.ui_headRowRight = "HeaderRowRight" self.ui_labelLeft = "LabelLeft" self.ui_labelRight = "LabelRight" self.ui_info_output = "InfoOutput" self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode self.ui_rightListGroup = "RightListGroup" self.ui_refreshButtonGroup = "RefreshButtonGroup" self.reset() def on_close(self): self.reset() def on_map_changed(self, map_change_type_str): # remove the reference, avoid memory leaking when load another map. if map_change_type_str == "TearDownWorld": self.reset(bResetParameter=False) else: pass # skip: LoadMap, SaveMap, NewMap def reset(self, bResetParameter=True): if bResetParameter: self.showBuiltin = True self.showOther = True self.showProperties = True self.showEditorProperties = True self.showParamFunction = True self.compareMode = False self.left = None self.right = None self.leftSearchText = "" self.rightSearchText = "" self.left_rich = None self.left_plain = None self.var = None self.diff_count = 0 self.clear_ui_info() def clear_ui_info(self): for text_ui in [self.ui_info_output, self.ui_labelLeft, self.ui_labelRight]: self.data.set_text(text_ui, "") self.data.set_list_view_multi_column_items(self.ui_detailListLeft, [], 2) self.data.set_list_view_multi_column_items(self.ui_detailListRight, [], 2) for ui_breadcrumb in [self.ui_hisObjsBreadcrumbRight, self.ui_hisObjsBreadcrumbLeft]: crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) for i in range(crumbCount): self.data.pop_breadcrumb_string(ui_breadcrumb) def update_log_text(self, bRight): bShowRight = self.compareMode result = "" for side_str in ["left", "right"] if bShowRight else ["left"]: bRight = side_str != "left" ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: result += "\t\t\t" result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs)) if self.compareMode: result = f"{result}\t\t\tdiff count: {self.diff_count}" self.data.set_text(self.ui_info_output, result) def get_color_by(self, attr : Utils.attr_detail): if attr.bCallable_builtin: return "DarkTurquoise".lower() if attr.bCallable_other: return "RoyalBlue".lower() if attr.bEditorProperty: return "LimeGreen".lower() if attr.bOtherProperty: return "yellow" def get_color(self, typeStr): if typeStr == "property": return 'white' if typeStr == "return_type": return 'gray' if typeStr == "param": return 'gray' def get_name_with_rich_text(self, attr:Utils.attr_detail): name_color = self.get_color_by(attr) param_color = self.get_color("param") return_type_color = self.get_color("return_type") if attr.bProperty: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: if attr.param_str: return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name , param_color, attr.param_str , name_color) else: if attr.bCallable_other: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name , return_type_color, attr.return_type_str) def get_name_with_plain_text(self, attr:Utils.attr_detail): if attr.bProperty: return "\t{}".format(attr.name) else: if attr.param_str: return "\t{}({})".format( attr.name, attr.param_str) else: if attr.bCallable_other: return "\t{}".format( attr.name) else: return "\t{}() {}".format(attr.name,attr.return_type_str) def filter(self, data:DetailData): result = [] indices = [] for i, attr in enumerate(data.attributes): if not self.showEditorProperties and attr.bEditorProperty: continue if not self.showProperties and attr.bOtherProperty: continue if not self.showParamFunction and attr.bHasParamFunction: continue if not self.showBuiltin and attr.bCallable_builtin: continue if not self.showOther and attr.bCallable_other: continue if data.filter_str: if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() : continue result.append(attr) indices.append(i) return result, indices def show_data(self, data:DetailData, ui_listView): flatten_list_items = [] flatten_list_items_plain = [] for i, attr in enumerate(data.filtered_attributes): # print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ") attr.check() assert attr.display_name, f"display name null {attr.display_name}" assert isinstance(attr.display_result, str), f"display result null {attr.display_result}" result_str = attr.display_result if len(result_str) > 200: result_str = result_str[:200] + "......" flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str]) flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str]) data.riches = flatten_list_items data.plains = flatten_list_items_plain data.selected.clear() self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2) def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property if bRight: ui_Label = self.ui_labelRight ui_listView = self.ui_detailListRight ui_breadcrumb = self.ui_hisObjsBreadcrumbRight else: ui_Label = self.ui_labelLeft ui_listView = self.ui_detailListLeft ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left data.attributes = Utils.ll(obj) data.filtered_attributes, data.filteredIndexToIndex = self.filter(data) self.show_data(data, ui_listView) # set breadcrumb if propertyName and len(propertyName) > 0: label = propertyName else: if isinstance(obj, unreal.Object): label = obj.get_name() else: try: label = obj.__str__() except TypeError: label = f"{obj}" if bPush: # push # print(f"%%% push: {propertyName}, label {label}") data.hisCrumbObjsAndNames.append((obj, propertyName)) self.data.push_breadcrumb_string(ui_breadcrumb, label, label) self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) ) crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount) else: assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount) self.update_log_text(bRight) def clear_and_query(self, obj, bRight): # first time query self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft) if not self.right: self.right = DetailData() if not self.left: self.left = DetailData() data = self.right if bRight else self.left data.hisCrumbObjsAndNames = [] #clear his-Object at first time query if bRight: assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0" else: assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0" self.query_and_push(obj, "", bPush=True, bRight= bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def update_ui_by_mode(self): self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode) self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode) bCollapsed = not self.compareMode self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed) self.data.set_collapsed(self.ui_right_group, bCollapsed) self.data.set_collapsed(self.ui_button_refresh, bCollapsed) def on_checkbox_SingleMode_Click(self, state): self.compareMode = False self.update_ui_by_mode() def on_checkbox_CompareMode_Click(self, state): self.compareMode = True self.update_ui_by_mode() def on_button_Refresh_click(self): self.apply_compare_if_needed() def on_button_SelectAsset_click(self, bRightSide): selectedAssets = Utilities.Utils.get_selected_assets() if len(selectedAssets) == 0: return self.clear_and_query(selectedAssets[0], bRightSide) def on_button_QuerySelected_click(self, bRightSide): # query component when any component was selected, otherwise actor obj = Utilities.Utils.get_selected_comp() if not obj: obj = Utilities.Utils.get_selected_actor() if obj: self.clear_and_query(obj, bRightSide) def on_drop(self, bRightSide, *args, **kwargs): if "assets" in kwargs and kwargs["assets"]: asset = unreal.load_asset(kwargs["assets"][0]) if asset: self.clear_and_query(asset, bRightSide) return if "actors" in kwargs and kwargs["actors"]: actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world()) if actor: print(actor) self.clear_and_query(actor, bRightSide) return item_count = 0 for k, v in kwargs.items(): item_count += len(v) if item_count == 0: selected_comp = Utilities.Utils.get_selected_comp() if selected_comp: self.clear_and_query(selected_comp, bRightSide) def log_r_warning(self): unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu") def on_button_Query_R_click(self, r_obj, bRightSide=False): print("on_button_Query_R_click call") if not r_obj: return self.clear_and_query(r_obj, bRightSide) def on_list_double_click_do(self, index, bRight): # print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight)) data = self.right if bRight else self.left typeBlacklist = [int, float, str, bool] #, types.NotImplementedType] real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index assert 0 <= real_index < len(data.attributes) currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] attr_name = data.attributes[real_index].name objResult, propertyName = self.try_get_object(data, currentObj, attr_name) if not objResult or objResult is currentObj: # equal return if isinstance(objResult, str) and "skip call" in objResult.lower(): return if type(objResult) in typeBlacklist: return if isinstance(objResult, collections.abc.Iterable): if type(objResult[0]) in typeBlacklist: return nextObj = objResult[0] nextPropertyName = str(propertyName) + "[0]" else: nextObj = objResult nextPropertyName = str(propertyName) self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def on_listview_DetailListRight_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=True) def on_listview_DetailListLeft_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=False) def on_breadcrumbtrail_click_do(self, item, bRight): ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb) print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames))) while len(data.hisCrumbObjsAndNames) > count: data.hisCrumbObjsAndNames.pop() nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] if not bRight: assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames" self.query_and_push(nextObj, name, bPush=False, bRight=False) self.apply_compare_if_needed() self.update_log_text(bRight=False) def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=False) def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=True) def remove_address_str(self, strIn): return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn) def apply_compare_if_needed(self): if not self.compareMode: return lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes if not lefts: lefts = [] if not rights: rights = [] leftIDs = [] rightIDs = [] for i, left_attr in enumerate(lefts): for j, right_attr in enumerate(rights): if right_attr.name == left_attr.name: if right_attr.result != left_attr.result: if isinstance(right_attr.result, unreal.Transform): if right_attr.result.is_near_equal(left_attr.result, location_tolerance=1e-20, rotation_tolerance=1e-20, scale3d_tolerance=1e-20): continue leftIDs.append(i) rightIDs.append(j) break self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs) self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs) self.diff_count = len(leftIDs) def apply_search_filter(self, text, bRight): _data = self.right if bRight else self.left _data.filter_str = text if len(text) else "" _data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data) ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft self.show_data(_data, ui_listView) self.apply_compare_if_needed() def on_searchbox_FilterLeft_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterLeft_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterRight_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def on_searchbox_FilterRight_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def apply_filter(self): _datas = [self.left, self.right] _isRight = [False, True] for data, bRight in zip(_datas, _isRight): if len(data.hisCrumbObjsAndNames) > 0: nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1] self.query_and_push(nextObj, name, bPush=False, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight=False) # def try_get_object(self, data, obj, name:str): index = -1 attribute = None for i, attr in enumerate(data.attributes): if attr.name == name: index = i attribute = attr assert index >= 0 return attribute.result, name def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled): self.showBuiltin = bEnabled self.apply_filter() def ui_on_checkbox_ShowOther_state_changed(self, bEnabled): self.showOther = bEnabled self.apply_filter() def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled): self.showProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled): self.showEditorProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled): self.showParamFunction = bEnabled self.apply_filter() def ui_on_listview_DetailList_selection_changed(self, bRight): data = [self.left, self.right][bRight] list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight] selected_indices = set(self.data.get_list_view_multi_column_selection(list_view)) added = selected_indices - data.selected de_selected = data.selected - selected_indices for i, lineId in enumerate(added): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False) for i, lineId in enumerate(de_selected): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(de_selected)-1 else False) data.selected = selected_indices
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-debugeachsave") args = parser.parse_args() #print(args.vrm) ###### rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r h_mod = rig.get_hierarchy_modifier() elements = h_mod.get_selection() print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller() else: c = rig.controller g = c.get_graph() n = g.get_nodes() mesh = rig.get_preview_mesh() morphList = mesh.get_all_morph_target_names() morphListWithNo = morphList[:] morphListRenamed = [] morphListRenamed.clear() for i in range(len(morphList)): morphListWithNo[i] = '{}'.format(morphList[i]) print(morphListWithNo) ###### root key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'MorphControlRoot_s') space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE) else: space = key a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() print(a) # 配列ノード追加 values_forCurve:unreal.RigVMStructNode = [] items_forControl:unreal.RigVMStructNode = [] items_forCurve:unreal.RigVMStructNode = [] for node in n: print(node) print(node.get_node_title()) # set curve num if (node.get_node_title() == 'For Loop'): print(node) pin = node.find_pin('Count') print(pin) c.set_pin_default_value(pin.get_pin_path(), str(len(morphList))) # curve name array pin if (node.get_node_title() == 'Select'): print(node) pin = node.find_pin('Values') #print(pin) #print(pin.get_array_size()) #print(pin.get_default_value()) values_forCurve.append(pin) # items if (node.get_node_title() == 'Items'): if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())): items_forCurve.append(node.find_pin('Items')) else: items_forControl.append(node.find_pin('Items')) print(values_forCurve) # reset controller for e in reversed(h_mod.get_elements()): if (e.type!= unreal.RigElementType.CONTROL): continue tmp = h_mod.get_control(e) if (tmp.space_name == 'MorphControlRoot_s'): #if (str(e.name).rstrip('_c') in morphList): # continue print('delete') #print(str(e.name)) h_mod.remove_element(e) # curve array for v in values_forCurve: c.clear_array_pin(v.get_pin_path()) for morph in morphList: tmp = "{}".format(morph) c.add_array_pin(v.get_pin_path(), default_value=tmp) # curve controller for morph in morphListWithNo: name_c = "{}_c".format(morph) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) try: control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): k = h_mod.add_control(name_c, control_type=unreal.RigControlType.FLOAT, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) control = h_mod.get_control(k) except: k = h_mod.add_control(name_c, control_type=unreal.RigControlType.FLOAT, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) control = h_mod.get_control(k) control.set_editor_property('gizmo_visible', False) control.set_editor_property('gizmo_enabled', False) h_mod.set_control(control) morphListRenamed.append(control.get_editor_property('name')) if (args.debugeachsave == '1'): try: unreal.EditorAssetLibrary.save_loaded_asset(rig) except: print('save error') #unreal.SystemLibrary.collect_garbage() # curve Control array for v in items_forControl: c.clear_array_pin(v.get_pin_path()) for morph in morphListRenamed: tmp = '(Type=Control,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp) # curve Float array for v in items_forCurve: c.clear_array_pin(v.get_pin_path()) for morph in morphList: tmp = '(Type=Curve,Name=' tmp += "{}".format(morph) tmp += ')' c.add_array_pin(v.get_pin_path(), default_value=tmp)
import unreal class OrganicGridToolUtilities: ORGANIC_GRID_TOOL_MESH_ACTOR_PATH = "D:/project/.uasset" @classmethod @classmethod def spawn_organic_grid_tooL_mesh_actor(cls): actor = unreal.EditorLevelLibrary.spawn_actor_from_class()
import unreal from CommonFunctions import * # from importlib import reload # reload Blueprint BASE_COLLISION: unreal.Name = unreal.Name("CamToHiddenMesh") # "CamToHiddenMesh"可以实现相机穿透功能,使用Actor Tag"Camera_NoHide" 屏蔽 DECAL_COLLISION: unreal.Name = unreal.Name("NoCollision") sys_lib = unreal.SystemLibrary string_lib = unreal.StringLibrary bp_editor_lib = unreal.BlueprintEditorLibrary staticmesh_subsys = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) subobj_subsys = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() sk_component_class = unreal.SkeletalMeshComponent.static_class() sm_component_class = unreal.StaticMeshComponent.static_class() def get_blueprint_assets(assets): """ 筛选蓝图资产 """ blueprints = [] for asset in assets: assetClass = asset.get_class() assetClass = sys_lib.get_class_display_name(asset.get_class()) if assetClass == "Blueprint": blueprints.append(asset) return blueprints def get_blueprint_components(blueprint): """ 获取蓝图子物件列表 """ components = [] root_data_handle = subobj_subsys.k2_gather_subobject_data_for_blueprint(blueprint) for handle in root_data_handle: subObject = subobj_subsys.k2_find_subobject_data_from_handle(handle) component = unreal.SubobjectDataBlueprintFunctionLibrary.get_object(subObject) if component not in components: components.append(component) return components def checkMaterials(materials): """ 检查模型的材质属性,如果有透明材质返回0,不透明和masked材质返回1 """ validBlendModes = ["OPAQUE", "MASKED"] blendModes = [] count = 0 # iterate over materials and collect blend mode info for material in materials: if isinstance(material, unreal.Material): blendModes.append(material.get_editor_property("blend_mode")) if isinstance(material, unreal.MaterialInstanceConstant): parentMaterial = material.get_base_material() blendModes.append(parentMaterial.get_editor_property("blend_mode")) # check to see if valid blend mode in material blend mode for vbm in validBlendModes: for bm in blendModes: if vbm in str(bm): count += 1 if count == len(materials): return 1 return 0 def setBaseMesh(staticMesh): """ 设置Base Mesh""" meshNaniteSettings = staticMesh.get_editor_property("nanite_settings") # 开启nanite,配置参数避免法线错误 meshNaniteSettings.enabled = True meshNaniteSettings.fallback_relative_error = 0 staticmesh_subsys.set_nanite_settings( staticMesh, meshNaniteSettings, apply_changes=True ) def setDecalMesh(staticMesh): """ 设置Decal Mesh""" # 关闭nanite print("set decal mesh") meshNaniteSettings = staticMesh.get_editor_property("nanite_settings") meshNaniteSettings.enabled = False # meshNaniteSettings.fallback_relative_error = 0 staticmesh_subsys.set_nanite_settings( staticMesh, meshNaniteSettings, apply_changes=True ) # 删除碰撞 default_object = unreal.StaticMeshEditorSubsystem.get_default_object() default_object.remove_collisions(staticMesh) def set_skeletalmesh_components(components): """ 设置SkeletalMeshComponent""" # print("use skm settings") sk_components = [] sm_components = [] for component in components: if component.get_class() == sk_component_class: sk_components.append(component) for component in components: if component.get_class() == sm_component_class: sm_components.append(component) for sk_comp in sk_components: # unreal.SkeletalMeshComponent.set_visibility(sk_comp, False) sk_comp.set_editor_property(name="cast_shadow", value=False) sk_mesh = sk_comp.get_skeletal_mesh_asset() sk_name = sk_mesh.get_name() sk_name = sk_name.split("_")[1] for sm_comp in sm_components: staticMesh = sm_comp.get_editor_property("static_mesh") assetName = staticMesh.get_name() if sk_name in assetName: # if "Class 'SkeletalMeshComponent'" in str(component): # 检查是否smcomponent # staticMesh = component.get_editor_property( # "static_mesh" # ) # 从smcomponent中获取对应的static mesh # assetName = staticMesh.get_name() # if str(staticMesh) == "None": # unreal.log_warning( # "StaticMeshComponent: {} has no StaticMesh | 没有StaticMesh,跳过".format( # str(component) # ) # ) if string_lib.contains(str(assetName), "_Decal") is True: # decal处理,关闭投影和碰撞 component.set_editor_property(name="cast_shadow", value=False) component.set_collision_profile_name( collision_profile_name=DECAL_COLLISION ) setDecalMesh(staticMesh) unreal.log( "{} is decal mesh, turn off nanite and collision | 贴花模型处理".format( assetName ) ) else: materials = unreal.StaticMeshComponent.get_materials(component) component.set_collision_profile_name( collision_profile_name=BASE_COLLISION ) component.set_editor_property( name="mobility", value=unreal.ComponentMobility.STATIC ) if checkMaterials(materials) == 1: setBaseMesh(staticMesh) unreal.log( "{} is base mesh, turn on nanite | base模型处理".format( assetName ) ) def set_staticmesh_components(components): """ 设置StaticMeshComponent""" for component in components: if component.get_class() == sm_component_class: # 检查是否smcomponent # component.set_component_tick_enabled(False) # tick_disable=unreal.ActorComponentTickFunction.set_editor_property(name="start_with_tick_enabled", value=False, notify_mode=unreal.PropertyAccessChangeNotifyMode.NEVER) # component.set_editor_property(name="primary_component_tick", value=tick_disable) staticMesh = component.get_editor_property("static_mesh") # 从smcomponent中获取对应的static mesh if str(staticMesh) == "None": unreal.log_warning( "StaticMeshComponent: {} has no StaticMesh | 没有StaticMesh,跳过".format( str(component) ) ) elif string_lib.contains(str(staticMesh), "_Decal") is True: # decal处理,关闭投影和碰撞 assetName = staticMesh.get_name() component.set_editor_property(name="cast_shadow", value=False) component.set_collision_profile_name( collision_profile_name=DECAL_COLLISION ) component.set_editor_property( name="mobility", value=unreal.ComponentMobility.STATIC ) component.set_editor_property( name="world_position_offset_disable_distance", value=int(400) ) setDecalMesh(staticMesh) unreal.log( "{} is decal mesh, turn off nanite and collision | 贴花模型处理".format( assetName ) ) else: # set base mesh component assetName = staticMesh.get_name() materials = unreal.StaticMeshComponent.get_materials(component) component.set_collision_profile_name( collision_profile_name=BASE_COLLISION ) component.set_editor_property( name="mobility", value=unreal.ComponentMobility.STATIC ) if checkMaterials(materials) == 1: setBaseMesh(staticMesh) unreal.log( "{} is base mesh, turn on nanite | base模型处理".format(assetName) ) def set_components_static(components): """设置所有Component为Static""" class_bp="BlueprintGeneratedClass" for component in components: if class_bp not in str(component.get_class()): component.set_editor_property( name="mobility", value=unreal.ComponentMobility.STATIC ) def set_childs(components): """设置蓝图中的Components""" has_skm = False for component in components: if component.get_class() == sk_component_class: has_skm = True break if has_skm: set_skeletalmesh_components(components) else: set_components_static(components) set_staticmesh_components(components) def attach_skm_components(blueprint): sk_handles = [] sm_handles = [] handles = Blueprint.get_handels(blueprint) for handle in handles: if Blueprint.get_handle_component(handle).get_class() == sk_component_class: sk_handles.append(handle) elif Blueprint.get_handle_component(handle).get_class() == sm_component_class: sm_handles.append(handle) if len(sk_handles) > 0: print("attach sk handles") for sk_handle in sk_handles: sk_component = Blueprint.get_handle_component(sk_handle) sk_mesh = unreal.SkeletalMeshComponent.get_skeletal_mesh_asset(sk_component) sk_name = str(sk_mesh.get_name()) sk_name = sk_name.split("_")[1] for sm_handle in sm_handles: sm_name = Blueprint.get_handle_component(sm_handle).get_name() if sk_name in sm_name: subobj_subsys.attach_subobject(sk_handle, sm_handle) def fix_prefab_with_parent(blueprint)->bool: """fix prefab with parent""" has_parent_prefab_bp = True bp_actor = Blueprint.get_default_object(blueprint) try: base_sm=bp_editor_lib.get_editor_property(bp_actor,name="Base") decal_sm=bp_editor_lib.get_editor_property(bp_actor,name="Decal") setBaseMesh(base_sm) setDecalMesh(decal_sm) except: base_sm=None decal_sm=None has_parent_prefab_bp = False return has_parent_prefab_bp def fix_prefab_assets(assets): """修复Prefab资产,自动配置对应的Mesh属性""" blueprints = get_blueprint_assets(assets) assetCount = len(blueprints) taskName = "Batch Processing BP Assets: " currentStep = 0 # Slow Task 进度条 with unreal.ScopedSlowTask(assetCount, taskName) as slowTask: slowTask.make_dialog(True) for blueprint in blueprints: # 进度条目前进度 currentStep += 1 if slowTask.should_cancel(): break slowTask.enter_progress_frame( 1, taskName + str(currentStep) + "/" + str(assetCount) ) attach_skm_components(blueprint) has_parent=fix_prefab_with_parent(blueprint) if has_parent is False: components = get_blueprint_components(blueprint) set_childs(components) if assetCount == 0: unreal.log_error("selection no Blueprint, aborted. | 所选模型没有Blueprint") else: unreal.log( "{} BPs with its child assets done | 蓝图及对应资产属性设置完成".format( assetCount ) ) def get_component_from_variable(variable_name: str, blueprint_cdo)->unreal.StaticMeshComponent: static_mesh = bp_editor_lib.get_editor_property(blueprint_cdo, name=variable_name) static_mesh_component = None if isinstance (static_mesh, unreal.StaticMesh): static_mesh_component = unreal.StaticMeshComponent() static_mesh_component.set_static_mesh(static_mesh) return static_mesh_component def reparent_blueprints(blueprints,parent_asset_path)->None: """ reparent blueprints """ parent_class = Blueprint.get_blueprint_class(parent_asset_path) parent_class_name = sys_lib.get_display_name(parent_class) for blueprint in blueprints: components = get_blueprint_components(blueprint) has_target_parent = False for component in components: if parent_class_name in str(component): has_target_parent = True break if has_target_parent == False: bp_editor_lib.reparent_blueprint(blueprint, parent_class) def set_bp_variables_staticmesh(static_meshes,blueprint)->None: """ set bp variables staticmesh """ bp_actor = Blueprint.get_default_object(blueprint) decal_mesh=None base_mesh=None for static_mesh in static_meshes: if "_Decal" in static_mesh.get_name(): decal_mesh=static_mesh else: base_mesh=static_mesh if base_mesh: bp_editor_lib.set_editor_property(bp_actor,name="Base",value=base_mesh) if decal_mesh: bp_editor_lib.set_editor_property(bp_actor,name="Decal",value=decal_mesh) def get_parent_basemat(parent_asset_path): parent_bp=unreal.load_asset(parent_asset_path) parent_components=get_blueprint_components(parent_bp) parent_base_mat=None for component in parent_components: if "BaseMesh" in component.get_name(): component_basemesh=component.get_editor_property("static_mesh") if component_basemesh: parent_base_mat=get_materials(component_basemesh)[0] parent_base_mat=parent_base_mat.get_base_material() break return parent_base_mat def get_bp_variables_staticmesh(blueprint,parent_asset_path,parent_base_mat)->list: """ get bp variables staticmesh """ bp_actor = Blueprint.get_default_object(blueprint) components = get_blueprint_components(blueprint) parent_class = Blueprint.get_blueprint_class(parent_asset_path) parent_class_name = sys_lib.get_display_name(parent_class) filtered_meshes=[] sm_components=[] for component in components: component_class = component.get_class() if (parent_class_name not in str(component) and component_class == sm_component_class): sm_components.append(component) for component in sm_components: static_mesh=component.get_editor_property("static_mesh") if static_mesh is not None: if "_Decal" not in static_mesh.get_name(): if parent_base_mat is not None: mats=get_materials(static_mesh) for material in mats: master_mat=material.get_base_material() if master_mat==parent_base_mat: filtered_meshes.append(static_mesh) component.set_static_mesh(None) component.set_visibility(False) break else: filtered_meshes.append(static_mesh) component.set_static_mesh(None) component.set_visibility(False) break for component in sm_components: static_mesh=component.get_editor_property("static_mesh") if static_mesh is not None: if "_Decal" in static_mesh.get_name(): filtered_meshes.append(static_mesh) component.set_static_mesh(None) component.set_visibility(False) break if len(filtered_meshes)>0: return filtered_meshes else: return None def filter_target_components(blueprint,parent_class)->list: bp_actor = Blueprint.get_default_object(blueprint) parent_class_name = sys_lib.get_display_name(parent_class) components = get_blueprint_components(blueprint) target_components = [] for component in components: component_class = component.get_class() component_class = sys_lib.get_display_name(component_class) if ( parent_class_name not in str(component) and component_class == "StaticMeshComponent" ): target_components.append(component) try: base_component=get_component_from_variable(variable_name="Base",blueprint_cdo=bp_actor) except: base_component=None if base_component is not None: target_components.append(base_component) try: decal_component=get_component_from_variable(variable_name="Decal",blueprint_cdo=bp_actor) except: decal_component=None if decal_component is not None: target_components.append(decal_component) return target_components def reparent_blueprint_assets(assets, parent_asset_path): "替换bp的parent class,并配置子模型参数" parent_asset_path=unreal.Paths.normalize_filename(parent_asset_path) parent_class = Blueprint.get_blueprint_class(parent_asset_path) parent_class_name = sys_lib.get_display_name(parent_class) parent_basemat=get_parent_basemat(parent_asset_path) print(f"ParentClass:{parent_class_name}") blueprints = get_blueprint_assets(assets) assetCount = len(blueprints) taskName = "Batch Processing BP Assets: " currentStep = 0 # Slow Task 进度条 with unreal.ScopedSlowTask(assetCount, taskName) as slowTask: slowTask.make_dialog(True) for blueprint in blueprints: # 进度条目前进度 currentStep += 1 if slowTask.should_cancel(): break slowTask.enter_progress_frame( 1, taskName + str(currentStep) + "/" + str(assetCount) ) is_mesh_prefab_bp = False if "_SM" in blueprint.get_name(): is_mesh_prefab_bp = True if is_mesh_prefab_bp is True: components = get_blueprint_components(blueprint) # 检查是否已有parent has_target_parent = False for component in components: if parent_class_name in str(component): has_target_parent = True break if has_target_parent is False: filtered_meshes=get_bp_variables_staticmesh(blueprint,parent_asset_path,parent_basemat) has_base_mesh=False if filtered_meshes is not None: for mesh in filtered_meshes: if "_Decal" not in mesh.get_name(): has_base_mesh=True break if has_base_mesh is True: bp_editor_lib.reparent_blueprint(blueprint, parent_class) bp_editor_lib.compile_blueprint(blueprint) set_bp_variables_staticmesh(filtered_meshes,blueprint) else: print(f"{blueprint.get_name()} cannot be auto processed, skipped") else: print(f"{blueprint.get_name()} does not have '_SM' suffix, is not a mesh prefab, ") target_components=filter_target_components(blueprint,parent_class) if target_components is not None: set_childs(target_components) if assetCount == 0: unreal.log_error("selection no Blueprint, aborted. | 所选模型没有Blueprint") else: unreal.log( "{} BPs with its child assets done | 蓝图及对应资产属性设置完成".format( assetCount ) ) def batch_recompile_bps(assets): "批量重新编译蓝图" blueprints = get_blueprint_assets(assets) for bp in blueprints: bp_editor_lib.compile_blueprint(bp)
# coding: utf-8 import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## meta 取得 a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] for e in reversed(h_mod.get_elements()): if (e.type != unreal.RigElementType.BONE): h_mod.remove_element(e) name_to_control = {"dummy_for_table" : None} gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2]) for e in h_mod.get_elements(): print(e.name) if (e.type != unreal.RigElementType.BONE): continue bone = h_mod.get_bone(e) parentName = "{}".format(bone.get_editor_property('parent_name')) #print("parent==") #print(parentName) cur_parentName = parentName + "_c" name_s = "{}".format(e.name) + "_s" name_c = "{}".format(e.name) + "_c" space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL) control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[0.1, 0.1, 1.0, 1.0], ) h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e)) cc = h_mod.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) #cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_mod.set_control(cc) name_to_control[name_c] = cc c = None try: i = list(name_to_control.keys()).index(cur_parentName) except: i = -1 if (i >= 0): c = name_to_control[cur_parentName] if (cc != None): if ("{}".format(e.name) in meta.humanoid_bone_table.values() ): cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0)) h_mod.set_control(cc) else: cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0)) h_mod.set_control(cc) c = rig.controller g = c.get_graph() n = g.get_nodes() # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) if (collectionItem_forBone != None): items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) for bone_h in meta.humanoid_bone_table: bone_m = meta.humanoid_bone_table[bone_h] try: i = humanoidBoneList.index(bone_h.lower()) except: i = -1 if (i >= 0): tmp = '(Type=Bone,Name=' tmp += "{}".format(bone_m).lower() tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) for e in h_mod.get_elements(): print(e.name) if (e.type == unreal.RigElementType.CONTROL): tmp = '(Type=Control,Name=' tmp += "{}".format(e.name) tmp += ')' c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ An example script that uses the API to instantiate an HDA and then set 2 inputs: a geometry input (a cube) and a curve input (a helix). The inputs are set during post instantiation (before the first cook). After the first cook and output creation (post processing) the input structure is fetched and logged. """ import math import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.copy_to_curve_1_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_geo_asset_path(): return '/project/.Cube' def get_geo_asset(): return unreal.load_object(None, get_geo_asset_path()) def configure_inputs(in_wrapper): print('configure_inputs') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs) # Create a geo input geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput) # Set the input objects/assets for this input geo_object = get_geo_asset() if not geo_input.set_input_objects((geo_object, )): # If any errors occurred, get the last error message print('Error on geo_input: {0}'.format(geo_input.get_last_error_message())) # copy the input data to the HDA as node input 0 in_wrapper.set_input_at_index(0, geo_input) # We can now discard the API input object geo_input = None # Create a curve input curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput) # Create a curve wrapper/helper curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input) # Make it a Nurbs curve curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS) # Set the points of the curve, for this example we create a helix # consisting of 100 points curve_points = [] for i in range(100): t = i / 20.0 * math.pi * 2.0 x = 100.0 * math.cos(t) y = 100.0 * math.sin(t) z = i curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1])) curve_object.set_curve_points(curve_points) # Error handling/message example: try to set geo_object on curve input if not curve_input.set_input_objects((geo_object, )): print('Error (example) while setting \'{0}\' on curve input: {1}'.format( geo_object.get_name(), curve_input.get_last_error_message() )) # Set the curve wrapper as an input object curve_input.set_input_objects((curve_object, )) # Copy the input data to the HDA as node input 1 in_wrapper.set_input_at_index(1, curve_input) # We can now discard the API input object curve_input = None # Check for errors on the wrapper last_error = in_wrapper.get_last_error_message() if last_error: print('Error on wrapper during input configuration: {0}'.format(last_error)) def print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput): print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge)) print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds)) print('\t\tbExportSockets: {0}'.format(in_input.export_sockets)) print('\t\tbExportColliders: {0}'.format(in_input.export_colliders)) elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput): print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed)) print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves)) input_objects = in_input.get_input_objects() if not input_objects: print('\t\tEmpty input!') else: print('\t\tNumber of objects in input: {0}'.format(len(input_objects))) for idx, input_object in enumerate(input_objects): print('\t\t\tInput object #{0}: {1}'.format(idx, input_object)) if hasattr(in_input, 'get_object_transform_offset'): print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_object_transform_offset(input_object))) if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject): print('\t\t\tbClosed: {0}'.format(input_object.is_closed())) print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method())) print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type())) print('\t\t\tReversed: {0}'.format(input_object.is_reversed())) print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points())) def print_inputs(in_wrapper): print('print_inputs') # Unbind from the delegate in_wrapper.on_post_processing_delegate.remove_callable(print_inputs) # Fetch inputs, iterate over it and log node_inputs = in_wrapper.get_inputs_at_indices() parm_inputs = in_wrapper.get_input_parameters() if not node_inputs: print('No node inputs found!') else: print('Number of node inputs: {0}'.format(len(node_inputs))) for input_index, input_wrapper in node_inputs.items(): print('\tInput index: {0}'.format(input_index)) print_api_input(input_wrapper) if not parm_inputs: print('No parameter inputs found!') else: print('Number of parameter inputs: {0}'.format(len(parm_inputs))) for parm_name, input_wrapper in parm_inputs.items(): print('\tInput parameter name: {0}'.format(parm_name)) print_api_input(input_wrapper) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Configure inputs on_post_instantiation, after instantiation, but before first cook _g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs) # Print the input state after the cook and output creation. _g_wrapper.on_post_processing_delegate.add_callable(print_inputs) if __name__ == '__main__': run()
import unreal #This python script should be put into a folder that is accessible to UE and add it to the "startup scripts" in the project settings #https://docs.unrealengine.com/en-US/scripting-the-unreal-editor-using-python/ #this pipeline will change the compression settings on textures based on their name suffixes @unreal.uclass() class MyProjectPythonPipeline(unreal.InterchangePythonPipelineBase): configure_texture_from_name_suffix = unreal.uproperty(bool,meta=dict(Category="Textures")) def cast(self, object_to_cast, object_class): try: return object_class.cast(object_to_cast) except: return None def recursive_set_node_properties(self, base_node_container, node_unique_id): node = base_node_container.get_node(node_unique_id) texture_node = self.cast(node, unreal.InterchangeTexture2DFactoryNode) if texture_node: texture_name = texture_node.get_display_label() if texture_name.endswith("_D"): #unreal.TextureCompressionSettings.TC_BC7 is 11 texture_node.set_custom_compression_settings(11) elif texture_name.ends_with("_N"): #unreal.TextureCompressionSettings.TC_NORMALMAP is 1 texture_node.set_custom_compression_settings(1) else: #unreal.TextureCompressionSettings.TC_DEFAULT is 0 texture_node.set_custom_compression_settings(0) childrens = base_node_container.get_node_children_uids(node.get_unique_id()) for child_uid in childrens: self.recursive_set_node_properties(base_node_container, child_uid) @unreal.ufunction(override=True) def scripted_execute_pipeline(self, base_node_container, in_source_datas, content_base_path): if not self.configure_texture_from_name_suffix: return root_nodes = base_node_container.get_roots() for node_unique_id in root_nodes: self.recursive_set_node_properties(base_node_container, node_unique_id) return True
import unreal @unreal.uclass() class DungeonScalerUtility(unreal.GlobalEditorUtilityBase): pass # ===================================== # 파라미터 (여기만 수정하세요) # ===================================== scale_multiplier = 3.0 # 스케일 배수 # ===================================== # 현재 레벨에 배치된 모든 StaticMeshActor 스케일 조정 # ===================================== all_actors = unreal.EditorLevelLibrary.get_all_level_actors() count = 0 for actor in all_actors: if isinstance(actor, unreal.StaticMeshActor): actor_root = actor.get_editor_property("root_component") old_scale = actor_root.get_editor_property("relative_scale3d") new_scale = unreal.Vector( old_scale.x * scale_multiplier, old_scale.y * scale_multiplier, old_scale.z * scale_multiplier ) actor_root.set_editor_property("relative_scale3d", new_scale) count += 1 print(f"스케일 변경됨: {actor.get_name()} → {new_scale}") unreal.EditorLevelLibrary.save_current_level() print(f"===== 던전 스케일러 완료 ({count}개 액터 수정됨) =====")
import unreal selected_assets = unreal.EditorLevelLibrary.get_selected_level_actors() for actor in selected_assets: actor_class = actor.get_class() # 파라미터 이름 및 수치 parameter_name = "sss" control_bool_val = True # SM Actor 대응 if isinstance(actor, unreal.StaticMeshActor): get_smComp = actor.static_mesh_component for get_mi in get_smComp.get_materials(): if get_mi is not None: get_mi_param = unreal.MaterialEditingLibrary.get_static_switch_parameter_source(get_mi,parameter_name) if get_mi_param : changeval = unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(get_mi, parameter_name, control_bool_val) unreal.MaterialEditingLibrary.update_material_instance(get_mi) print(actor.get_name(), ">", get_mi.get_name(), ">>", parameter_name, ">>>", control_bool_val) else : print(actor.get_name(), ">", get_mi.get_name(), ">>", parameter_name, ">>> 해당 파라미터는 존재하지 않습니다") # BP대응 elif isinstance(actor_class, unreal.BlueprintGeneratedClass): actor_components = actor.get_components_by_class(unreal.ActorComponent) for Comp in actor_components: if isinstance(Comp, unreal.StaticMeshComponent): for get_mi in Comp.get_materials(): if get_mi is not None: get_mi_param = unreal.MaterialEditingLibrary.get_static_switch_parameter_source(get_mi,parameter_name) if get_mi_param: changeval = unreal.MaterialEditingLibrary.set_material_instance_static_switch_parameter_value(get_mi, parameter_name, control_bool_val) unreal.MaterialEditingLibrary.update_material_instance(get_mi) print(actor.get_name(), ">", get_mi.get_name(), ">>", parameter_name, ">>>", control_bool_val) else: print(actor.get_name(), ">", get_mi.get_name(), ">>", parameter_name, ">>> 해당 파라미터는 존재하지 않습니다") else: print("Not SM")
# -*- 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 argparse import json def get_scriptstruct_by_node_name(node_name): control_rig_blueprint = unreal.load_object(None, '/project/') rig_vm_graph = control_rig_blueprint.get_model() nodes = rig_vm_graph.get_nodes() for node in nodes: if node.get_node_path() == node_name: return node.get_script_struct() last_construction_link = 'PrepareForExecution' def create_construction(bone_name): global last_construction_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_Construction_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_Construction_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(137.732236, -595.972187), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) rig_controller.set_node_selection([get_bone_transform_node_name]) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) except Exception as e: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 45: rig_controller.add_link(): " + str(e)) rig_controller.set_node_position_by_name(set_control_transform_node_name, unreal.Vector2D(512.000000, -656.000000)) rig_controller.add_link(last_construction_link + '.ExecuteContext', set_control_transform_node_name + '.ExecuteContext') last_construction_link = set_control_transform_node_name last_backward_solver_link = 'InverseExecution.ExecuteContext' def create_backward_solver(bone_name): global last_backward_solver_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_BackwardSolver_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_BackwardSolver_SetTransform_" + control_name #rig_controller.add_link('InverseExecution.ExecuteContext', 'RigUnit_SetTransform_3.ExecuteContext') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-636.574629, -1370.167943), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) #rig_controller.set_pin_default_value(set_control_transform_node_name + '.Transform', '(Rotation=(X=0.000000,Y=0.000000,Z=0.000000,W=-1.000000),Translation=(X=0.551784,Y=-0.000000,Z=72.358307),Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 84: rig_controller.add_link(): " + str(e)) rig_controller.add_link(last_backward_solver_link, set_control_transform_node_name + '.ExecuteContext') last_backward_solver_link = set_control_transform_node_name + '.ExecuteContext' def create_control(bone_name): control_name = bone_name + '_ctrl' default_setting = unreal.RigControlSettings() default_setting.shape_name = 'Box_Thin' default_setting.control_type = unreal.RigControlType.EULER_TRANSFORM default_value = hierarchy.make_control_value_from_euler_transform( unreal.EulerTransform(scale=[1, 1, 1])) key = unreal.RigElementKey(type=unreal.RigElementType.BONE, name=bone_name) rig_control_element = hierarchy.find_control(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name)) control_key = rig_control_element.get_editor_property('key') print(rig_control_element) if control_key.get_editor_property('name') != "": control_key = rig_control_element.get_editor_property('key') else: try: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True, True) except: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True) transform = hierarchy.get_global_transform(key, True) hierarchy.set_control_offset_transform(control_key, transform, True) if bone_name in control_list: create_direct_control(bone_name) elif bone_name in effector_list: create_effector(bone_name) create_construction(bone_name) create_backward_solver(bone_name) effector_get_transform_widget_height = 0 def create_direct_control(bone_name): global next_forward_execute global effector_get_transform_widget_height #effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_control_transform_node_name = "RigUnit_DirectControl_GetTransform_" + bone_name set_bone_transform_node_name = "RigtUnit_DirectControl_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') except: try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' # def create_preferred_angle_control(bone_name): # global next_forward_execute # global effector_get_transform_widget_height # #effector_get_transform_widget_height += 250 # control_name = bone_name + '_ctrl' # get_control_transform_node_name = "RigUnit_PreferredAngle_GetTransform_" + bone_name # set_bone_transform_node_name = "RigtUnit_PreferredAngle_SetTransform_" + control_name # rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') # rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) # try: # rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # except: # set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") # rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') # rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') # except: # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') # except Exception as e: # print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) # rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') # next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' def create_effector(bone_name): global effector_get_transform_widget_height effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_transform_name = control_name + '_RigUnit_GetTransform' pin_name = rig_controller.insert_array_pin('PBIK.Effectors', -1, '') print(pin_name) rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-122.733358, effector_get_transform_widget_height), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_transform_name + '.Item', True) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_transform_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) rig_controller.set_node_selection([get_transform_name]) rig_controller.add_link(get_transform_name + '.Transform', pin_name + '.Transform') rig_controller.set_pin_default_value(pin_name + '.Bone', bone_name, False) if(bone_name in guide_list): rig_controller.set_pin_default_value(pin_name + '.StrengthAlpha', '0.200000', False) parser = argparse.ArgumentParser(description = 'Creates a Control Rig given a SkeletalMesh') parser.add_argument('--skeletalMesh', help='Skeletal Mesh to Use') parser.add_argument('--dtuFile', help='DTU File to use') args = parser.parse_args() asset_name = args.skeletalMesh.split('.')[1] + '_CR' package_path = args.skeletalMesh.rsplit('/', 1)[0] blueprint = unreal.load_object(name = package_path + '/' + asset_name , outer = None) if not blueprint: blueprint = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=asset_name, package_path=package_path, asset_class=unreal.ControlRigBlueprint, factory=unreal.ControlRigBlueprintFactory()) #blueprint = unreal.load_object(name = '/project/.NewControlRigBlueprint', outer = None) if blueprint: # Turn off notifications or each change will compile the RigVM blueprint.suspend_notifications(True) library = blueprint.get_local_function_library() library_controller = blueprint.get_controller(library) hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() #rig_controller.set_node_selection(['RigUnit_BeginExecution']) hierarchy_controller.import_bones_from_asset(args.skeletalMesh, 'None', True, False, True) # Remove Existing Nodes graph = rig_controller.get_graph() node_count = len(graph.get_nodes()) while node_count > 0: rig_controller.remove_node(graph.get_nodes()[-1]) node_count = node_count - 1 # Create Full Body IK Node rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_BeginExecution', 'Execute', unreal.Vector2D(22.229613, 60.424645), 'BeginExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PrepareForExecution', 'Execute', unreal.Vector2D(-216.659278, -515.130927), 'PrepareForExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_InverseExecution', 'Execute', unreal.Vector2D(-307.389434, -270.395477), 'InverseExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PBIK', 'Execute', unreal.Vector2D(370.599976, 42.845032), 'PBIK') rig_controller.set_pin_default_value('PBIK.Settings', '(Iterations=20,MassMultiplier=1.000000,MinMassMultiplier=0.200000,bStartSolveFromInputPose=True)') rig_controller.set_pin_expansion('PBIK.Settings', False) rig_controller.set_pin_default_value('PBIK.Debug', '(DrawScale=1.000000)') rig_controller.set_pin_expansion('PBIK.Debug', False) rig_controller.set_node_selection(['PBIK']) rig_controller.set_pin_default_value('PBIK.Root', 'hip', False) rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) next_forward_execute = 'BeginExecution.ExecuteContext' #rig_controller.add_link('BeginExecution.ExecuteContext', 'PBIK.ExecuteContext') # Get Bone list for character dtu_data = json.load(open(args.dtuFile.replace('\"', ''))) limits = dtu_data['LimitData'] bones_in_dtu = ['root'] for bone_limits in limits.values(): bone_limit_name = bone_limits[0] #print(bone_limit_name) bones_in_dtu.append(bone_limit_name) # Create Effectors, order matters. Child controls should be after Parent Control effector_list = ['pelvis', 'l_foot', 'r_foot', 'spine4', 'l_hand', 'r_hand'] # G9 effector_list+= ['chestUpper', 'head', 'lFoot', 'rFoot', 'lHand', 'rHand'] #G8 effector_list = [bone for bone in effector_list if bone in bones_in_dtu] #print(effector_list) # These controls are mid chain and don't have full weight guide_list = ['l_shin', 'r_shin', 'l_forearm', 'r_forearm'] # G9 guide_list+= ['lShin', 'rShin', 'lForearmBend', 'rForearmBend'] # G8 guide_list = [bone for bone in guide_list if bone in bones_in_dtu] # These controls are for bones that shouldn't move much on their own, but user can rotate them suggested_rotation_list = ['l_shoulder', 'r_shoulder'] # G9 suggested_rotation_list+= ['lCollar', 'rCollar'] # G8 suggested_rotation_list = [bone for bone in suggested_rotation_list if bone in bones_in_dtu] # This is for controls outside of Full Body IK control_list = ['root', 'hip'] control_list = [bone for bone in control_list if bone in bones_in_dtu] for effector_name in control_list + effector_list + guide_list: create_control(effector_name) parent_list = { 'root':['hip', 'l_foot', 'r_foot', 'l_shin', 'r_shin', 'lFoot', 'rFoot', 'lShin', 'rShin'], 'hip':['pelvis'], 'pelvis':['spine4', 'chestUpper'], 'spine4':['head', 'l_hand', 'r_hand', 'l_forearm', 'r_forearm'], 'chestUpper':['head', 'lHand', 'rHand', 'lForearmBend', 'rForearmBend'] } for parent_bone, child_bone_list in parent_list.items(): if not parent_bone in bones_in_dtu: continue filtered_child_bone_list = [bone for bone in child_bone_list if bone in bones_in_dtu] for child_bone in child_bone_list: hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= child_bone + '_ctrl'), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= parent_bone + '_ctrl'), True) hierarchy.set_local_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=child_bone + '_ctrl'), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,-0.000000],scale=[1.000000,1.000000,1.000000]), True, True) skeletal_mesh = unreal.load_object(name = args.skeletalMesh, outer = None) skeletal_mesh_import_data = skeletal_mesh.get_editor_property('asset_import_data') skeletal_mesh_force_front_x = skeletal_mesh_import_data.get_editor_property('force_front_x_axis') stiff_limits = ['l_shoulder', 'r_shoulder'] stiff_limits+= ['lCollar', 'rCollar'] exclude_limits = ['root', 'hip', 'pelvis'] for bone_limits in limits.values(): # Get the name of the bone bone_limit_name = bone_limits[0] # Add twist bones to the exlude list if 'twist' in bone_limit_name.lower(): exluded_bone_settings = rig_controller.insert_array_pin('PBIK.ExcludedBones', -1, '') rig_controller.set_pin_default_value(exluded_bone_settings, bone_limit_name, False) # Get the bone limits bone_limit_x_min = bone_limits[2] bone_limit_x_max = bone_limits[3] bone_limit_y_min = bone_limits[4] * -1.0 bone_limit_y_max = bone_limits[5] * -1.0 bone_limit_z_min = bone_limits[6] * -1.0 bone_limit_z_max = bone_limits[7] * -1.0 # update the axis if force front was used (facing right) if skeletal_mesh_force_front_x: bone_limit_y_min = bone_limits[2] * -1.0 bone_limit_y_max = bone_limits[3] * -1.0 bone_limit_z_min = bone_limits[4] * -1.0 bone_limit_z_max = bone_limits[5] * -1.0 bone_limit_x_min = bone_limits[6] bone_limit_x_max = bone_limits[7] if not bone_limit_name in exclude_limits: #if not bone_limit_name == "l_shin": continue limit_bone_settings = rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value(limit_bone_settings + '.Bone', bone_limit_name, False) x_delta = abs(bone_limit_x_max - bone_limit_x_min) y_delta = abs(bone_limit_y_max - bone_limit_y_min) z_delta = abs(bone_limit_z_max - bone_limit_z_min) if(x_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Locked', False) elif (x_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) if(y_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Locked', False) elif (y_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) if(z_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Locked', False) elif (z_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Limited', False) # It feels like Min\Max angel aren't the actual extents, but the amount of rotation allowed. So they shoudl be 0 to abs(min, max) # I think there's a bug if a min rotation is more negative than max is positive, the negative gets clamped to the relative positive. rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_x_max, bone_limit_x_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_x_max, abs(bone_limit_x_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_y_max, bone_limit_y_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_y_max, abs(bone_limit_y_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_z_max, bone_limit_z_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_z_max, abs(bone_limit_z_min))), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_y_max, bone_limit_y_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_y_max, bone_limit_y_min)), False) if bone_limit_name in stiff_limits: rig_controller.set_pin_default_value(limit_bone_settings + '.PositionStiffness', '0.800000', False) rig_controller.set_pin_default_value(limit_bone_settings + '.RotationStiffness', '0.800000', False) # Figure out preferred angles, the primary angle is the one that turns the furthest from base pose rig_controller.set_pin_default_value(limit_bone_settings + '.bUsePreferredAngles', 'true', False) x_max_rotate = max(abs(bone_limit_x_min), abs(bone_limit_x_max)) y_max_rotate = max(abs(bone_limit_y_min), abs(bone_limit_y_max)) z_max_rotate = max(abs(bone_limit_z_min), abs(bone_limit_z_max)) #print(bone_limit_name, x_max_rotate, y_max_rotate, z_max_rotate) if bone_limit_name in suggested_rotation_list: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', "0.0", False) create_control(bone_limit_name) to_euler_name = "Preferred_Angles_To_Euler_" + bone_limit_name get_transform_name = "Preferred_Angles_GetRotator_" + bone_limit_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetControlRotator', 'Execute', unreal.Vector2D(-344.784477, 4040.400172), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') #rig_controller.set_pin_default_value(get_transform_name + '.bInitial', 'False') rig_controller.set_pin_default_value(get_transform_name + '.Control', bone_limit_name + '_ctrl', True) #rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) #rig_controller.add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionToEuler', 'Execute', unreal.Vector2D(9.501237, 4176.400172), to_euler_name) #rig_controller.add_link(get_transform_name + '.Transform.Rotation', to_euler_name + '.Value') rig_controller.add_link(get_transform_name + '.Rotator.Roll', limit_bone_settings + '.PreferredAngles.X') rig_controller.add_link(get_transform_name + '.Rotator.Pitch', limit_bone_settings + '.PreferredAngles.Y') rig_controller.add_link(get_transform_name + '.Rotator.Yaw', limit_bone_settings + '.PreferredAngles.Z') else: limit_divider = 1.0 if x_max_rotate > y_max_rotate and x_max_rotate > z_max_rotate: if abs(bone_limit_x_min) > abs(bone_limit_x_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_max / limit_divider), False) if y_max_rotate > x_max_rotate and y_max_rotate > z_max_rotate: if abs(bone_limit_y_min) > abs(bone_limit_y_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_max / limit_divider), False) if z_max_rotate > x_max_rotate and z_max_rotate > y_max_rotate: if abs(bone_limit_z_min) > abs(bone_limit_z_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_max / limit_divider), False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) # Attach the node to execute rig_controller.add_link(next_forward_execute, 'PBIK.ExecuteContext') unreal.ControlRigBlueprintLibrary.set_preview_mesh(blueprint, skeletal_mesh) # Turn on notifications and force a recompile blueprint.suspend_notifications(False) unreal.ControlRigBlueprintLibrary.recompile_vm(blueprint) #rig_controller.add_link('RigUnit_BeginExecution.ExecuteContext', 'PBIK.ExecuteContext')
import unreal def add_attach_track_with_guid(): """ 현재 열려있는 Level Sequence에서 첫 번째로 선택된 바인딩에 Attach 트랙과 섹션을 추가하고, 지정된 GUID를 Constraint Binding ID로 설정합니다. """ # !!! 아래 문자열을 원하는 타겟 바인딩의 GUID로 직접 수정하세요 !!! target_guid_string = "A4F64ECC4E418B6CDBA7DF8D0F1272E9" # 예시 GUID, 반드시 수정 필요 # 현재 열려있는 Level Sequence 가져오기 level_sequence = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence() if not level_sequence: unreal.log_warning("현재 열려있는 Level Sequence가 없습니다. Sequencer를 열고 다시 시도하세요.") return # 선택된 바인딩 가져오기 (정확히 하나만 선택되어야 함) selected_bindings = unreal.LevelSequenceEditorBlueprintLibrary.get_selected_bindings() if not selected_bindings or len(selected_bindings) != 1: unreal.log_error("정확히 하나의 바인딩만 선택해야 합니다.") return target_binding = selected_bindings[0] unreal.log(f"타겟 바인딩: '{target_binding.get_display_name()}'") # 입력된 GUID 문자열을 unreal.Guid 객체로 변환 try: target_guid = unreal.Guid.from_string(target_guid_string) if not target_guid.is_valid(): unreal.log_error(f"입력된 GUID 문자열 '{target_guid_string}'이 유효하지 않습니다.") return unreal.log(f"사용할 타겟 GUID: {target_guid}") except Exception as e: unreal.log_error(f"GUID 문자열 변환 중 오류 발생: {e}") return # Attach 트랙 추가 try: attach_track = target_binding.add_track(unreal.MovieScene3DAttachTrack) if not attach_track: unreal.log_error("Attach 트랙을 추가하지 못했습니다.") return unreal.log(f"'{target_binding.get_display_name()}'에 Attach 트랙 추가됨.") except Exception as e: unreal.log_error(f"Attach 트랙 추가 중 오류 발생: {e}") return # Attach 섹션 추가 try: attach_section = attach_track.add_section() if not attach_section: unreal.log_error("Attach 섹션을 추가하지 못했습니다.") # 추가된 트랙 롤백 (선택 사항) # target_binding.remove_track(attach_track) return unreal.log("Attach 섹션 추가됨.") # 섹션 범위 설정 (예: 시퀀스 전체 길이) start_frame = level_sequence.get_playback_start() end_frame = level_sequence.get_playback_end() attach_section.set_range(start_frame, end_frame) unreal.log(f"섹션 범위 설정됨: {start_frame} - {end_frame}") # Constraint Binding ID 설정 new_binding_id = unreal.MovieSceneObjectBindingID() new_binding_id.set_editor_property("guid", target_guid) # GUID만 설정 attach_section.set_editor_property("constraint_binding_id", new_binding_id) unreal.log(f"Constraint Binding ID 설정됨: GUID={new_binding_id.get_editor_property('guid')}") # 시퀀서 UI 새로고침 (선택 사항) unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence() unreal.log("테스트 스크립트 완료. 시퀀스를 저장하여 변경사항을 확정하세요.") except Exception as e: unreal.log_error(f"Attach 섹션 처리 또는 ID 설정 중 오류 발생: {e}") # 오류 발생 시 트랙 롤백 (선택 사항) # target_binding.remove_track(attach_track) return # --- 스크립트 실행 --- add_attach_track_with_guid()
import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print "Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!" quit() # Create a variant set and add it to lvs var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") lvs.add_variant_set(var_set1) # Create a variant and add it to var_set1 var1 = unreal.Variant() var1.set_display_text("Variant 1") var_set1.add_variant(var1) # Create a test actor and add it to var1. The test actor has almost all possible types of capturable properties location = unreal.Vector() rotation = unreal.Rotator() test_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.VariantManagerTestActor, location, rotation) var1.add_actor_binding(test_actor) capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(test_actor) captured_props = [] print "Capturable properties for actor '" + test_actor.get_actor_label() + "':" for prop in capturable_props: print "\t" + prop # All test properties are named like 'Captured____Property' # The check here avoids capturing generic Actor properties like 'Can be Damaged' if str(prop).startswith('Captured') and str(prop).endswith('Property'): new_prop = var1.capture_property(test_actor, prop) captured_props.append(new_prop) for prop in captured_props: type_str = prop.get_property_type_string() # Set a value for a property depending on its type if type_str == "bool": prop.set_value_bool(True) elif type_str == "int": prop.set_value_int(2) elif type_str == "float": prop.set_value_float(2.0) elif type_str == "object": cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") prop.set_value_object(cube) elif type_str == "strint": prop.set_value_string("new string") elif type_str == "rotator": prop.set_value_rotator(unreal.Rotator(11, 12, 13)) elif type_str == "color": prop.set_value_color(unreal.Color(21, 22, 23, 24)) elif type_str == "linear_color": prop.set_value_linear_color(unreal.LinearColor(0.31, 0.32, 0.33, 0.34)) elif type_str == "vector": prop.set_value_vector(unreal.Vector(41, 42, 43)) elif type_str == "quat": prop.set_value_quat(unreal.Quat(0.51, 0.52, 0.53, 0.54)) elif type_str == "vector4": prop.set_value_vector4(unreal.Vector4(6.1, 6.2, 6.3, 6.4)) elif type_str == "Vector2D": prop.set_value_vector2d(unreal.Vector2D(7.1, 7.2)) elif type_str == "int_Point": prop.set_value_int_point(unreal.IntPoint(81, 82)) # Easier to print using getattr for prop in captured_props: type_str = prop.get_property_type_string() print(getattr(prop, "get_value_" + type_str)())
import unreal actor_subsys = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) level_actors = actor_subsys.get_all_level_actors() filtered_list = unreal.EditorFilterLibrary.by_actor_label( level_actors, "my_actor", unreal.EditorScriptingStringMatchType.EXACT_MATCH ) actor = filtered_list[0] value = actor.get_editor_property("my_property") print (value)
import unreal actorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) actors = actorSubsystem.get_selected_level_actors() for actor in actors: sm_comps = actor.get_components_by_class(unreal.StaticMeshComponent) for sm_comp in sm_comps: comp_name = sm_comp.get_name() sm_comp.rename("Generated " + comp_name)
# Copyright Epic Games, Inc. All Rights Reserved # Built-in import argparse from getpass import getuser # Internal from deadline_service import get_global_deadline_service_instance from deadline_job import DeadlineJob from deadline_menus import DeadlineToolBarMenu # Third Party import unreal # Editor Utility Widget path # NOTE: This is very fragile and can break if naming or pathing changes EDITOR_UTILITY_WIDGET = "/project/" def _launch_job_submitter(): """ Callback to execute to launch the job submitter """ unreal.log("Launching job submitter.") submitter_widget = unreal.EditorAssetLibrary.load_asset(EDITOR_UTILITY_WIDGET) # Get editor subsystem subsystem = unreal.get_editor_subsystem(unreal.EditorUtilitySubsystem) # Spawn the submitter widget subsystem.spawn_and_register_tab(submitter_widget) def register_menu_action(): """ Creates the toolbar menu """ if not _validate_euw_asset_exists(): unreal.log_warning( f"EUW {EDITOR_UTILITY_WIDGET} does not exist in the Asset registry!" ) return toolbar = DeadlineToolBarMenu() toolbar.register_submenu( "SubmitDeadlineJob", _launch_job_submitter, label_name="Submit Deadline Job", description="Submits a job to Deadline" ) def _validate_euw_asset_exists(): """ Make sure our reference editor utility widget exists in the asset registry :returns: Array(AssetData) or None """ asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() asset_data = asset_registry.get_assets_by_package_name( EDITOR_UTILITY_WIDGET, include_only_on_disk_assets=True ) return True if asset_data else False def _execute_submission(args): """ Creates and submits a job to Deadline :param args: Commandline args """ unreal.log("Executing job submission") # Create a Deadline job from the selected job preset deadline_job = DeadlineJob(job_preset=unreal.load_asset(args.job_preset_asset)) if not deadline_job.job_info.get("UserName", None): deadline_job.job_info = {"UserName": getuser()} deadline_service = get_global_deadline_service_instance() # Submit the Deadline Job job_id = deadline_service.submit_job(deadline_job) unreal.log(f"Deadline job submitted. JobId: {job_id}") if __name__ == "__main__": unreal.log("Executing job submitter action") parser = argparse.ArgumentParser( description="Submits a job to Deadline", add_help=False, ) parser.add_argument( "--job_preset_asset", type=str, help="Deadline Job Preset Asset" ) parser.set_defaults(func=_execute_submission) # Parse the arguments and execute the function callback arguments = parser.parse_args() arguments.func(arguments)
import unreal editor_asset_lib = unreal.EditorAssetLibrary editor_level_lib = unreal.EditorLevelLibrary editor_filter_lib = unreal.EditorFilterLibrary material_pad = "/project/.Object_ALV_TCF__30x20x11_" new_material_pad = "/project/.MI_Decorative_Brick_Wall_vi0lbih_2K" def reaplce_material(original, replacement): material = editor_asset_lib.load_asset(material_pad) new_material = editor_asset_lib.load_asset(new_material_pad) if material is None: unreal.log_warning("The original was not found please try again") quit() elif new_material is None: unreal.log_warning("The new material was not found please try again") quit() try: editor_asset_lib.consolidate_assets(new_material, [material]) unreal.log("The material was succesfully updated") except: unreal.log_warning("Something went wrong!") reaplce_material(material_pad, new_material_pad)
''' File: Author: Date: Description: Other Notes: ''' import unreal ##### # Code to print out all or specific actors in a loaded level - Confirmed editor = unreal.EditorLevelLibrary() actors = editor.get_all_level_actors() for y in actors: if 'SunSky' in y.get_name(): sunsky = y print("*** DEBUG: Found Sunsky object") print("-------------------") print(sunsky.get_components_by_class(unreal.SceneComponent)) print(sunsky.get_component_by_class(unreal.SkyLightComponent)) skylight = sunsky.get_component_by_class(unreal.SkyLightComponent) print("-------------------") print(sunsky) print(sunsky.get_editor_property("Latitude")) print(sunsky.get_editor_property("Longitude")) print(sunsky.get_editor_property("NorthOffset")) print(sunsky.get_editor_property("TimeZone")) print(sunsky.get_editor_property("Month")) print(sunsky.get_editor_property("Day")) print(sunsky.get_editor_property("SolarTime")) import random i = random.randint(12, 23) sunsky.set_editor_property("SolarTime", i)
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) #print(sk.bone_tree) # #kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss"); #kk.name = "" #kk.type = 1; #print(h_mod.get_bone(kk)) #print(h_mod.get_elements()) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] #for e in reversed(h_mod.get_elements()): # if (e.type != unreal.RigElementType.BONE): # h_mod.remove_element(e) for e in h_mod.get_elements(): if (e.type == unreal.RigElementType.BONE): modelBoneListAll.append(e) modelBoneNameList.append("{}".format(e.name).lower()) # else: # h_mod.remove_element(e) print(modelBoneListAll[0]) #exit #print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode")) #print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index")) #unreal.select #vrmlist = unreal.VrmAssetListObject #vrmmeta = vrmlist.vrm_meta_object #print(vrmmeta.humanoid_bone_table) #selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() #selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class()) #static_meshes = np.array([]) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv #v:unreal.VrmAssetListObject = None #if (True): # a = reg.get_assets_by_path(args.vrm) # a = reg.get_all_assets(); # for aa in a: # if (aa.get_editor_property("object_path") == args.vrm): # v:unreal.VrmAssetListObject = aa #v = unreal.VrmAssetListObject.cast(v) #print(v) #unreal.VrmAssetListObject.vrm_meta_object #meta = v.vrm_meta_object() #meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class()) print (meta) #print(meta[0].humanoid_bone_table) ### モデル骨のうち、ヒューマノイドと同じもの ### 上の変換テーブル humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() ### modelBoneでループ #for bone_h in meta.humanoid_bone_table: for bone_h_base in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == bone_h_base): bone_h = e; break; print("{}".format(bone_h)) if (bone_h==None): continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m.lower()) except: i = -1 if (i < 0): continue if ("{}".format(bone_h).lower() == "upperchest"): continue; humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower() if ("{}".format(bone_h).lower() == "chest"): #upperchestがあれば、これの次に追加 bh = 'upperchest' print("upperchest: check begin") for e in meta.humanoid_bone_table: if ("{}".format(e).lower() != 'upperchest'): continue bm = "{}".format(meta.humanoid_bone_table[e]).lower() if (bm == ''): continue humanoidBoneToModel[bh] = bm humanoidBoneParentList[10] = "upperchest" humanoidBoneParentList[12] = "upperchest" humanoidBoneParentList[13] = "upperchest" print("upperchest: find and insert parent") break print("upperchest: check end") parent=None control_to_mat={None:None} count = 0 ### 骨名からControlへのテーブル name_to_control = {"dummy_for_table" : None} print("loop begin") ###### root key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'root_s') space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space('root_s', space_type=unreal.RigSpaceType.SPACE) else: space = key key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c') control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control('root_c', space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) else: control = key h_mod.reparent_element(control, space) parent = control cc = h_mod.get_control(control) cc.set_editor_property('gizmo_visible', False) h_mod.set_control(cc) for ee in humanoidBoneToModel: element = humanoidBoneToModel[ee] humanoidBone = ee modelBoneNameSmall = element # 対象の骨 #modelBoneNameSmall = "{}".format(element.name).lower() #humanoidBone = modelBoneToHumanoid[modelBoneNameSmall]; boneNo = humanoidBoneList.index(humanoidBone) print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo])) # 親 if count != 0: parent = name_to_control[humanoidBoneParentList[boneNo]] # 階層作成 bIsNew = False name_s = "{}_s".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.SPACE, name_s) space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space(name_s, space_type=unreal.RigSpaceType.SPACE) bIsNew = True else: space = key name_c = "{}_c".format(humanoidBone) key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c) control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) #h_mod.get_control(control).gizmo_transform = gizmo_trans if (24<=boneNo & boneNo<=53): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1]) else: gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) if (17<=boneNo & boneNo<=18): gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1]) cc = h_mod.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_mod.set_control(cc) #h_mod.set_control_value_transform(control,gizmo_trans) bIsNew = True else: control = key if (bIsNew == True): h_mod.reparent_element(control, space) # テーブル登録 name_to_control[humanoidBone] = control print(humanoidBone) # ロケータ 座標更新 # 不要な上層階層を考慮 gTransform = h_mod.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)]) if count == 0: bone_initial_transform = gTransform else: #bone_initial_transform = h_mod.get_initial_transform(element) bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse()) h_mod.set_initial_transform(space, bone_initial_transform) control_to_mat[control] = gTransform # 階層修正 h_mod.reparent_element(space, parent) count += 1 if (count >= 500): break
import unreal def import_data_table_as_json(filename): task = unreal.AssetImportTask() task.filename = filename task.destination_path = "/project/" task.replace_existing = True task.automated = True task.save = False task.factory = unreal.ReimportDataTableFactory() task.factory.automated_import_settings.import_row_struct = unreal.load_object(None, '/project/') task.factory.automated_import_settings.import_type = unreal.CSVImportType.ECSV_DATA_TABLE unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task]) import_data_table_as_json("C:/project/.json")
# -*- coding: utf-8 -*- import unreal from Utilities.Utils import Singleton class MinimalExample(metaclass=Singleton): def __init__(self, json_path:str): self.json_path = json_path self.data:unreal.ChameleonData = unreal.PythonBPLib.get_chameleon_data(self.json_path) self.ui_output = "InfoOutput" self.click_count = 0 def on_button_click(self): self.click_count += 1 self.data.set_text(self.ui_output, "Clicked {} time(s)".format(self.click_count))
import inspect import time import Example from enum import Enum, auto import unreal from Utilities.Utils import Singleton import Utilities.ChameleonTaskExecutor import importlib importlib.reload(Utilities.ChameleonTaskExecutor) from Utilities.ChameleonTaskExecutor import ChameleonTaskExecutor, get_func_type class AnotherClass(): def __init__(self): ... def instance_fake_task(self, seconds:float): print(f"*** AnotherClass instance_fake_task") time.sleep(seconds) print(f"*** AnotherClass instance_fake_task done, {seconds}s") @staticmethod def static_fake_task(seconds:float): print(f"--- AnotherClass static_fake_task") time.sleep(seconds) print(f"--- AnotherClass static_fake_task done, {seconds}s") @classmethod def class_fake_task(cls, seconds: float): print(f"=== AnotherClass class_fake_task") time.sleep(seconds) print(f"=== AnotherClass class_fake_task done, {seconds}s") def instance_done(self, future_id:int): print(f"*** AnotherClass instance done: {future_id}") @staticmethod def static_done(future_id:int): print(f"--- AnotherClass static_done: {future_id}") @classmethod def class_done(cls, future_id:int): print(f"=== AnotherClass class_done: {future_id}") class AsyncTaskExample(metaclass=Singleton): def __init__(self, json_path:str): print("SlowToolTest.__init__ call") self.json_path = json_path self.data:unreal.ChameleonData = unreal.PythonBPLib.get_chameleon_data(self.json_path) self.ui_text_block = "TextBlock" self.ui_busy_icon = "BusyIcon" self.ui_throbber = "Throbber" self.other = AnotherClass() self.executor = ChameleonTaskExecutor(self) def instance_fake_task(self, seconds:float): print(f"*** instance_fake_task") time.sleep(seconds) print(f"*** instance_fake_task done, {seconds}s") return seconds @staticmethod def static_fake_task(seconds:float): print(f"--- static_fake_task") time.sleep(seconds) print(f"--- static_fake_task done, {seconds}s") @classmethod def class_fake_task(cls, seconds: float): print(f"=== class_fake_task") time.sleep(seconds) print(f"=== class_fake_task done, {seconds}s") def instance_done(self, future_id:int): future = self.executor.get_future(future_id) result = future.result() if future else None print(f"*** instance done: {future_id} result: {result}") self.data.set_text(self.ui_text_block, f"instance{future_id}_done{result}") @staticmethod def static_done(future_id:int): print(f"--- static_done: {future_id}") @classmethod def class_done(cls, future_id:int): print(f"=== classmethod: {future_id}") def some_func1(): ... def log_func_cmd(self): s = ChameleonTaskExecutor.get_cmd_str_from_callable(self.other.instance_done) print(s) def log_functions(self): print("=== self ===") print("{} is a {}".format("self.instance_done", get_func_type(self.instance_done))) print("{} is a {}".format("self.class_done", get_func_type(self.class_done))) print("{} is a {}".format("self.static_done", get_func_type(self.static_done))) print("{} is a {}".format("AsyncTaskExample.instance_done", get_func_type(AsyncTaskExample.instance_done))) print("{} is a {}".format("AsyncTaskExample.class_done", get_func_type(AsyncTaskExample.class_done))) print("{} is a {}".format("AsyncTaskExample.static_done", get_func_type(AsyncTaskExample.static_done))) print("{} is a {}".format("staticmethod(self.static_done)", get_func_type(staticmethod(self.static_done)))) print("{} is a {}".format("lambda o: print(1)", get_func_type(lambda o: print(1)))) print("{} is a {}".format("AsyncTaskExample.some_func1", get_func_type(AsyncTaskExample.some_func1))) def some_slow_tasks(self): self.executor.submit_task(self.instance_fake_task, args=[0.5], on_finish_callback=self.instance_done) self.executor.submit_task(self.instance_fake_task, args=[1], on_finish_callback=self.other.instance_done) self.executor.submit_task(self.instance_fake_task, args=[1.5], on_finish_callback=Example.AsyncTaskExample.AsyncTaskExample.static_done) self.executor.submit_task(self.instance_fake_task, args=[2], on_finish_callback=self.class_done) self.executor.submit_task(AsyncTaskExample.static_fake_task, args=[2.5], on_finish_callback=self.instance_done) self.executor.submit_task(AsyncTaskExample.static_fake_task, args=[3], on_finish_callback=Example.AsyncTaskExample.AsyncTaskExample.static_done) self.executor.submit_task(AsyncTaskExample.class_fake_task, args=[3.5], on_finish_callback=Example.AsyncTaskExample.AsyncTaskExample.class_done) self.executor.submit_task(AsyncTaskExample.class_fake_task, args=[4], on_finish_callback=self.other.class_done) self.executor.submit_task(AsyncTaskExample.class_fake_task, args=[4.5], on_finish_callback=dir) self.executor.submit_task(self.other.instance_fake_task, args=[5], on_finish_callback=self.instance_done) self.executor.submit_task(self.other.instance_fake_task, args=[5.5], on_finish_callback=self.other.instance_done) def on_task_finish(self, future_id:int): future = self.executor.get_future(future_id) if future is None: unreal.log_warning(f"Can't find future: {future_id}") else: self.data.set_text(self.ui_text_block, f"Done {future.result()}") print(f"log Done. Future: {future} id: {future_id} result: {future.result()}") def show_busy_info(self): self.data.set_text(self.ui_text_block, "Running") self.data.set_visibility(self.ui_throbber, "Visible")
import unreal """ Should be used with internal UE Python API Auto generate LODs for static meshes""" asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() asset_root_dir = '/project/' assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True) def generate_lods(static_mesh): number_of_vertices = unreal.EditorStaticMeshLibrary.get_number_verts(static_mesh, 0) if number_of_vertices < 10: return options = unreal.EditorScriptingMeshReductionOptions() options.reduction_settings = [ unreal.EditorScriptingMeshReductionSettings(1.0, 1.0), unreal.EditorScriptingMeshReductionSettings(0.8, 0.75), unreal.EditorScriptingMeshReductionSettings(0.6, 0.5), unreal.EditorScriptingMeshReductionSettings(0.4, 0.25) ] options.auto_compute_lod_screen_size = True unreal.EditorStaticMeshLibrary.set_lods(static_mesh, options) unreal.EditorAssetLibrary.save_loaded_asset(static_mesh) for asset in assets: if asset.asset_class == "StaticMesh": loaded_asset = unreal.EditorAssetLibrary.find_asset_data(asset.object_path).get_asset() generate_lods(loaded_asset)
from datetime import date import unreal today = str(date.today()) unreal.EditorDialog.show_message("The title", today, unreal.AppMsgType.OK)
# develop 分支 from operator import contains # UPDATE: 2024/project/ 15:01 -> 新增命名匹配逻辑,对于PD开头,body结尾的actor,进行正则表达式匹配,将__body后面的字符替换为空字符串 # UPDATE: 2024/project/ 16:24 -> 本脚本是对于merge.py的简化,用于针对性的对供应商的模型按原AO+工位进行分类。原始脚本请看merge.py import unreal import csv import time import os import pandas as pd # 正则表达式模块 import re def saveToAsset(actor, GW, AO): try: setting = unreal.MeshMergingSettings() setting.pivot_point_at_zero = True setting.merge_materials = False options = unreal.MergeStaticMeshActorsOptions( destroy_source_actors=False, spawn_merged_actor=False, mesh_merging_settings=setting ) # TODO:模型保存路径 # 供应商模型保存路径 # temp_dir = os.path.join('/project/', str(GW), str(AO)) # 上飞厂模型保存路径 temp_dir = os.path.join('/project/', str(GW), str(AO)) actor_label = actor.get_actor_label() asset_path = os.path.join(temp_dir,actor_label).replace('\\', '/') # /project/-000-403/PD_269A1011-011-001__body1 options.base_package_name = asset_path # The package path you want to save to1 if unreal.EditorAssetLibrary().does_asset_exist(asset_path): unreal.log_warning("当前资产 %s 已存在" % actor_label) else: merge_actor = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem).merge_static_mesh_actors([actor], options) unreal.log("EXPORT SUCCESS : %s is save to %s" % (actor.get_actor_label(), asset_path.replace('\\', '/'))) except Exception as e: unreal.log_error(f"Error in saveToAsset: {e}") level_lib = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) asset_lib = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) static_mesh_lib = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) selected_actors = level_lib.get_selected_level_actors() if not selected_actors: unreal.log_error("No actors selected.") exit() all_static_mesh_actors = [] for item in selected_actors: label = item.get_name().split('_') if label and label[0] == "StaticMeshActor": all_static_mesh_actors.append(item) # TODO:CSV路径 # 供应商CSV路径 # csv_path = r"/project/-000-403\531A0000-000-403_0918.csv" # 上飞厂CSV路径 csv_path = r"/project/.csv" file_name = csv_path.split('\\')[-1].split('_')[0] df = pd.read_csv(csv_path) # TODO:仅需针对性修改列名称即可筛选目标列 # 供应商CSV列名 # df_target_col = df.loc[:, ['零组件编号',"下级工程组件"]] # 上飞厂CSV列名 df_target_col = df.loc[:,['工位','零组件号',"下级工艺件"]] timeStart = time.time() # 批量处理:逻辑已修改 batch_size = 5000 # 每批处理的数量 num_batches = (len(all_static_mesh_actors) + batch_size - 1) # batch_size csv_count = 0 no_data_count = 0 for i in range(num_batches): batch = all_static_mesh_actors[i * batch_size:(i + 1) * batch_size] # for item in batch: # unreal.log(item.get_actor_label()) for item in batch: item_name = item.get_actor_label() if item.get_actor_label().startswith("PD_"): item_name = item.get_actor_label().replace("PD_", "" , 1) if contains(item_name, "__body"): # 使用正则表达式匹配 '__body' 及其后面的所有字符,并替换为空字符串 # sub函数用于替换字符串中匹配正则表达式模式的部分 # r:表示原始字符串,告诉 Python 不要处理字符串中的转义字符。 # .*:匹配除换行符之外的任何单个字符 # $:表示字符串的末尾 item_name = re.sub(r'__body.*$', '', item_name) # print(item_name) if item.static_mesh_component.static_mesh: # TODO:替换列名称:零组件号 / 零组件编号 # 供应商CSV列名 # df_copy = df_target_col[df['零组件编号'] == item_name].copy() # 上飞厂CSV列名 df_copy = df_target_col[df['零组件号'] == item_name].copy() if df_copy.size: for index, row in df_copy.iterrows(): # TODO:修改工位和保存名称 # 供应商工位号和保存零件名称 # saveToAsset(item, '221', file_name) # 上飞厂工位号和保存零件名称 saveToAsset(item, row['工位'], row['下级工艺件']) unreal.log("save_to_asset") else: unreal.log(f"当前csv数据中未找到:{item.get_actor_label()}") csv_count += 1 else: unreal.log_error(f"丢失static mesh component:{item.get_actor_label()}") no_data_count += 1 # 处理完一批后,可以调用GC(垃圾回收),以释放内存 unreal.SystemLibrary.collect_garbage() unreal.log(csv_count) unreal.log(no_data_count) unreal.log_warning(time.time() - timeStart) # TODO:修改资产保存逻辑 # 供应商模型保存 # unreal.get_editor_subsystem(unreal.EditorAssetSubsystem).save_directory('/project/',only_if_is_dirty=True,recursive=True) # 上飞厂模型保存 unreal.get_editor_subsystem(unreal.EditorAssetSubsystem).save_directory('/project/',only_if_is_dirty=True,recursive=True) unreal.log("保存执行完毕!")
# 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 sys import os import json def import_animations_from_json(anim_dict_path): """ Function to call via the subprocess version / unreal cmd.exe version of the gameplay import to import all anims in json :param anim_dict_path: path to json with sequence_data :return: """ if not os.path.exists(anim_dict_path): unreal.log_error(f"FILE DOES NOT EXIST: {anim_dict_path}") return script_dir = os.path.dirname(__file__) tools_dir = os.path.dirname(script_dir) sys.path.append(tools_dir) from unreal_tools import sequence_importer sequence_path = sequence_importer.import_gameplay_animations_from_json(anim_dict_path) unreal.log(f"Imported Animations for : {sequence_path}") return sequence_path if __name__ == "__main__": # Load the args script_dir = os.path.dirname(__file__) args_path = "C:/project/.json" if not os.path.exists(args_path): raise ValueError("Missing sequence_args.json") with open(args_path, "r") as f: args = json.load(f) anim_dict_path = args.get("anim_dict_path") if not anim_dict_path: raise ValueError("Missing required argument: anim_dict_path") unreal.log(f"Parsed anim_dict_path: {anim_dict_path}") import_animations_from_json(anim_dict_path)
# coding: utf-8 import unreal def executeConsoleCommand(): console_commands = ['r.ScreenPercentage 0.1', 'r.Color.Max 6', 'stat fps', 'stat unit'] for x in console_commands: unreal.CppLib.execute_console_command(x) # import EditorFunction_2 as ef # reload(ef) # ef.executeConsoleCommand()
import unreal import argparse import sys import os import json import tkinter as tk from tkinter import filedialog def create_performance_asset(path_to_identity : str, path_to_capture_data : str, save_performance_location : str) -> unreal.MetaHumanPerformance: capture_data_asset = unreal.load_asset(path_to_capture_data) identity_asset = unreal.load_asset(path_to_identity) performance_asset_name = "{0}_Performance".format(capture_data_asset.get_name()) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() performance_asset = asset_tools.create_asset(asset_name=performance_asset_name, package_path=save_performance_location, asset_class=unreal.MetaHumanPerformance, factory=unreal.MetaHumanPerformanceFactoryNew()) performance_asset.set_editor_property("identity", identity_asset)# load into the identity setting performance_asset.set_editor_property("footage_capture_data", capture_data_asset)# load into the capture footage setting return performance_asset def run_animation_export(output_order, performance_asset : unreal.MetaHumanPerformance): performance_asset_name = "AS"+str(output_order)# this is the name of the animation sequence, can be changed unreal.log("Exporting animation sequence for Performance '{0}'".format(performance_asset_name)) export_settings = unreal.MetaHumanPerformanceExportAnimationSettings() export_settings.enable_head_movement = False# Enable or disable to export the head rotation export_settings.show_export_dialog = False export_settings.export_range = unreal.PerformanceExportRange.PROCESSING_RANGE anim_sequence: unreal.AnimSequence = unreal.MetaHumanPerformanceExportUtils.export_animation_sequence(performance_asset, export_settings) unreal.log("Exported Anim Sequence {0}".format(performance_asset_name)) def process_shot(output_order, performance_asset : unreal.MetaHumanPerformance, export_level_sequence : bool, export_sequence_location : str, path_to_meta_human_target : str, start_frame : int = None, end_frame : int = None): performance_asset_name = "AS"+str(output_order)# this is the name of the animation sequence, can be changed if start_frame is not None: performance_asset.set_editor_property("start_frame_to_process", start_frame) if end_frame is not None: performance_asset.set_editor_property("end_frame_to_process", end_frame) #Setting process to blocking will make sure the action is executed on the main thread, blocking it until processing is finished process_blocking = True performance_asset.set_blocking_processing(process_blocking) unreal.log("Starting MH pipeline for '{0}'".format(performance_asset_name)) startPipelineError = performance_asset.start_pipeline() if startPipelineError is unreal.StartPipelineErrorType.NONE: unreal.log("Finished MH pipeline for '{0}'".format(performance_asset_name)) elif startPipelineError is unreal.StartPipelineErrorType.TOO_MANY_FRAMES: unreal.log("Too many frames when starting MH pipeline for '{0}'".format(performance_asset_name)) else: unreal.log("Unknown error starting MH pipeline for '{0}'".format(performance_asset_name)) #export the animation sequence run_animation_export(output_order, performance_asset) def run(output_order, number, end_frame): #load into the metahuman identity and capture footage, then output a metahuman performance performance_asset = create_performance_asset( path_to_identity="/project/", # can be changed path_to_capture_data="/project/"+str(number)+"_Ingested/006Vasilisa_"+str(number), # can be changed save_performance_location="/project/") # can be changed #process the metahuman performance and export the animation sequence process_shot( output_order=output_order, performance_asset=performance_asset, export_level_sequence=True, export_sequence_location="/project/", # can be changed path_to_meta_human_target="/project/", # can be changed start_frame=0, end_frame=end_frame) # function to get the current level sequence and the sequencer objects def get_sequencer_objects(level_sequence): world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() #sequence_asset = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence() sequence_asset = level_sequence range = sequence_asset.get_playback_range() sequencer_objects_list = [] sequencer_names_list = [] bound_objects = [] sequencer_objects_list_temp = unreal.SequencerTools.get_bound_objects(world, sequence_asset, sequence_asset.get_bindings(), range) for obj in sequencer_objects_list_temp: bound_objects = obj.bound_objects if len(bound_objects)>0: if type(bound_objects[0]) == unreal.Actor: sequencer_objects_list.append(bound_objects[0]) sequencer_names_list.append(bound_objects[0].get_actor_label()) return sequence_asset, sequencer_objects_list, sequencer_names_list # function to export the face animation keys to a json file def mgMetaHuman_face_keys_export(level_sequence, output_path): system_lib = unreal.SystemLibrary() root = tk.Tk() root.withdraw() face_anim = {} world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() sequence_asset, sequencer_objects_list,sequencer_names_list = get_sequencer_objects(level_sequence) face_possessable = None editor_asset_name = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(sequence_asset).split('.')[-1] for num in range(0, len(sequencer_names_list)): actor = sequencer_objects_list[num] asset_name = actor.get_actor_label() bp_possessable = sequence_asset.add_possessable(actor) child_possessable_list = bp_possessable.get_child_possessables() character_name = '' for current_child in child_possessable_list: if 'Face' in current_child.get_name(): face_possessable = current_child if face_possessable: character_name = (face_possessable.get_parent().get_display_name()) face_possessable_track_list = face_possessable.get_tracks() face_control_rig_track = face_possessable_track_list[len(face_possessable_track_list)-1] face_control_channel_list = unreal.MovieSceneSectionExtensions.get_all_channels(face_control_rig_track.get_sections()[0]) face_control_name_list = [] for channel in face_control_channel_list: channel_name = str(channel.get_name()) channel_string_list = channel_name.split('_') channel_name = channel_name.replace('_' + channel_string_list[-1], '') face_control_name_list.append(channel_name) for ctrl_num in range(0, len(face_control_channel_list)): control_name = face_control_name_list[ctrl_num] try: numKeys = face_control_channel_list[ctrl_num].get_num_keys() key_list = [None] * numKeys keys = face_control_channel_list[ctrl_num].get_keys() for key in range(0, numKeys): key_value = keys[key].get_value() key_time = keys[key].get_time(time_unit=unreal.SequenceTimeUnit.DISPLAY_RATE).frame_number.value key_list[key]=([key_value, key_time]) face_anim[control_name] = key_list except: face_anim[control_name] = [] character_name = str(character_name) if 'BP_' in character_name: character_name = character_name.replace('BP_', '') if 'BP ' in character_name: character_name = character_name.replace('BP ', '') character_name = character_name.lower() print('character_name is ' + character_name) folder_path = output_path os.makedirs(folder_path, exist_ok=True) file_path = os.path.join(folder_path, f'{editor_asset_name}_face_anim.json') with open(file_path, 'w') as keys_file: keys_file.write('anim_keys_dict = ') keys_file.write(json.dumps(face_anim)) print('Face Animation Keys output to: ' + str(keys_file.name)) else: print(editor_asset_name) print('is not a level sequence. Skipping.') #path that contains video data, start to process performance path = "/project/" #can be changed output_order = 1 for i in os.listdir(path): set_path = os.path.join(path, i) if os.path.isdir(set_path): #get the current folder number folder_number = int(i.split("_")[-1]) json_file_path = os.path.join(set_path, "take.json") if os.path.isfile(json_file_path): with open(json_file_path, "r") as file: data = json.load(file) end_frame = data["frames"] end_frame = end_frame // 2 + 1 run(output_order, folder_number, end_frame) print("The performance process is done!") output_order += 1 # The start the second part: create the level sequence and export the sequence # add a new actor into the world actor_path = "/project/" # the path of the actor, can be changed actor_class = unreal.EditorAssetLibrary.load_blueprint_class(actor_path) coordinate = unreal.Vector(-25200.0, -25200.0, 100.0) # randomly put it on a coordinate of the world editor_subsystem = unreal.EditorActorSubsystem() new_actor = editor_subsystem.spawn_actor_from_class(actor_class, coordinate) animation_sequence = dict() #assume the dataset is only 50 folders !!! Important, need to be changed base on real dataset number!! And number order should be 1, 2, 3, 4, ... ... for i in range(1,50): animation_sequence[i] = False path = "/project/" #folder that contain all the character folders, need to be changed base on the real path, can be changed #for every character folder, start to do the work: for i in os.listdir(path): set_path = os.path.join(path, i) #the path of each specific character folder if os.path.isdir(set_path): #if it is indeed a directory json_file_path = os.path.join(set_path, "take.json") if os.path.isfile(json_file_path): #if the json file exists -> create a new level sequence -> set the playback range with open(json_file_path) as file: data = json.load(file) frames_value = data["frames"] value = frames_value // 2 + 1 #this is the upper bound of the frame range #create a new level sequence asset_tools = unreal.AssetToolsHelpers.get_asset_tools() asset_name = set_path.split("\\")[-1] #get the last part of the path level_sequence = unreal.AssetTools.create_asset(asset_tools, asset_name, package_path = "/Game/", asset_class = unreal.LevelSequence, factory = unreal.LevelSequenceFactoryNew()) level_sequence.set_playback_start(0) #starting frame will always be 0 level_sequence.set_playback_end(value) #end #start to load into the animation to the current face track: #Need to be changed base on the real name face_anim_path = "/project/" #then from low to high to load the animation sequence into the current face track (if the sequenced is loaded before, it will not be loaded again, then go the next) for i in range(26,50):#And number order of the animation file should be continueing!!! final_face_anim_path = face_anim_path + str(i) + "_Performance" if final_face_anim_path:#if the path exists if animation_sequence[i] == False:#if the animation sequence is not used before animation_sequence[i] = True anim_asset = unreal.EditorAssetLibrary.load_asset(final_face_anim_path) print("animation sequence:" + str(anim_asset)) break else: continue anim_asset = unreal.AnimSequence.cast(anim_asset) params = unreal.MovieSceneSkeletalAnimationParams() params.set_editor_property("Animation", anim_asset) #add the actor into the level sequence actor_binding = level_sequence.add_possessable(new_actor) transform_track = actor_binding.add_track(unreal.MovieScene3DTransformTrack) anim_track = actor_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack) # Add section to track to be able to manipulate range, parameters, or properties transform_section = transform_track.add_section() anim_section = anim_track.add_section() # Get level sequence start and end frame start_frame = level_sequence.get_playback_start() end_frame = level_sequence.get_playback_end() # Set section range to level sequence start and end frame transform_section.set_range(start_frame, end_frame) anim_section.set_range(start_frame, end_frame) #add face animation track components = new_actor.get_components_by_class(unreal.SkeletalMeshComponent) print("Components of Cooper: ") print(components) face_component = None for component in components: if component.get_name() == "Face": face_component = component break print(face_component) #get the face track (same technique as above): face_binding = level_sequence.add_possessable(face_component) print(face_binding) transform_track2 = face_binding.add_track(unreal.MovieScene3DTransformTrack) anim_track2 = face_binding.add_track(unreal.MovieSceneSkeletalAnimationTrack) transform_section2 = transform_track2.add_section() anim_section2 = anim_track2.add_section() anim_section2.set_editor_property("Params", params)#add animation transform_section2.set_range(start_frame, end_frame) anim_section2.set_range(start_frame, end_frame) # bake to control rig to the face print("level sequence: " + str(level_sequence)) editor_subsystem = unreal.UnrealEditorSubsystem() world = editor_subsystem.get_editor_world() print("world: " + str(world)) anim_seq_export_options = unreal.AnimSeqExportOption() print("anim_seq_export_options: " + str(anim_seq_export_options)) control_rig = unreal.load_object(name = '/project/', outer = None)# can be changed control_rig_class = control_rig.get_control_rig_class()# use class type in the under argument print("control rig class: " + str(control_rig_class)) unreal.ControlRigSequencerLibrary.bake_to_control_rig(world, level_sequence, control_rig_class = control_rig_class, export_options = anim_seq_export_options, tolerance = 0.01, reduce_keys = False, binding = face_binding) # Refresh to visually see the new level sequence unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence() # Export the current face animation keys to a json file output_path = "/project/" # can be changed mgMetaHuman_face_keys_export(level_sequence, output_path) unreal.LevelSequenceEditorBlueprintLibrary.refresh_current_level_sequence() print("Well Done! Jerry!")
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") args = parser.parse_args() print(args.vrm) #print(dummy[3]) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", # 9 optional "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", # 24 "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", #54 ] humanoidBoneParentList = [ "", #"hips", "hips",#"leftUpperLeg", "hips",#"rightUpperLeg", "leftUpperLeg",#"leftLowerLeg", "rightUpperLeg",#"rightLowerLeg", "leftLowerLeg",#"leftFoot", "rightLowerLeg",#"rightFoot", "hips",#"spine", "spine",#"chest", "chest",#"upperChest" 9 optional "chest",#"neck", "neck",#"head", "chest",#"leftShoulder", # <-- upper.. "chest",#"rightShoulder", "leftShoulder",#"leftUpperArm", "rightShoulder",#"rightUpperArm", "leftUpperArm",#"leftLowerArm", "rightUpperArm",#"rightLowerArm", "leftLowerArm",#"leftHand", "rightLowerArm",#"rightHand", "leftFoot",#"leftToes", "rightFoot",#"rightToes", "head",#"leftEye", "head",#"rightEye", "head",#"jaw", "leftHand",#"leftThumbProximal", "leftThumbProximal",#"leftThumbIntermediate", "leftThumbIntermediate",#"leftThumbDistal", "leftHand",#"leftIndexProximal", "leftIndexProximal",#"leftIndexIntermediate", "leftIndexIntermediate",#"leftIndexDistal", "leftHand",#"leftMiddleProximal", "leftMiddleProximal",#"leftMiddleIntermediate", "leftMiddleIntermediate",#"leftMiddleDistal", "leftHand",#"leftRingProximal", "leftRingProximal",#"leftRingIntermediate", "leftRingIntermediate",#"leftRingDistal", "leftHand",#"leftLittleProximal", "leftLittleProximal",#"leftLittleIntermediate", "leftLittleIntermediate",#"leftLittleDistal", "rightHand",#"rightThumbProximal", "rightThumbProximal",#"rightThumbIntermediate", "rightThumbIntermediate",#"rightThumbDistal", "rightHand",#"rightIndexProximal", "rightIndexProximal",#"rightIndexIntermediate", "rightIndexIntermediate",#"rightIndexDistal", "rightHand",#"rightMiddleProximal", "rightMiddleProximal",#"rightMiddleIntermediate", "rightMiddleIntermediate",#"rightMiddleDistal", "rightHand",#"rightRingProximal", "rightRingProximal",#"rightRingIntermediate", "rightRingIntermediate",#"rightRingDistal", "rightHand",#"rightLittleProximal", "rightLittleProximal",#"rightLittleIntermediate", "rightLittleIntermediate",#"rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(humanoidBoneParentList)): humanoidBoneParentList[i] = humanoidBoneParentList[i].lower() ###### reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## meta 取得 a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object print(vv) meta = vv ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.get_selection() #sk = rig.get_preview_mesh() #k = sk.skeleton #print(k) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] for e in reversed(h_mod.get_elements()): if (e.type != unreal.RigElementType.BONE): h_mod.remove_element(e) name_to_control = {"dummy_for_table" : None} gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2]) for e in h_mod.get_elements(): print(e.name) if (e.type != unreal.RigElementType.BONE): continue bone = h_mod.get_bone(e) parentName = "{}".format(bone.get_editor_property('parent_name')) #print("parent==") #print(parentName) cur_parentName = parentName + "_c" name_s = "{}".format(e.name) + "_s" name_c = "{}".format(e.name) + "_c" space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL) control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[0.1, 0.1, 1.0, 1.0], ) h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e)) cc = h_mod.get_control(control) cc.set_editor_property('gizmo_transform', gizmo_trans) #cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR) h_mod.set_control(cc) name_to_control[name_c] = cc c = None try: i = list(name_to_control.keys()).index(cur_parentName) except: i = -1 if (i >= 0): c = name_to_control[cur_parentName] if (cc != None): if ("{}".format(e.name) in meta.humanoid_bone_table.values() ): cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0)) h_mod.set_control(cc) else: cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0)) h_mod.set_control(cc) c = rig.controller g = c.get_graph() n = g.get_nodes() # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) if (collectionItem_forBone != None): items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) for bone_h in meta.humanoid_bone_table: bone_m = meta.humanoid_bone_table[bone_h] try: i = humanoidBoneList.index(bone_h.lower()) except: i = -1 if (i >= 0): tmp = '(Type=Bone,Name=' tmp += "{}".format(bone_m).lower() tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) for e in h_mod.get_elements(): print(e.name) if (e.type == unreal.RigElementType.CONTROL): tmp = '(Type=Control,Name=' tmp += "{}".format(e.name) tmp += ')' c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
import unreal @unreal.uclass() class UnrealGlobalEditorUtilityBase(unreal.GlobalEditorUtilityBase): pass @unreal.uclass() class UnrealEditorUtilityLibrary(unreal.EditorUtilityLibrary): pass @unreal.uclass() class UnrealEditorAssetLibrary(unreal.EditorAssetLibrary): pass @unreal.uclass() class UnrealSystemLibrary(unreal.SystemLibrary): pass @unreal.uclass() class UnrealStringLibrary(unreal.StringLibrary): pass @unreal.uclass() class UnrealEditorSkeletalMeshLibrary(unreal.EditorSkeletalMeshLibrary): pass @unreal.uclass() class UnrealEditorStaticMeshLibrary(unreal.EditorStaticMeshLibrary): pass
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. import os import unreal # Required imports from deadline.unreal_submitter.submitter import ( UnrealRenderOpenJobSubmitter, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job import ( RenderUnrealOpenJob, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_step import ( RenderUnrealOpenJobStep, UnrealOpenJobStepParameterDefinition, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_environment import ( LaunchEditorUnrealOpenJobEnvironment, ) from deadline.unreal_logger import get_logger logger = get_logger() # Add default location of predefined YAML templates to env to allow OpenJob entities # load them without declaring full path to templates if "OPENJD_TEMPLATES_DIRECTORY" not in os.environ: os.environ["OPENJD_TEMPLATES_DIRECTORY"] = ( f"{os.path.dirname(os.path.dirname(__file__))}" f"/project/" ) def main(): # Create Submitter for Render OpenJobs in silent mode (without UI notifications) render_job_submitter = UnrealRenderOpenJobSubmitter(silent_mode=True) # Get jobs from Render Queue or you can create your own queue = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem).get_queue() # From each MRQ job create Render Unreal OpenJob for job in queue.get_jobs(): default_render_job = RenderUnrealOpenJob( # Set single Render step steps=[ RenderUnrealOpenJobStep( extra_parameters=[ # Override ChunkSize parameter value UnrealOpenJobStepParameterDefinition("ChunkSize", "INT", [10]) ] ) ], # Set single Launch UE Environment environments=[LaunchEditorUnrealOpenJobEnvironment()], # Set MRQ Job to retrieve render data and OpenJob overrides from mrq_job=job, ) # Add Render Unreal OpenJob to submission queue render_job_submitter.add_job(default_render_job) # Sumit jobs and log their IDs submitted_job_ids = render_job_submitter.submit_jobs() for job_id in submitted_job_ids: logger.info(f"Job submitted: {job_id}") if __name__ == "__main__": main()
# coding:utf-8 # source ref: # https://github.com/project/.py # TODO: https://github.com/project/-Virtual-Film-Project/project/.26/project/.py import unreal import os JSON_FILE_NAME = "filelist.json" @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass @unreal.uclass() class GetEditorUtility(unreal.GlobalEditorUtilityBase): pass @unreal.uclass() class GetEditorLevelLibrary(unreal.EditorLevelLibrary): pass @unreal.uclass() class GetEditorFilterLibrary(unreal.EditorFilterLibrary): pass # --------------------------------------------------------------------------------------------------------- # def create_directory(path=''): editorAssetLib = GetEditorAssetLibrary() return editorAssetLib.make_directory(directory_path=path) # --------------------------------------------------------------------------------------------------------- # def directory_exists(path=''): editorAssetLib = GetEditorAssetLibrary() return editorAssetLib.does_directory_exist(directory_path=path) # --------------------------------------------------------------------------------------------------------- # def build_import_task(filename='', destination_path='', options=None): task = unreal.AssetImportTask() task.set_editor_property('automated', True) task.set_editor_property('destination_name', '') task.set_editor_property('destination_path', destination_path) task.set_editor_property('filename', filename) task.set_editor_property('replace_existing', True) task.set_editor_property('save', True) task.set_editor_property('options', options) filename = os.path.basename(os.path.splitext(filename)[0]) return task, filename # --------------------------------------------------------------------------------------------------------- # def build_static_mesh_import_options(scale=1.0): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_mesh', True) options.set_editor_property('import_textures', True) options.set_editor_property('import_materials', True) options.set_editor_property('import_as_skeletal', False) # Static Mesh # unreal.FbxMeshImportData options.static_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_uniform_scale', scale) # unreal.FbxStaticMeshImportData options.static_mesh_import_data.set_editor_property('combine_meshes', False) # !!!!!!!!!!!!! options.static_mesh_import_data.set_editor_property('generate_lightmap_u_vs', True) options.static_mesh_import_data.set_editor_property('auto_generate_collision', True) return options # --------------------------------------------------------------------------------------------------------- # def build_skeletal_mesh_import_options(scale=1.0): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_mesh', True) options.set_editor_property('import_textures', True) options.set_editor_property('import_materials', True) options.set_editor_property('import_as_skeletal', True) # Skeletal Mesh # unreal.FbxMeshImportData options.skeletal_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.skeletal_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.skeletal_mesh_import_data.set_editor_property('import_uniform_scale', scale) # unreal.FbxSkeletalMeshImportData options.skeletal_mesh_import_data.set_editor_property('import_morph_targets', True) options.skeletal_mesh_import_data.set_editor_property('update_skeleton_reference_pose', False) return options # --------------------------------------------------------------------------------------------------------- # # skeleton_path: str : Skeleton asset path of the skeleton that will be used to bind the animation def build_animation_import_options(skeleton_path='',scale=1.0): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_animations', True) options.skeleton = unreal.load_asset(skeleton_path) # unreal.FbxMeshImportData options.anim_sequence_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.anim_sequence_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.anim_sequence_import_data.set_editor_property('import_uniform_scale', scale) # unreal.FbxAnimSequenceImportData options.anim_sequence_import_data.set_editor_property('animation_length', unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME) options.anim_sequence_import_data.set_editor_property('remove_redundant_keys', False) return options # --------------------------------------------------------------------------------------------------------- # def execute_import_task(task): # 只接受列表传参 tasks = [task] unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks) # 返回所有的单独的asset 路径 # imported_asset_paths = [] # for path in task.get_editor_property('imported_object_paths'): # imported_asset_paths.append(path) # return imported_asset_paths # --------------------------------------------------------------------------------------------------------- # def import_fbx_asset(fbx_files=[], dest_path="/project/", import_type="static_mesh", assemble_scale_factor=1): # -------------------------------------------- # 判断类型,生成option # 尺寸缩放在这个时候(导入之前)进行 if import_type=="static_mesh": option = build_static_mesh_import_options(assemble_scale_factor) if import_type=="misc": option = None # -------------------------------------------- # 一个FBX对应一个task, 一个FBX可以包含若干个asset # 一个FBX对应一个actor,一个actor包含若干个asset # -------------------------------------------- # opertion start, with slow task !!! for idx, fbx in enumerate(fbx_files): # -------------------------------------------- # create folder # dest_path = dest_path + str("_%d" % (idx+1)) if not directory_exists(dest_path): create_directory(dest_path) # -------------------------------------------- # 对每个fbx新建一个task,导入到content browser fbx_task, spawn_actor_name = build_import_task(fbx, dest_path, option) execute_import_task(fbx_task) print("CB imported") editor_asset_lib = GetEditorAssetLibrary() editor_filter_lib = GetEditorFilterLibrary() asset_paths = editor_asset_lib.list_assets(dest_path) print(asset_paths) # -------------------------------------------- # 针对导入的fbx里每个单独的asset,spawn(导入的时候不要combine mesh!!!,build option里设置) # 做了一个过滤,只会spawn static mesh editor_level_lib = GetEditorLevelLibrary() actor_in_asset_list = [] for asset in asset_paths: loaded_asset = unreal.load_asset(asset) temp_list = [] temp_list.append(loaded_asset) temp_list = editor_filter_lib.by_class(temp_list, unreal.StaticMesh.static_class()) if not temp_list: continue actor = editor_level_lib.spawn_actor_from_object(loaded_asset, (0,0,0), (0,0,0)) actor_in_asset_list.append(actor) print("assets spawned") ''' # -------------------------------------------- # join to a new actor join_options = unreal.EditorScriptingJoinStaticMeshActorsOptions() join_options.new_actor_label = spawn_actor_name join_options.destroy_source_actors = True join_options.rename_components_from_source = True new_actor = editor_level_lib.join_static_mesh_actors(actor_in_asset_list, join_options) print("actors joined") # -------------------------------------------- # join to a new group #new_actor.set_folder_path("new_group") #print("group created") ''' import argparse # Initialize parser parser = argparse.ArgumentParser() # Adding optional argument parser.add_argument("-json", "--JsonFileName", help = "Json file name") # Read arguments from command line args = parser.parse_args() if args.JsonFileName: print(args.JsonFileName) import_fbx_asset(["/project/.fbx", "/project/.fbx", "/project/.fbx"])
import unreal import argparse import DTUControlRigHelpers import importlib importlib.reload(DTUControlRigHelpers) # Info about Python with IKRigs here: # https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-rigs-in-unreal-engine/ # https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-retargeter-assets-in-unreal-engine/ # Figure out the forward axis for a child bone def get_bone_forward_axis(child_bone_relative_pos): forward = "X+" if abs(child_bone_relative_pos.x) > max(abs(child_bone_relative_pos.y), abs(child_bone_relative_pos.z)): forward = 'X' + forward[1] if abs(child_bone_relative_pos.y) > max(abs(child_bone_relative_pos.x), abs(child_bone_relative_pos.z)): forward = 'Y' + forward[1] if abs(child_bone_relative_pos.z) > max(abs(child_bone_relative_pos.x), abs(child_bone_relative_pos.y)): forward = 'Z' + forward[1] if forward[0] == 'X' and child_bone_relative_pos.x > 0: forward = forward[0] + '+' if forward[0] == 'X' and child_bone_relative_pos.x < 0: forward = forward[0] + '-' if forward[0] == 'Y' and child_bone_relative_pos.y > 0: forward = forward[0] + '+' if forward[0] == 'Y' and child_bone_relative_pos.y < 0: forward = forward[0] + '-' if forward[0] == 'Z' and child_bone_relative_pos.z > 0: forward = forward[0] + '+' if forward[0] == 'Z' and child_bone_relative_pos.z < 0: forward = forward[0] + '-' return forward parser = argparse.ArgumentParser(description = 'Creates an IKRetargetter between two control rigs') parser.add_argument('--sourceIKRig', help='Source IKRig to Use') parser.add_argument('--targetIKRig', help='Target IKRig to Use') args = parser.parse_args() # Retageter name is Source_to_Target asset_tools = unreal.AssetToolsHelpers.get_asset_tools() source_rig_name = args.sourceIKRig.split('.')[-1] target_rig_name = args.targetIKRig.split('.')[-1] # Check if it exists package_path = args.targetIKRig.rsplit('/', 1)[0] + '/' asset_name = source_rig_name.replace('_IKRig', '') + '_to_' + target_rig_name.replace('_IKRig', '') + '_IKRetargeter' rtg = skel_mesh = unreal.load_asset(name = package_path + asset_name ) # If not, create a new one if not rtg: rtg = asset_tools.create_asset( asset_name=asset_name, package_path=package_path, asset_class=unreal.IKRetargeter, factory=unreal.IKRetargetFactory()) # Get the IK Retargeter controller rtg_controller = unreal.IKRetargeterController.get_controller(rtg) # Load the Source and Target IK Rigs source_ik_rig = unreal.load_asset(name = args.sourceIKRig) target_ik_rig = unreal.load_asset(name = args.targetIKRig) source_ikr_controller = unreal.IKRigController.get_controller(source_ik_rig) target_ikr_controller = unreal.IKRigController.get_controller(target_ik_rig) # Load the Source and Target Skeletal Meshes source_ik_mesh = unreal.IKRigController.get_controller(source_ik_rig).get_skeletal_mesh() target_ik_mesh = unreal.IKRigController.get_controller(target_ik_rig).get_skeletal_mesh() # Assign the Source and Target IK Rigs rtg_controller.set_ik_rig(unreal.RetargetSourceOrTarget.SOURCE, source_ik_rig) rtg_controller.set_ik_rig(unreal.RetargetSourceOrTarget.TARGET, target_ik_rig) rtg_controller.auto_map_chains(unreal.AutoMapChainType.EXACT, True) # Get the root rotation source_asset_import_data = source_ik_mesh.get_editor_property('asset_import_data') target_asset_import_data = target_ik_mesh.get_editor_property('asset_import_data') source_force_front_x = source_asset_import_data.get_editor_property('force_front_x_axis') target_force_front_x = target_asset_import_data.get_editor_property('force_front_x_axis') # Rotate the root if needed so the character faces forward if source_force_front_x == False and target_force_front_x == True: rotation_offset = unreal.Rotator() rotation_offset.yaw = 90 rtg_controller.set_rotation_offset_for_retarget_pose_bone("root", rotation_offset.quaternion(), unreal.RetargetSourceOrTarget.TARGET) # Setup the root translation root_chain_settings = rtg_controller.get_retarget_chain_settings('Root') root_chain_fk_settings = root_chain_settings.get_editor_property('fk') root_chain_fk_settings.set_editor_property('translation_mode', unreal.RetargetTranslationMode.ABSOLUTE) rtg_controller.set_retarget_chain_settings('Root', root_chain_settings) # Set the root Settings (not the root chain settings) root_settings = rtg_controller.get_root_settings() root_settings.blend_to_source = 1.0 # Fixes a hitch in the MM_Run_Fwd conversion rtg_controller.set_root_settings(root_settings) # Get the bone limit data bone_limits = DTUControlRigHelpers.get_bone_limits_from_skeletalmesh(target_ik_mesh) # Align chains source_skeleton = source_ik_mesh.get_editor_property('skeleton') target_skeleton = target_ik_mesh.get_editor_property('skeleton') source_reference_pose = source_skeleton.get_reference_pose() target_reference_pose = target_skeleton.get_reference_pose() def single_axis_bend(target_bone, source_bone): axis_x, axis_y, axis_z = bone_limits[str(target_bone)].get_preferred_angle() source_bone_transform = source_reference_pose.get_ref_bone_pose(source_bone, space=unreal.AnimPoseSpaces.LOCAL) source_bone_rotation = source_bone_transform.get_editor_property('rotation').rotator() source_angle = abs(max(source_bone_rotation.get_editor_property("pitch"), source_bone_rotation.get_editor_property("yaw"), source_bone_rotation.get_editor_property("roll"), key=lambda x: abs(x))) new_rot = unreal.Rotator() if axis_x > 0.01: new_rot.set_editor_property('roll', source_angle) #X if axis_x < -0.01: new_rot.set_editor_property('roll', source_angle * -1.0) #X if axis_y > 0.01: new_rot.set_editor_property('pitch', source_angle) #Y if axis_y < -0.01: new_rot.set_editor_property('pitch', source_angle * -1.0) #Y if axis_z > 0.01: new_rot.set_editor_property('yaw', source_angle) #Z if axis_z < -0.01: new_rot.set_editor_property('yaw', source_angle * -1.0) #Z rtg_controller.set_rotation_offset_for_retarget_pose_bone(target_bone, new_rot.quaternion(), unreal.RetargetSourceOrTarget.TARGET) def dual_axis_target_bend(target_bone, source_bone, target_end_bone, source_end_bone): source_bone_transform = source_reference_pose.get_ref_bone_pose(source_bone, space=unreal.AnimPoseSpaces.WORLD) source_end_bone_transform = source_reference_pose.get_ref_bone_pose(source_end_bone, space=unreal.AnimPoseSpaces.WORLD) source_relative_position = source_end_bone_transform.get_editor_property('translation') - source_bone_transform.get_editor_property('translation') # Fix the axis if the target character is facing right if source_force_front_x == False and target_force_front_x == True: new_relative_position = unreal.Vector() new_relative_position.x = source_relative_position.y * -1.0 new_relative_position.y = source_relative_position.x * -1.0 new_relative_position.z = source_relative_position.z source_relative_position = new_relative_position target_bone_transform_world = target_reference_pose.get_ref_bone_pose(target_bone, space=unreal.AnimPoseSpaces.WORLD) target_end_bone_transform_world = target_reference_pose.get_ref_bone_pose(target_end_bone, space=unreal.AnimPoseSpaces.WORLD) target_relative_position = target_end_bone_transform_world.get_editor_property('translation') - target_bone_transform_world.get_editor_property('translation') target_position = target_bone_transform_world.get_editor_property('translation') + source_relative_position #- (target_relative_position - source_relative_position) new_pos = target_bone_transform_world.inverse_transform_location(target_position) target_child_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_bone, target_end_bone) target_child_bone_transform_local = target_reference_pose.get_ref_bone_pose(target_child_bone, space=unreal.AnimPoseSpaces.LOCAL) forward_direction = get_bone_forward_axis(target_child_bone_transform_local.get_editor_property('translation')) # Make a rotator to point the joints at the new new_rot = unreal.Rotator() if forward_direction[0] == 'X': y_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.x) * -1.0 z_rot = unreal.MathLibrary.deg_atan(new_pos.y / new_pos.x) new_rot.set_editor_property('pitch', y_rot) #Y new_rot.set_editor_property('yaw', z_rot) #Z if forward_direction == 'Y+': x_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.y) #* -1.0 z_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.y) * -1.0 new_rot.set_editor_property('yaw', z_rot) #Z new_rot.set_editor_property('roll', x_rot) #X if forward_direction == 'Y-': x_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.y) * -1.0 z_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.y) * -1.0 new_rot.set_editor_property('yaw', z_rot) #Z new_rot.set_editor_property('roll', x_rot) #X if forward_direction[0] == 'Z': x_rot = unreal.MathLibrary.deg_atan(new_pos.y / new_pos.z) y_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.z) * -1.0 new_rot.set_editor_property('roll', x_rot) #X new_rot.set_editor_property('pitch', y_rot) #Y # Set the new rotation on the joint rtg_controller.set_rotation_offset_for_retarget_pose_bone(target_bone, new_rot.quaternion(), unreal.RetargetSourceOrTarget.TARGET) # Single Axis Bends (Elbow, Knee, etc) for chain in ['LeftArm', 'RightArm', 'LeftLeg', 'RightLeg']: source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain) source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain) target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain) target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain) target_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone) source_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone) single_axis_bend(target_bone, source_bone) # Dual Axis Bends (Elbow, Knee, etc) for chain in ['LeftArm', 'RightArm', 'LeftLeg', 'RightLeg']: source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain) source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain) target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain) target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain) # Get the joint (elbow, knee) target_joint_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone) source_joint_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone) # Got one deeper (hand, foot) target_end_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_joint_bone, target_end_bone) source_end_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_joint_bone, source_end_bone) dual_axis_target_bend(target_start_bone, source_start_bone, target_end_bone, source_end_bone) # Single Axis Chains (fingers) for chain in ['RightThumb', 'RightIndex', 'RightMiddle', 'RightRing', 'RightPinky', 'LeftThumb', 'LeftIndex', 'LeftMiddle', 'LeftRing', 'LeftPinky']: source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain) source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain) target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain) target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain) while target_start_bone and source_start_bone and target_start_bone != target_end_bone and source_start_bone != source_end_bone: target_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone) source_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone) single_axis_bend(target_bone, source_bone) target_start_bone = target_bone source_start_bone = source_bone
# Copyright (c) <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 from os.path import dirname, basename, isfile, join import glob import importlib import traceback import sys 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 Blueprint 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 Blueprint Library #################### """) try: reload(mod) except: importlib.reload(mod) # try: # unreal.reload(mod) # except: # unreal.log("{} is not Unreal Generated Class".format(m)) 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("""@ #################### """)
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() #print(args.vrm) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", "leftThumbIntermediate", "leftThumbDistal", "leftIndexProximal", "leftIndexIntermediate", "leftIndexDistal", "leftMiddleProximal", "leftMiddleIntermediate", "leftMiddleDistal", "leftRingProximal", "leftRingIntermediate", "leftRingDistal", "leftLittleProximal", "leftLittleIntermediate", "leftLittleDistal", "rightThumbProximal", "rightThumbIntermediate", "rightThumbDistal", "rightIndexProximal", "rightIndexIntermediate", "rightIndexDistal", "rightMiddleProximal", "rightMiddleIntermediate", "rightMiddleDistal", "rightRingProximal", "rightRingIntermediate", "rightRingDistal", "rightLittleProximal", "rightLittleIntermediate", "rightLittleDistal", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() ###### rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() #print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller()#rig.controller else: c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() # print(a) # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items' or node.get_node_title() == 'Collection from Items'): #print(node.get_node_title()) #node = unreal.RigUnit_CollectionItems.cast(node) pin = node.find_pin('Items') print(pin.get_array_size()) print(pin.get_default_value()) if (pin.get_array_size() < 40): continue if 'Type=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() if (vv == None): for aa in a: if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object #print(vv) meta = vv # controller array if (collectionItem_forControl == None): collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forControl = collectionItem_forControl.find_pin('Items') c.clear_array_pin(items_forControl.get_pin_path()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] print(items_forControl) print(items_forBone) humanoidBoneTable = {"dummy" : "dummy"} humanoidBoneTable.clear() for h in meta.humanoid_bone_table: bone_h = "{}".format(h).lower() bone_m = "{}".format(meta.humanoid_bone_table[h]).lower() try: i = list(humanoidBoneTable.values()).index(bone_m) except: i = -1 if (bone_h!="" and bone_m!="" and i==-1): humanoidBoneTable[bone_h] = bone_m for bone_h in humanoidBoneList: bone_m = humanoidBoneTable.get(bone_h, None) if bone_m == None: continue #for bone_h in meta.humanoid_bone_table: # bone_m = meta.humanoid_bone_table[bone_h] # try: # i = humanoidBoneList.index(bone_h.lower()) # except: # i = -1 # if (i >= 0): if (True): tmp = '(Type=Bone,Name=' #tmp += "{}".format(bone_m).lower() tmp += bone_m tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) #print(bone_m) tmp = '(Type=Control,Name=' #tmp += "{}".format(bone_h).lower() + '_c' tmp += bone_h + '_c' tmp += ')' #print(c) c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # if (e.type == unreal.RigElementType.CONTROL): # tmp = '(Type=Control,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
from pathlib import Path from ue_importer_gui import USDAnimImportDialog, USDStageHandler import unittest from pxr import Usd, UsdGeom, Sdf import unreal import sys ELL = unreal.EditorLevelLibrary() EAL = unreal.EditorAssetLibrary() class TestUSDStageHandler(unittest.TestCase): def setUp(self): # Directory containing test USD files self.test_files_dir = Path(__file__).resolve().parent / "test_files" def test_open_stage_valid_file(self): file_path = str(self.test_files_dir / "test_shapes.usd") USDStageHandler.open_stage(file_path) self.assertIsNotNone(USDStageHandler.stage) self.assertIsInstance(USDStageHandler.stage, Usd.Stage) def test_open_stage_invalid_file_extension(self): file_path = str(self.test_files_dir / "invalid.txt") with self.assertRaises(ValueError): USDStageHandler.open_stage(file_path) def test_open_stage_nonexistent_file(self): file_path = str(self.test_files_dir / "nonexistent.usd") with self.assertRaises(RuntimeError): USDStageHandler.open_stage(file_path) class TestUSDAnimImportDialog(unittest.TestCase): def setUp(self): self.dialog = USDAnimImportDialog() self.file_path = str(Path(__file__).resolve().parent / "test_files" / "test_shapes.usd") self.stage = Usd.Stage.Open(self.file_path) def reload_prims_list(self): # set up so they are different self.dialog.prim_type_combo.setCurrentIndex(0) self.dialog.export_type_combo.setCurrentIndex(1) self.dialog.reload_prims_list() # assert that they have both been set to the same index self.assertEqual(self.dialog.prim_type_combo.currentIndex(), self.dialog.export_type_combo.currentIndex()) def test_usd_prim_extraction(self): mesh_type = "Mesh" expected = [Sdf.Path('/pCube1'), Sdf.Path('/pCone1'), Sdf.Path('/pTorus1')] expected2 = [Sdf.Path('/pCube1'), Sdf.Path('/pCone1'), Sdf.Path('/pTorus1'), Sdf.Path('/pCylinder1')] actual1 = self.dialog.usd_prim_extraction(self.stage, mesh_type, True) actual2 = self.dialog.usd_prim_extraction(self.stage, mesh_type, False) self.assertEqual(expected, actual1) self.assertNotEqual(expected, actual2) self.assertEqual(expected2, actual2) def test_usd_prim_extraction_2(self): stairs_file = Path(__file__).resolve().parent / "test_files" / "stairs_objects.usd" stage = Usd.Stage.Open(str(stairs_file)) mesh_type = "Camera" expected = [Sdf.Path('/camera1')] actual = self.dialog.usd_prim_extraction(stage, mesh_type, False) self.assertEqual(expected, actual) def test_populate_prims_list(self): prims = [Sdf.Path('/pCube1'), Sdf.Path('/pCone1'), Sdf.Path('/pTorus1')] self.dialog.prim_type_combo.setCurrentText("Mesh") self.dialog.is_animated_checkbox.setChecked(True) self.dialog.populate_prims_list(self.file_path) expected_paths = ['/pCube1', '/pCone1', '/pTorus1'] for index in range(self.dialog.prim_list_widget.count()): item = self.dialog.prim_list_widget.item(index) self.assertIsNotNone(item) self.assertIn(str(item.text()), expected_paths) expected_dict = {"/pCube1": Sdf.Path('/pCube1'), "/pCone1": Sdf.Path('/pCone1'), "/pTorus1": Sdf.Path('/pTorus1')} self.assertEqual(self.dialog.prim_strings, expected_dict) self.assertEqual(self.dialog.prim_list_widget.count(), len(prims)) self.assertEqual(len(self.dialog.prim_strings), len(prims)) def test_toggle_export_dir_edit(self): self.dialog.use_default_checkbox.setChecked(True) self.dialog.toggle_export_dir_edit() self.assertFalse(self.dialog.export_dir_edit.isEnabled()) self.assertFalse(self.dialog.select_export_dir_button.isEnabled()) self.dialog.use_default_checkbox.setChecked(False) self.dialog.toggle_export_dir_edit() self.assertTrue(self.dialog.export_dir_edit.isEnabled()) self.assertTrue(self.dialog.select_export_dir_button.isEnabled()) def test_toggle_individual_export(self): self.dialog.individual_checkbox.setChecked(True) self.dialog.toggle_individual_export() self.assertFalse(self.dialog.file_name_edit.isEnabled()) self.dialog.individual_checkbox.setChecked(False) self.dialog.toggle_individual_export() self.assertTrue(self.dialog.file_name_edit.isEnabled()) def test_create_temp_stage(self): temp_stage = self.dialog.create_temp_stage(self.stage) self.assertIsInstance(temp_stage, Usd.Stage) self.assertEqual(temp_stage.GetStartTimeCode(), self.stage.GetStartTimeCode()) self.assertEqual(temp_stage.GetEndTimeCode(), self.stage.GetEndTimeCode()) self.assertEqual(temp_stage.GetTimeCodesPerSecond(), self.stage.GetTimeCodesPerSecond()) self.assertEqual(temp_stage.GetFramesPerSecond(), self.stage.GetFramesPerSecond()) def test_add_prim_to_stage(self): temp_stage = self.dialog.create_temp_stage(self.stage) export_type = "Mesh" prim_path = Sdf.Path('/pCube1') temp_stage = self.dialog.add_prim_to_stage(self.stage, temp_stage, self.file_path, export_type, prim_path) self.assertIsInstance(temp_stage, Usd.Stage) added_prim = temp_stage.GetPrimAtPath(Sdf.Path("/project/")) self.assertIsNotNone(added_prim) self.assertTrue(added_prim.IsA(UsdGeom.Mesh)) def test_export_stage(self): temp_stage = self.dialog.create_temp_stage(self.stage) export_type = "Mesh" prim_path = Sdf.Path('/pCube1') file_name = "test_export" temp_stage = self.dialog.add_prim_to_stage(self.stage, temp_stage, self.file_path, export_type, prim_path) target_directory = Path(__file__).resolve().parent / "test_exports" self.dialog.export_stage(temp_stage, target_directory, file_name) expected_export_path = target_directory / (file_name + ".usda") self.assertTrue(expected_export_path.exists()) def test_create_usd_stage_actor(self): file_path = Path(__file__).resolve().parent / "test_files" / "test_cube.usd" prim_name = "pCube1" usd_stage_actor = self.dialog.create_usd_stage_actor(str(file_path), prim_name) self.assertEqual(usd_stage_actor.get_actor_label(), "pCube1_usd") existing_actors = ELL.get_all_level_actors() usd_actors = [actor for actor in existing_actors if isinstance(actor, unreal.UsdStageActor)] self.assertIn(usd_stage_actor, usd_actors) if __name__ == "__main__": suite = unittest.TestSuite() suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestUSDStageHandler)) suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestUSDAnimImportDialog)) result = unittest.TextTestRunner(stream=sys.stdout, buffer=True).run(suite)
# Copyright Epic Games, Inc. All Rights Reserved """ This script handles processing jobs and shots in the current loaded queue """ import unreal import os from .utils import ( movie_pipeline_queue, execute_render, setup_remote_render_jobs, update_render_output ) def setup_render_parser(subparser): """ This method adds a custom execution function and args to a render subparser :param subparser: Subparser for processing custom sequences """ # Function to process arguments subparser.set_defaults(func=_process_args) def render_jobs( is_remote=False, is_cmdline=False, executor_instance=None, remote_batch_name=None, remote_job_preset=None, output_dir_override=None, output_filename_override=None ): """ This renders the current state of the queue :param bool is_remote: Is this a remote render :param bool is_cmdline: Is this a commandline render :param executor_instance: Movie Pipeline Executor instance :param str remote_batch_name: Batch name for remote renders :param str remote_job_preset: Remote render job preset :param str output_dir_override: Movie Pipeline output directory override :param str output_filename_override: Movie Pipeline filename format override :return: MRQ executor """ if not movie_pipeline_queue.get_jobs(): # Make sure we have jobs in the queue to work with raise RuntimeError("There are no jobs in the queue!!") # Update the job for job in movie_pipeline_queue.get_jobs(): config = job.get_configuration() # Override texture streaming method texture_streaming_override = os.environ.get("texture_streaming_override") if texture_streaming_override: game_setting = config.find_setting_by_class( unreal.MoviePipelineGameOverrideSetting ) if texture_streaming_override == "Disabled": game_setting.texture_streaming = unreal.MoviePipelineTextureStreamingMethod.DISABLED elif texture_streaming_override == "FullyLoad": game_setting.texture_streaming = unreal.MoviePipelineTextureStreamingMethod.FULLY_LOAD elif texture_streaming_override == "None": game_setting.texture_streaming = unreal.MoviePipelineTextureStreamingMethod.NONE # get override output override_output = os.environ.get("override_output") if override_output != None: override_output = int(override_output) # update output settings update_render_output( job, output_dir=output_dir_override, output_filename=output_filename_override, override_output=override_output, ) # Get the job output settings output_setting = config.find_setting_by_class( unreal.MoviePipelineOutputSetting ) # Allow flushing flies to disk per shot. # Required for the OnIndividualShotFinishedCallback to get called. output_setting.flush_disk_writes_per_shot = True # Workaround to make the config dirty so that the overrides are actually accounted for. # Modifying directly the various settings class does not make the config dirty # and when rendering starts, the config is reset to the default saved one. job.set_configuration(config) # set job user_data user_data = os.environ.get("MRQ_user_data", "{}") job.user_data = user_data if is_remote: setup_remote_render_jobs( remote_batch_name, remote_job_preset, movie_pipeline_queue.get_jobs(), ) try: # Execute the render. # This will execute the render based on whether its remote or local executor = execute_render( is_remote, executor_instance=executor_instance, is_cmdline=is_cmdline, ) except Exception as err: unreal.log_error( f"An error occurred executing the render.\n\tError: {err}" ) raise return executor def _process_args(args): """ Function to process the arguments for the sequence subcommand :param args: Parsed Arguments from parser """ return render_jobs( is_remote=args.remote, is_cmdline=args.cmdline, remote_batch_name=args.batch_name, remote_job_preset=args.deadline_job_preset, output_dir_override=args.output_override, output_filename_override=args.filename_override )
# -*- coding: utf-8 -*- import unreal import os from Utilities.Utils import Singleton from Utilities.Utils import cast import Utilities import QueryTools import re import types import collections from .import Utils global _r COLUMN_COUNT = 2 class DetailData(object): def __init__(self): self.filter_str = "" self.filteredIndexToIndex = [] self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)] self.attributes = None self.filtered_attributes = None self.plains = [] self.riches = [] self.selected = set() def check_line_id(self, line_id, column_count): from_line = line_id * column_count to_line = (line_id + 1) * column_count assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)" if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains): return True else: unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}") return False def get_plain(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.plains[line_id * 2 : line_id * 2 + 2] def get_rich(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.riches[line_id * 2: line_id * 2 + 2] class ObjectDetailViewer(metaclass=Singleton): def __init__(self, jsonPath): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_checkbox_single_mode = "CheckBoxSingleMode" self.ui_checkbox_compare_mode = "CheckBoxCompareMode" self.ui_left_group = "LeftDetailGroup" self.ui_right_group = "RightDetailGroup" self.ui_button_refresh = "RefreshCompareButton" self.ui_detailListLeft = "ListViewLeft" self.ui_detailListRight = "ListViewRight" self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft' self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight' # self.ui_headRowLeft = "HeaderRowLeft" # self.ui_headRowRight = "HeaderRowRight" self.ui_labelLeft = "LabelLeft" self.ui_labelRight = "LabelRight" self.ui_info_output = "InfoOutput" self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode self.ui_rightListGroup = "RightListGroup" self.ui_refreshButtonGroup = "RefreshButtonGroup" self.reset() def on_close(self): self.reset() def on_map_changed(self, map_change_type_str): # remove the reference, avoid memory leaking when load another map. if map_change_type_str == "TearDownWorld": self.reset(bResetParameter=False) else: pass # skip: LoadMap, SaveMap, NewMap def reset(self, bResetParameter=True): if bResetParameter: self.showBuiltin = True self.showOther = True self.showProperties = True self.showEditorProperties = True self.showParamFunction = True self.compareMode = False self.left = None self.right = None self.leftSearchText = "" self.rightSearchText = "" self.left_rich = None self.left_plain = None self.var = None self.diff_count = 0 self.clear_ui_info() def clear_ui_info(self): for text_ui in [self.ui_info_output, self.ui_labelLeft, self.ui_labelRight]: self.data.set_text(text_ui, "") self.data.set_list_view_multi_column_items(self.ui_detailListLeft, [], 2) self.data.set_list_view_multi_column_items(self.ui_detailListRight, [], 2) for ui_breadcrumb in [self.ui_hisObjsBreadcrumbRight, self.ui_hisObjsBreadcrumbLeft]: crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) for i in range(crumbCount): self.data.pop_breadcrumb_string(ui_breadcrumb) def update_log_text(self, bRight): bShowRight = self.compareMode result = "" for side_str in ["left", "right"] if bShowRight else ["left"]: bRight = side_str != "left" ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: result += "\t\t\t" result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs)) if self.compareMode: result = f"{result}\t\t\tdiff count: {self.diff_count}" self.data.set_text(self.ui_info_output, result) def get_color_by(self, attr : Utils.attr_detail): if attr.bCallable_builtin: return "DarkTurquoise".lower() if attr.bCallable_other: return "RoyalBlue".lower() if attr.bEditorProperty: return "LimeGreen".lower() if attr.bOtherProperty: return "yellow" def get_color(self, typeStr): if typeStr == "property": return 'white' if typeStr == "return_type": return 'gray' if typeStr == "param": return 'gray' def get_name_with_rich_text(self, attr:Utils.attr_detail): name_color = self.get_color_by(attr) param_color = self.get_color("param") return_type_color = self.get_color("return_type") if attr.bProperty: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: if attr.param_str: return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name , param_color, attr.param_str , name_color) else: if attr.bCallable_other: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name , return_type_color, attr.return_type_str) def get_name_with_plain_text(self, attr:Utils.attr_detail): if attr.bProperty: return "\t{}".format(attr.name) else: if attr.param_str: return "\t{}({})".format( attr.name, attr.param_str) else: if attr.bCallable_other: return "\t{}".format( attr.name) else: return "\t{}() {}".format(attr.name,attr.return_type_str) def filter(self, data:DetailData): result = [] indices = [] for i, attr in enumerate(data.attributes): if not self.showEditorProperties and attr.bEditorProperty: continue if not self.showProperties and attr.bOtherProperty: continue if not self.showParamFunction and attr.bHasParamFunction: continue if not self.showBuiltin and attr.bCallable_builtin: continue if not self.showOther and attr.bCallable_other: continue if data.filter_str: if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() : continue result.append(attr) indices.append(i) return result, indices def show_data(self, data:DetailData, ui_listView): flatten_list_items = [] flatten_list_items_plain = [] for i, attr in enumerate(data.filtered_attributes): # print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ") attr.check() assert attr.display_name, f"display name null {attr.display_name}" assert isinstance(attr.display_result, str), f"display result null {attr.display_result}" result_str = attr.display_result if len(result_str) > 200: result_str = result_str[:200] + "......" flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str]) flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str]) data.riches = flatten_list_items data.plains = flatten_list_items_plain data.selected.clear() self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2) def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property if bRight: ui_Label = self.ui_labelRight ui_listView = self.ui_detailListRight ui_breadcrumb = self.ui_hisObjsBreadcrumbRight else: ui_Label = self.ui_labelLeft ui_listView = self.ui_detailListLeft ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left data.attributes = Utils.ll(obj) data.filtered_attributes, data.filteredIndexToIndex = self.filter(data) self.show_data(data, ui_listView) # set breadcrumb if propertyName and len(propertyName) > 0: label = propertyName else: if isinstance(obj, unreal.Object): label = obj.get_name() else: try: label = obj.__str__() except TypeError: label = f"{obj}" if bPush: # push # print(f"%%% push: {propertyName}, label {label}") data.hisCrumbObjsAndNames.append((obj, propertyName)) self.data.push_breadcrumb_string(ui_breadcrumb, label, label) self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) ) crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount) else: assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount) self.update_log_text(bRight) def clear_and_query(self, obj, bRight): # first time query self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft) if not self.right: self.right = DetailData() if not self.left: self.left = DetailData() data = self.right if bRight else self.left data.hisCrumbObjsAndNames = [] #clear his-Object at first time query if bRight: assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0" else: assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0" self.query_and_push(obj, "", bPush=True, bRight= bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def update_ui_by_mode(self): self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode) self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode) bCollapsed = not self.compareMode self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed) self.data.set_collapsed(self.ui_right_group, bCollapsed) self.data.set_collapsed(self.ui_button_refresh, bCollapsed) def on_checkbox_SingleMode_Click(self, state): self.compareMode = False self.update_ui_by_mode() def on_checkbox_CompareMode_Click(self, state): self.compareMode = True self.update_ui_by_mode() def on_button_Refresh_click(self): self.apply_compare_if_needed() def on_button_SelectAsset_click(self, bRightSide): selectedAssets = Utilities.Utils.get_selected_assets() if len(selectedAssets) == 0: return self.clear_and_query(selectedAssets[0], bRightSide) def on_button_QuerySelected_click(self, bRightSide): # query component when any component was selected, otherwise actor obj = Utilities.Utils.get_selected_comp() if not obj: obj = Utilities.Utils.get_selected_actor() if obj: self.clear_and_query(obj, bRightSide) def on_drop(self, bRightSide, *args, **kwargs): if "assets" in kwargs and kwargs["assets"]: asset = unreal.load_asset(kwargs["assets"][0]) if asset: self.clear_and_query(asset, bRightSide) return if "actors" in kwargs and kwargs["actors"]: actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world()) if actor: print(actor) self.clear_and_query(actor, bRightSide) return item_count = 0 for k, v in kwargs.items(): item_count += len(v) if item_count == 0: selected_comp = Utilities.Utils.get_selected_comp() if selected_comp: self.clear_and_query(selected_comp, bRightSide) def log_r_warning(self): unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu") def on_button_Query_R_click(self, r_obj, bRightSide=False): print("on_button_Query_R_click call") if not r_obj: return self.clear_and_query(r_obj, bRightSide) def on_list_double_click_do(self, index, bRight): # print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight)) data = self.right if bRight else self.left typeBlacklist = [int, float, str, bool] #, types.NotImplementedType] real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index assert 0 <= real_index < len(data.attributes) currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] attr_name = data.attributes[real_index].name objResult, propertyName = self.try_get_object(data, currentObj, attr_name) if not objResult or objResult is currentObj: # equal return if isinstance(objResult, str) and "skip call" in objResult.lower(): return if type(objResult) in typeBlacklist: return if isinstance(objResult, collections.abc.Iterable): if type(objResult[0]) in typeBlacklist: return nextObj = objResult[0] nextPropertyName = str(propertyName) + "[0]" else: nextObj = objResult nextPropertyName = str(propertyName) self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def on_listview_DetailListRight_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=True) def on_listview_DetailListLeft_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=False) def on_breadcrumbtrail_click_do(self, item, bRight): ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb) print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames))) while len(data.hisCrumbObjsAndNames) > count: data.hisCrumbObjsAndNames.pop() nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] if not bRight: assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames" self.query_and_push(nextObj, name, bPush=False, bRight=False) self.apply_compare_if_needed() self.update_log_text(bRight=False) def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=False) def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=True) def remove_address_str(self, strIn): return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn) def apply_compare_if_needed(self): if not self.compareMode: return lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes if not lefts: lefts = [] if not rights: rights = [] leftIDs = [] rightIDs = [] for i, left_attr in enumerate(lefts): for j, right_attr in enumerate(rights): if right_attr.name == left_attr.name: if right_attr.result != left_attr.result: if isinstance(right_attr.result, unreal.Transform): if right_attr.result.is_near_equal(left_attr.result, location_tolerance=1e-20, rotation_tolerance=1e-20, scale3d_tolerance=1e-20): continue leftIDs.append(i) rightIDs.append(j) break self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs) self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs) self.diff_count = len(leftIDs) def apply_search_filter(self, text, bRight): _data = self.right if bRight else self.left _data.filter_str = text if len(text) else "" _data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data) ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft self.show_data(_data, ui_listView) self.apply_compare_if_needed() def on_searchbox_FilterLeft_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterLeft_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterRight_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def on_searchbox_FilterRight_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def apply_filter(self): _datas = [self.left, self.right] _isRight = [False, True] for data, bRight in zip(_datas, _isRight): if len(data.hisCrumbObjsAndNames) > 0: nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1] self.query_and_push(nextObj, name, bPush=False, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight=False) # def try_get_object(self, data, obj, name:str): index = -1 attribute = None for i, attr in enumerate(data.attributes): if attr.name == name: index = i attribute = attr assert index >= 0 return attribute.result, name def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled): self.showBuiltin = bEnabled self.apply_filter() def ui_on_checkbox_ShowOther_state_changed(self, bEnabled): self.showOther = bEnabled self.apply_filter() def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled): self.showProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled): self.showEditorProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled): self.showParamFunction = bEnabled self.apply_filter() def ui_on_listview_DetailList_selection_changed(self, bRight): data = [self.left, self.right][bRight] list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight] selected_indices = set(self.data.get_list_view_multi_column_selection(list_view)) added = selected_indices - data.selected de_selected = data.selected - selected_indices for i, lineId in enumerate(added): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False) for i, lineId in enumerate(de_selected): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(de_selected)-1 else False) data.selected = selected_indices
import unreal import inspect import logging logger = logging.getLogger(__name__) MEL = unreal.MaterialEditingLibrary from pamux_unreal_tools.base.material_expression.material_expression_sockets_base import InSocket, OutSocket from pamux_unreal_tools.base.material_expression.material_expression_base import MaterialExpressionBase from pamux_unreal_tools.utils.node_pos import NodePos class OutSocketImpl(OutSocket): def __init__(self, material_expression: MaterialExpressionBase, name: str, type: str) -> None: super().__init__(material_expression, name, type) # def connectTo(self, param1, param2 = None, param3 = None) -> bool: # if isinstance(param1, unreal.MaterialProperty): # return self.__connectTo_MaterialProperty(param1) # if isinstance(param1, str) and param1 is not None and isinstance(param2, MaterialExpressionBase) and isinstance(param3, str) and param3 is not None: # return self.__comesFrom_MaterialExpressionBase(param1, param2, param3) # raise Exception(f"Don't know how to call connectTo for type[s]: {str(param1)}, {str(param2)}") # def __connectTo_MaterialProperty(self, materialProperty: unreal.MaterialProperty) -> bool: # return MEL.connect_material_property(self.unrealAsset, "", materialProperty) # def __comesFrom_MaterialExpressionBase(self, outPortName: str, material_expression: MaterialExpressionBase, inPortName: str) -> bool: # return MEL.connect_material_expressions(self.unrealAsset, outPortName, material_expression.unrealAsset, inPortName) # @dispatch(MaterialExpressionBase, str) # def connectTo(self, OutSocket) -> bool: # return MEL.connect_material_expressions(self.unrealAsset, "", materialExpression.unrealAsset, inPortName) def connectTo(self, param) -> bool: if isinstance(param, InSocket): return self.__connectToInSocket(param) if isinstance(param, unreal.MaterialProperty): return self.__connectToMaterialProperty(param) if isinstance(param, MaterialExpressionBase): return self.__connectToMaterialExpression(param) raise Exception(f"Don't know how to call connectTo for type: {str(param)}") def __connectToInSocket(self, inSocket: InSocket) -> bool: self.material_expression.material_expression_editor_x.set(inSocket.material_expression.material_expression_editor_x.get() - NodePos.DeltaX) return MEL.connect_material_expressions(self.material_expression.unrealAsset, self.name, inSocket.material_expression.unrealAsset, inSocket.name) def __connectToMaterialProperty(self, materialProperty: unreal.MaterialProperty) -> bool: return MEL.connect_material_property(self.material_expression.unrealAsset, self.name, materialProperty) def __connectToMaterialExpression(self, material_expression: MaterialExpressionBase) -> bool: self.material_expression.material_expression_editor_x.set(material_expression.material_expression_editor_x.get() - NodePos.DeltaX) return MEL.connect_material_expressions(self.material_expression.unrealAsset, self.name, material_expression.unrealAsset, "") def __make_reroute_name_from_parts(self, parts: list): isFirst = True result = None for part in parts: if part is None: continue if isFirst: isFirst = False result = "rt" else: result += "." result += part[0].upper() + part[1:] return result def __get_reroute_name_from_stack(self): requiredLineEnding = ".add_rt()" _self = "self." for frame in inspect.getouterframes(inspect.currentframe()): # if type(self.material_expression).__name__ == "MF_LandscapeBaseMaterial": # logger.warning("*****************************") for line in frame.code_context: line = line.strip() if not line.endswith(requiredLineEnding): continue if line == "return self.output.add_rt()": continue if line.startswith(_self): start = len(_self ) else: start = 0 line = line[start:-len(requiredLineEnding)] if "." in line: return self.__make_reroute_name_from_parts(line.split(".")) return self.__make_reroute_name_from_parts([line, "Output"]) def add_rt(self, container_name:str = None, socket_name:str = None): if container_name is None: name = None else: if socket_name is None: name = self.__make_reroute_name_from_parts([container_name]) else: name = self.__make_reroute_name_from_parts([container_name, socket_name]) if name is None: name = self.__get_reroute_name_from_stack() result = self.material_expression.container.add_rt(name, self) self.rt = result return result raise Exception(f"Cannot find string ending with .add_rt() in call stack to set the name of the reroute")
import unreal import scripts.utils.UEFileManagerScript as UEFileManager import scripts.utils.popUp as popUp import scripts.state.stateManagerScript as stateManagerScript import scripts.export.exportAndSend as exportAndSend import re class TakeRecorder: """ Class for recording functionality in Unreal Engine. This class provides methods to start/stop recording and fetch the last recorded sequence and its assets. Methods: - __init__(self): Constructor method to initialize the TakeRecorder. - start_recording(self): Start recording. - stop_recording(self): Stop recording. - fetch_last_recording(self): Fetch last recording. - fetch_last_recording_assets(self): Fetch last recording assets. - set_name_take(self, name): Set name for the recording take. - get_slate(self): Get the current slate str - get_sources(self): Get the take recorder sourcs for the current take recorder panel - get_slate_from_take(self): get the slate from the take - is_recording(self): check if we are recording currently """ def __init__(self, stateManager): self.stateManager = stateManager unreal.TakeRecorderBlueprintLibrary.open_take_recorder_panel() self.take_recorder_panel = unreal.TakeRecorderBlueprintLibrary.get_take_recorder_panel() self.levelSequence = unreal.LevelSequence self.metadata = self.take_recorder_panel.get_take_meta_data() self.UEFileFuncs = UEFileManager.UEFileFunctionalities() # make it callable def __call__(self): return True @staticmethod def _sanitize_name(name: str, replacement: str = "_") -> str: if name is None: return "" # any character _not_ in A–Z a–z 0–9 space _ or - _SANITIZE_RE = re.compile(r'[^0-9A-Za-z _-]') return _SANITIZE_RE.sub(replacement, name) def get_slate(self) -> str: """Retrieve the slate information from the take recorder panel.""" self.metadata = self.take_recorder_panel.get_take_meta_data() return self.metadata.get_slate() def set_slate_name(self, name : str) -> None: """ Sets the slate name for the Take Recorder panel. :param name: The name to set as the slate. """ clean_name = self._sanitize_name(name) self.metadata = self.take_recorder_panel.get_take_meta_data() self.metadata.set_slate(clean_name) def get_sources(self): """Retrieve the sources from the take recorder panel.""" lala = unreal.TakeRecorderBlueprintLibrary().get_take_recorder_panel() return lala.get_sources() def get_slate_from_take(self) -> str: """Retrieve the slate information from the current take.""" lala = unreal.TakeRecorderBlueprintLibrary().get_take_recorder_panel() lala.get_class() return unreal.TakeMetaData().get_slate() def is_recording(self) -> bool: """Check if recording is currently in progress.""" return unreal.TakeRecorderBlueprintLibrary.is_recording() def start_recording(self): """ Start recording. This function starts the recording process using the take recorder panel. """ self.take_recorder_panel.start_recording() def stop_recording(self): """ Stop recording. This function stops the recording process using the take recorder panel. """ try: self.take_recorder_panel.stop_recording() except Exception as e: print(f"Error stopping recording: {e}") popUp.show_popup_message("Error stopping recording", f"Error stopping recording: {e}") def replay_last(self, replay_actor): """ Start replaying. This function starts the replaying process using the take recorder panel. """ # cur_level_sequence_actor.call_method( # "Event Replay Recording", args=(self.fetch_last_recording(),) # ) replay_actor.call_method("playThisAnim", args=(self.fetch_last_recording(),)) def replay_anim(self, replay_actor, anim): """ Start replaying. This function starts the replaying process using the take recorder panel. """ replay_actor.call_method("playThisAnim", args=(anim,)) def fetch_last_recording(self): """ Fetch last recording. Returns: - level_sequence (unreal.LevelSequence): The last recorded level sequence. """ return self.take_recorder_panel.get_last_recorded_level_sequence() # return self.take_recorder_panel.get_level_sequence() def fetch_last_animation(self, actor_name="GlassesGuyRecord"): """ Fetch last animation. Returns: - level_sequence (unreal.AnimSequence): The last recorded level sequence. """ last_record = self.fetch_last_recording() if last_record is None: print("No last recording found, returning None None") return None, None last_record = last_record.get_full_name() unrealTake = last_record.replace("LevelSequence ", "") unrealScene = unrealTake.split(".")[1] unrealTake = unrealTake.split(".")[0] animLocation = unrealTake + f"_Subscenes/Animation/{actor_name}" + "_" + unrealScene animation_asset = unreal.load_asset(animLocation) return animation_asset, animLocation def fetch_last_recording_assets(self): """ Fetch last recording assets. This function fetches the assets recorded in the last recording session. Returns: - files_list (list): A list of file names of assets recorded in the last session. """ # Fetch last recording path in UE path form anim_dir = self.fetch_last_recording().get_path_name() anim_dir = anim_dir.split(".")[0] + "_Subscenes/Animation/" project_path = self.UEFileFuncs.get_project_path() return self.UEFileFuncs.fetch_files_from_dir_in_project( anim_dir, project_path, mode="UE" ) def take_recorder_ready(self): """ Check if the take recorder is ready. This function checks if the take recorder panel is ready for recording. Returns: - ready (bool): True if the take recorder is ready, False otherwise. """ print(self.take_recorder_panel.can_start_recording()) return self.take_recorder_panel.can_start_recording() def error_test(self): """ Check if the take recorder is ready. This function checks if the take recorder panel is ready for recording. Returns: - ready (bool): True if the take recorder is ready, False otherwise. """ print("Error Test") popUp.show_popup_message("Error Test", "This is a pop-up message from Unreal Python!") return False def export_animation(self, location, folder, gloss_name, actor_name="GlassesGuyRecord"): if not gloss_name: gloss_name = self.stateManager.get_gloss_name() print(f"Exporting last recording: {gloss_name}...") last_anim, location = self.fetch_last_animation(actor_name=actor_name) if last_anim is None: self.stateManager.flip_export_status() self.stateManager.set_recording_status(stateManagerScript.Status.IDLE) popUp.show_popup_message("replay", "[TakeRecorder.py] No last recording found") return False success, full_export_path = exportAndSend.export_animation(location, self.stateManager.folder, gloss_name) if not success: self.stateManager.flip_export_status() self.stateManager.set_recording_status(stateManagerScript.Status.IDLE) popUp.show_popup_message("Export Failed", f"[TakeRecorder.py] Export failed for {gloss_name}") return False print(f"Exporting last recording done: {gloss_name}\tPath: {location}") # Export fbx to Vicon PC exportAndSend.copy_paste_file_to_vicon_pc( source=full_export_path ) return True def add_actor_to_take_recorder(self, actor: unreal.Actor): """ Adds an actor to the Take Recorder as a source. """ if not actor: unreal.log_error("No actor provided.") return # Grab source container sources = self.take_recorder_panel.get_sources() # Use the Actor-source helper new_source = unreal.TakeRecorderActorSource.add_source_for_actor(actor, sources) if new_source: unreal.log(f"Added '{actor.get_name()}' to Take Recorder sources.") else: unreal.log_error(f"Failed to add '{actor.get_name()}' to Take Recorder sources.")
""" GUI class to detect USD prims with animation and individually import them to Unreal Engine 5 as USDStageActors """ import unreal from pathlib import Path from pxr import Usd, UsdGeom, Sdf from PySide2 import QtWidgets from PySide2.QtWidgets import * ELL = unreal.EditorLevelLibrary() EAL = unreal.EditorAssetLibrary() class USDStageHandler: """ Handler class to store the current USD Stage object""" stage = None @classmethod def open_stage(cls, file_path): """class method to open and store current USD Stage Parameters ----------- file_path : str string address for the location of the USD file to be loaded """ valid_extensions = [".usd", ".usda", ".usdc", ".usdz"] if not any(file_path.endswith(ext) for ext in valid_extensions): raise ValueError("Invalid USD file path") try: stage = Usd.Stage.Open(file_path) cls.stage = stage except Exception as e: print(f"Failed to open USD stage: {e}") cls.stage = None class USDAnimImportDialog(QtWidgets.QDialog): """ A dialog for importing USD animations Attributes: file_path_edit (QLineEdit): Input field for file path. prim_list_widget (QListWidget): List widget for displaying prims. prim_strings (dict): Dictionary to store path strings and Sdf.Path(). use_default_checkbox (QCheckBox): Checkbox for default export directory. export_dir_edit (QLineEdit): Input field for export directory. export_button (QPushButton): Button for exporting selected prims. """ def __init__(self, parent=None): """ Initialise the USDAnimImportDialog """ super().__init__() # input file section self.file_path_edit = QLineEdit() self.browse_button = QPushButton("Browse") self.browse_button.clicked.connect(self.browse_file) self.file_input_layout = QHBoxLayout() self.file_input_layout.addWidget(QLabel("File Path:")) self.file_input_layout.addWidget(self.file_path_edit) self.file_input_layout.addWidget(self.browse_button) self.prim_type_combo = QComboBox() self.prim_type_combo.addItem("Mesh") self.prim_type_combo.addItem("Camera") self.prim_type_combo.addItem("XForm") self.is_animated_checkbox = QCheckBox("Animated") self.is_animated_checkbox.setChecked(False) self.reload_button = QPushButton("Reload") self.reload_button.clicked.connect(self.reload_prims_list) self.prim_type_layout = QHBoxLayout() self.prim_type_layout.addWidget(self.prim_type_combo) self.prim_type_layout.addWidget(self.is_animated_checkbox) self.prim_type_layout.addWidget(self.reload_button) # list widget for prims self.prim_list_widget = QListWidget() self.prim_list_widget.setSelectionMode(QListWidget.MultiSelection) # create dictionary for path strings and Sdf.Path() self.prim_strings = {} # checkbox for default export directory self.use_default_checkbox = QCheckBox("Use Default Export Directory") self.use_default_checkbox.setChecked(True) self.use_default_checkbox.stateChanged.connect(self.toggle_export_dir_edit) self.individual_checkbox = QCheckBox("Export individually") self.individual_checkbox.setChecked(True) self.individual_checkbox.stateChanged.connect(self.toggle_individual_export) self.file_name_edit = QLineEdit() self.file_name_edit.setEnabled(False) self.export_checkboxes = QHBoxLayout() self.export_checkboxes.addWidget(self.use_default_checkbox) self.export_checkboxes.addWidget(self.individual_checkbox) self.export_checkboxes.addWidget(QLabel("File Name:")) self.export_checkboxes.addWidget(self.file_name_edit) # create export directory selection section self.export_type_combo = QComboBox() self.export_type_combo.addItem("Mesh") self.export_type_combo.addItem("Camera") self.export_type_combo.addItem("XForm") self.export_dir_edit = QLineEdit() self.export_dir_edit.setEnabled(False) # disabled by default self.select_export_dir_button = QPushButton("Select export directory") self.select_export_dir_button.setEnabled(False) self.select_export_dir_button.clicked.connect(self.select_export_directory) self.export_dir_layout = QHBoxLayout() self.export_dir_layout.addWidget(QLabel("Export Type:")) self.export_dir_layout.addWidget(self.export_type_combo) self.export_dir_layout.addWidget(QLabel("Export Directory:")) self.export_dir_layout.addWidget(self.export_dir_edit) self.export_dir_layout.addWidget(self.select_export_dir_button) self.export_button = QPushButton("Export Selected Prims") self.export_button.clicked.connect(self.export_options) # set layout layout = QVBoxLayout() layout.addLayout(self.file_input_layout) layout.addWidget(QLabel("Prim Type:")) layout.addLayout(self.prim_type_layout) layout.addWidget(QLabel("Select imported prims:")) layout.addWidget(self.prim_list_widget) layout.addLayout(self.export_checkboxes) layout.addLayout(self.export_dir_layout) layout.addWidget(self.export_button) self.setLayout(layout) def browse_file(self) -> None: """ Open a file dialog to browse and select a USD file. The selected file path is displayed in the file path edit field, and the prims list is populated based on the selected file. Returns: None """ file_path, _ = QFileDialog.getOpenFileName(self, "Open File", "", "USD Files (*.usd*)") if file_path: self.file_path_edit.setText(file_path) self.populate_prims_list(file_path) def reload_prims_list(self): """ Calls populate_prims_list on button press and updates the export type. """ file_path = self.file_path_edit.text() self.populate_prims_list(file_path) # set the export type to match the current prim type self.export_type_combo.setCurrentIndex(self.prim_type_combo.currentIndex()) def populate_prims_list(self, file_path: str) -> None: """ Populate the prims list widget with animation prims from the specified USD file. Parameters ---------- file_path : str The path to the USD file. Returns ------- None """ self.prim_list_widget.clear() try: USDStageHandler.open_stage(file_path) except Exception as e: print("Error:", e) return stage = USDStageHandler.stage mesh_type = self.prim_type_combo.currentText() is_animated = self.is_animated_checkbox.isChecked() prims = self.usd_prim_extraction(stage, mesh_type, is_animated) for prim_path in prims: self.prim_list_widget.addItem(str(prim_path)) self.prim_strings[str(prim_path)] = prim_path def usd_prim_extraction(self, stage: Usd.Stage, mesh_type: str, is_animated: bool) -> list[Sdf.Path]: """ Retrieve the paths of USD Prims that match the specified type and filter criteria based on the presence of time samples. Parameters ---------- stage : Usd.Stage The USD stage to extract from mesh_type : str The type of prim to extract is_animated : bool Whether to only extract prims with animation or not Returns ------- list list of the prim_paths found """ prim_paths = [] if mesh_type == "Mesh": prims = self.find_prims_by_type(stage, UsdGeom.Mesh) elif mesh_type == "Camera": prims = self.find_prims_by_type(stage, UsdGeom.Camera) else: prims = self.find_prims_by_type(stage, UsdGeom.Xform) for prim in prims: if is_animated: for attr in prim.GetAttributes(): if attr.GetNumTimeSamples() > 0: prim_paths.append(prim.GetPath()) break else: prim_paths.append(prim.GetPath()) return prim_paths def toggle_export_dir_edit(self): """ Toggle whether to use default export directory or chosen. """ state = self.use_default_checkbox.isChecked() if state == 0: self.export_dir_edit.setEnabled(True) self.select_export_dir_button.setEnabled(True) else: self.export_dir_edit.setEnabled(False) self.select_export_dir_button.setEnabled(False) self.toggle_individual_export() def toggle_individual_export(self): """ Toggle whether to export prim files individually or together. """ state = self.individual_checkbox.isChecked() if state == 0: self.file_name_edit.setEnabled(True) else: self.file_name_edit.setEnabled(False) def select_export_directory(self): """ Opens a file dialog to browse and select directory to export animated prim files to. """ export_dir = QFileDialog.getExistingDirectory(self, "Select export Directory") if export_dir: self.export_dir_edit.setText(export_dir) def export_options(self): """ Called from the button click event to set up export of selected animated prims. """ file_path = self.file_path_edit.text() stage = USDStageHandler.stage selected_paths = self.prim_list_widget.selectedItems() anim_obj_paths = [] # add selected prims to list to be exported for path in selected_paths: anim_obj_paths.append(self.prim_strings[path.text()]) export_type = self.export_type_combo.currentText() export_individual = self.individual_checkbox.isChecked() if not self.use_default_checkbox.isChecked(): target_directory = self.export_dir_edit.text() else: target_directory = "" if export_individual: self.export_anim_prims(file_path, stage, anim_obj_paths, export_type, export_individual, target_directory) else: file_name = self.file_name_edit.text() self.export_anim_prims(file_path, stage, anim_obj_paths, export_type, export_individual, target_directory, file_name) # update doc string def export_anim_prims(self, file_path: str, stage: Usd.Stage, anim_obj_paths: list[Sdf.Path], export_type: str, export_individual: bool, target_directory:str ="", file_name: str="untitled") -> None: """ Export animation prims to USD files. Parameters ---------- file_path : str The original USD file path. stage : Usd.Stage The USD stage containing animation prims anim_obj_paths : list[Sdf.Path] List of Sdf.Path objects representing animation prims export_type : str The type to export the prim as export_individual : bool Determines whether to export individual usd prim files or have group them into one target_directory : str, optional The target directory for exporting USD files. Defaults to "" file_name : str, optional The name of the usd file if exporting as a group. Defaults to "untitled" Returns ------- None """ if export_individual: for prim_path in anim_obj_paths : temp_stage = self.create_temp_stage(stage) temp_stage = self.add_prim_to_stage(stage, temp_stage, file_path, export_type, prim_path) file_name = stage.GetPrimAtPath(prim_path).GetName() self.export_stage(temp_stage, target_directory, file_name) target_directory = "" else: temp_stage = self.create_temp_stage(stage) for prim_path in anim_obj_paths: temp_stage = self.add_prim_to_stage(stage, temp_stage, file_path, export_type, prim_path) self.export_stage(temp_stage, target_directory, file_name) target_directory = "" def create_temp_stage(self, stage: Usd.Stage) -> Usd.Stage: """ Creates a temporary USD stage with a default animation prim. Parameters ---------- stage : Usd.Stage The original USD stage. Returns ------- Usd.Stage The temporary USD stage to add to and export """ temp_stage = Usd.Stage.CreateInMemory() default_prim = UsdGeom.Xform.Define(temp_stage, Sdf.Path("/default")) temp_stage.SetDefaultPrim(default_prim.GetPrim()) # set basic stage metadata for animation temp_stage.SetStartTimeCode(stage.GetStartTimeCode()) temp_stage.SetEndTimeCode(stage.GetEndTimeCode()) temp_stage.SetTimeCodesPerSecond(stage.GetTimeCodesPerSecond()) temp_stage.SetFramesPerSecond(stage.GetFramesPerSecond()) return temp_stage def add_prim_to_stage(self, stage: Usd.Stage, temp_stage: Usd.Stage, file_path: str, export_type: str, prim_path: Sdf.Path) -> Usd.Stage: """ Add a prim to the stage. Parameters ---------- stage : Usd.Stage The original USD stage temp_stage : Usd.Stage The temporary USD stage file_path : str The file path of the original USD file export_type : str The type of prim to export prim_path : Sdf.Path The path of the prim to add Returns ------- Usd.Stage The modified USD stage to export """ prim_name = stage.GetPrimAtPath(prim_path).GetName() new_path = "/default/" + prim_name if export_type == "Mesh": ref_prim = UsdGeom.Mesh.Define(temp_stage, Sdf.Path(new_path)).GetPrim() elif export_type == "Camera": ref_prim = UsdGeom.Camera.Define(temp_stage, Sdf.Path(new_path)).GetPrim() else: ref_prim = UsdGeom.Xform.Define(temp_stage, Sdf.Path(new_path)).GetPrim() self.add_ext_reference(ref_prim, ref_asset_path=file_path, ref_target_path=prim_path) return temp_stage def export_stage(self, temp_stage: Usd.Stage, target_directory: str, file_name: str): """ Export the temporary stage with its additions to a USD file Parameters ---------- temp_stage : Usd.Stage The temporary USD stage to export target_directory : str The target directory for exporting the USD file file_name : str The name of the exported USD file Returns ------- None """ if target_directory == "": project_path = Path(unreal.Paths.get_project_file_path()).parent target_directory = project_path / "Content" / "usd_exports" / file_name else : target_directory = Path(target_directory) / file_name target_directory = target_directory.with_suffix(".usda") temp_stage.Export(str(target_directory)) print("Creating .usda at: " + str(target_directory)) self.create_usd_stage_actor(str(target_directory ), file_name) return target_directory def add_ext_reference(self, prim: Usd.Prim, ref_asset_path: str, ref_target_path: Sdf.Path) -> None: """ Code from NVidia Omniverse dev guide to add USD reference prim to a stage https://docs.omniverse.nvidia.com/dev-guide/project/-payloads/add-reference.html """ references: Usd.References = prim.GetReferences() references.AddReference( assetPath=ref_asset_path, primPath=ref_target_path # OPTIONAL: Reference a specific target prim. Otherwise, uses the referenced layer's defaultPrim. ) def find_prims_by_type(self, stage: Usd.Stage, prim_type: type[Usd.Typed]) -> list[Usd.Prim]: """ Code from NVidia Omniverse dev guide to find prims of a given type https://docs.omniverse.nvidia.com/dev-guide/project/-traversal/find-prims-by-type.html """ found_prims = [x for x in stage.Traverse() if x.IsA(prim_type)] return found_prims def create_usd_stage_actor(self, file_path: str, prim_name: str) -> None: usd_stage_actor = ELL.spawn_actor_from_class(unreal.UsdStageActor , unreal.Vector()) usd_stage_actor.set_editor_property("root_layer",unreal.FilePath( file_path )) usd_stage_actor.set_actor_label(prim_name + "_usd") return usd_stage_actor # if __name__ == "__ue_importer_gui__": if not QtWidgets.QApplication.instance(): app = QtWidgets.QApplication([]) dialog = USDAnimImportDialog() dialog.show() unreal.parent_external_window_to_slate(dialog.winId())
# Copyright Epic Games, Inc. All Rights Reserved import unreal from getpass import getuser # Get a render queue pipeline_subsystem = unreal.get_editor_subsystem( unreal.MoviePipelineQueueSubsystem ) # Get the project settings project_settings = unreal.get_default_object( unreal.MovieRenderPipelineProjectSettings ) # Get the pipeline queue movie_pipeline_queue = pipeline_subsystem.get_queue() pipeline_executor = None def get_executor_instance(is_remote): """ Method to return an instance of a render executor :param bool is_remote: Flag to use the local or remote executor class :return: Executor instance """ is_soft_class_object = True # Convert the SoftClassPath into a SoftClassReference. # local executor class from the project settings try: class_ref = unreal.SystemLibrary.conv_soft_class_path_to_soft_class_ref( project_settings.default_local_executor ) # For Backwards compatibility. Older version returned a class object from # the project settings except TypeError: class_ref = project_settings.default_local_executor is_soft_class_object = False if is_remote: try: # Get the remote executor class class_ref = ( unreal.SystemLibrary.conv_soft_class_path_to_soft_class_ref( project_settings.default_remote_executor ) ) except TypeError: class_ref = project_settings.default_remote_executor is_soft_class_object = False if not class_ref: raise RuntimeError( "Failed to get a class reference to the default executor from the " "project settings. Check the logs for more details." ) if is_soft_class_object: # Get the executor class as this is required to get an instance of # the executor executor_class = unreal.SystemLibrary.load_class_asset_blocking( class_ref ) else: executor_class = class_ref global pipeline_executor pipeline_executor = unreal.new_object(executor_class) return pipeline_executor def execute_render(is_remote=False, executor_instance=None, is_cmdline=False): """ Starts a render :param bool is_remote: Flag to use the local or remote executor class :param executor_instance: Executor instance used for rendering :param bool is_cmdline: Flag to determine if the render was executed from a commandline. """ if not executor_instance: executor_instance = get_executor_instance(is_remote) if is_cmdline: setup_editor_exit_callback(executor_instance) # Start the Render unreal.log("MRQ job started...") unreal.log(f"Is remote render: {is_remote}") pipeline_subsystem.render_queue_with_executor_instance(executor_instance) return executor_instance def setup_editor_exit_callback(executor_instance): """ Setup callbacks for when you need to close the editor after a render :param executor_instance: Movie Pipeline executor instance """ unreal.log("Executed job from commandline, setting up shutdown callback..") # add a callable to the executor to be executed when the pipeline is done rendering executor_instance.on_executor_finished_delegate.add_callable( shutdown_editor ) # add a callable to the executor to be executed when the pipeline fails to render executor_instance.on_executor_errored_delegate.add_callable( executor_failed_callback ) def shutdown_editor(movie_pipeline=None, results=None): """ This method shutdown the editor """ unreal.log("Rendering is complete! Exiting...") unreal.SystemLibrary.quit_editor() def executor_failed_callback(executor, pipeline, is_fatal, error): """ Callback executed when a job fails in the editor """ unreal.log_error( f"An error occurred while executing a render.\n\tError: {error}" ) unreal.SystemLibrary.quit_editor() def get_asset_data(name_or_path, asset_class): """ Get the asset data for the asset name or path based on its class. :param str name_or_path: asset name or package name :param str asset_class: Asset class filter to use when looking for assets in registry :raises RuntimeError :return: Asset package if it exists """ # Get all the specified class assets in the project. # This is the only mechanism we can think of at the moment to allow # shorter path names in the commandline interface. This will allow users # to only provide the asset name or the package path in the commandline # interface based on the assumption that all assets are unique asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() # If the asset registry is still loading, wait for it to finish if asset_registry.is_loading_assets(): unreal.log_warning("Asset Registry is loading, waiting to complete...") asset_registry.wait_for_completion() unreal.log("Asset Registry load complete!") assets = asset_registry.get_assets( unreal.ARFilter(class_names=[asset_class]) ) # This lookup could potentially be very slow for asset in assets: # If a package name is provided lookup the package path. If a # packages startwith a "/" this signifies a content package. Content # packages can either be Game or plugin. Game content paths start # with "/Game" and plugin contents startswith /<PluginName> if name_or_path.startswith("/"): # Reconstruct the package path into a package name. eg. # /project/.package_name -> /project/ name_or_path = name_or_path.split(".")[0] if asset.package_name == name_or_path: return asset else: if asset.asset_name == name_or_path: return asset else: raise RuntimeError(f"`{name_or_path}` could not be found!") def setup_remote_render_jobs(batch_name, job_preset, render_jobs): """ This function sets up a render job with the options for a remote render. This is configured currently for deadline jobs. :param str batch_name: Remote render batch name :param str job_preset: Job Preset to use for job details :param list render_jobs: The list of render jobs to apply the ars to """ unreal.log("Setting up Remote render executor.. ") # Update the settings on the render job. # Currently, this is designed to work with deadline # Make sure we have the relevant attribute on the jobs. This remote cli # setup can be used with out-of-process rendering and not just deadline. unset_job_properties = [] for job in render_jobs: if hasattr(job, "batch_name") and not batch_name: unset_job_properties.append(job.name) if hasattr(job, "job_preset") and not job_preset: unset_job_properties.append(job.name) # If we find a deadline property on the job, and it's not set, raise an # error if unset_job_properties: raise RuntimeError( "These jobs did not have a batch name, preset name or preset " "library set. This is a requirement for deadline remote rendering. " "{jobs}".format( jobs="\n".join(unset_job_properties)) ) for render_job in render_jobs: render_job.batch_name = batch_name render_job.job_preset = get_asset_data( job_preset, "DeadlineJobPreset" ).get_asset() def set_job_state(job, enable=False): """ This method sets the state on a current job to enabled or disabled :param job: MoviePipeline job to enable/disable :param bool enable: Flag to determine if a job should be or not """ if enable: # Check for an enable attribute on the job and if not move along. # Note: `Enabled` was added to MRQ that allows disabling all shots in # a job. This also enables backwards compatibility. try: if not job.enabled: job.enabled = True except AttributeError: # Legacy implementations assumes the presence of a job means its # enabled return try: if job.enabled: job.enabled = False except AttributeError: # If the attribute is not available, go through and disable all the # associated shots. This behaves like a disabled job for shot in job.shot_info: unreal.log_warning( f"Disabling shot `{shot.inner_name}` from current render job `{job.job_name}`" ) shot.enabled = False def update_render_output( job, output_dir=None, output_filename=None, override_output=None ): """ Updates that output directory and filename on a render job :param job: MRQ job :param str output_dir: Output directory for renders :param str output_filename: Output filename """ # Get the job output settings output_setting = job.get_configuration().find_setting_by_class( unreal.MoviePipelineOutputSetting ) if output_dir: new_output_dir = unreal.DirectoryPath() new_output_dir.set_editor_property( "path", output_dir ) unreal.log_warning( f"Overriding output directory! New output directory is `{output_dir}`." ) output_setting.output_directory = new_output_dir if output_filename: unreal.log_warning( f"Overriding filename format! New format is `{output_filename}`." ) output_setting.file_name_format = output_filename if override_output != None and override_output != output_setting.override_existing_output: unreal.log_warning( f"Overriding output files: `{str(override_output)}`." ) output_setting.override_existing_output = override_output def update_queue( jobs=None, shots=None, all_shots=False, user=None, ): """ This function configures and renders a job based on the arguments :param list jobs: MRQ jobs to render :param list shots: Shots to render from jobs :param bool all_shots: Flag for rendering all shots :param str user: Render user """ # Iterate over all the jobs and make sure the jobs we want to # render are enabled. # All jobs that are not going to be rendered will be disabled if the # job enabled attribute is not set or their shots disabled. # The expectation is, If a job name is specified, we want to render the # current state of that job. # If a shot list is specified, we want to only render that shot alongside # any other whole jobs (job states) that are explicitly specified, # else other jobs or shots that are not # needed are disabled for job in movie_pipeline_queue.get_jobs(): enable_job = False # Get a list of jobs to enable. # This will enable jobs in their current queue state awaiting other # modifications if shots are provided, if only the job name is # specified, the job will be rendered in its current state if jobs and (job.job_name in jobs): enable_job = True # If we are told to render all shots. Enable all shots for all jobs if all_shots: for shot in job.shot_info: shot.enabled = True # set the user for the current job job.author = user or getuser() # Set the job to enabled and move on to the next job set_job_state(job, enable=True) continue # If we have a list of shots, go through the shots associated # with this job, enable the shots that need to be rendered and # disable the others if shots and (not enable_job): for shot in job.shot_info: if shot.inner_name in shots or (shot.outer_name in shots): shot.enabled = True enable_job = True else: unreal.log_warning( f"Disabling shot `{shot.inner_name}` from current render job `{job.job_name}`" ) shot.enabled = False if enable_job: job.author = user or getuser() # Set the state of the job by enabling or disabling it. set_job_state(job, enable=enable_job)
# This scripts describes the process of capturing an managing properties with a little more # detail than test_variant_manager.py import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") var1 = unreal.Variant() var1.set_display_text("Variant 1") # Adds the objects to the correct parents lvs.add_variant_set(var_set1) var_set1.add_variant(var1) # Spawn a simple cube static mesh actor cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") spawned_actor = None if cube: location = unreal.Vector() rotation = unreal.Rotator() spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation) spawned_actor.set_actor_label("Cube Actor") else: print ("Failed to find Cube asset!") if spawned_actor is None: print ("Failed to spawn an actor for the Cube asset!") quit() # Bind spawned_actor to all our variants var1.add_actor_binding(spawned_actor) # See which properties can be captured from any StaticMeshActor capturable_by_class = unreal.VariantManagerLibrary.get_capturable_properties(unreal.StaticMeshActor.static_class()) # See which properties can be captured from our specific spawned_actor # This will also return the properties for any custom component structure we might have setup on the actor capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor) print ("Capturable properties for actor '" + spawned_actor.get_actor_label() + "':") for prop in capturable_props: print ("\t" + prop) print ("Capturable properties for its class:") for prop in capturable_by_class: print ("\t" + prop) # Returns nullptr for invalid paths. This will also show an error in the Output Log prop1 = var1.capture_property(spawned_actor, "False property path") assert prop1 is None # Comparison is case insensitive: The property is named "Can be Damaged", but this still works prop2 = var1.capture_property(spawned_actor, "cAn Be DAMAged") assert prop2 is not None and prop2.get_full_display_string() == "Can be Damaged" # Attempts to capture the same property more than once are ignored, and None is returned prop2attempt2 = var1.capture_property(spawned_actor, "Can Be Damaged") assert prop2attempt2 is None # Check which properties have been captured for some actor in a variant print ("Captured properties for '" + spawned_actor.get_actor_label() + "' so far:") captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print ("\t" + captured_prop.get_full_display_string()) # Capture property in a component prop3 = var1.capture_property(spawned_actor, "Static Mesh Component / Relative Location") assert prop3 is not None and prop3.get_full_display_string() == "Static Mesh Component / Relative Location" # Can't capture the component itself. This will also show an error in the Output Log prop4 = var1.capture_property(spawned_actor, "Static Mesh Component") assert prop4 is None # Capture material property prop5 = var1.capture_property(spawned_actor, "Static Mesh Component / Material[0]") assert prop5 is not None # Removing property captures var1.remove_captured_property(spawned_actor, prop2) var1.remove_captured_property_by_name(spawned_actor, "Static Mesh Component / Relative Location") print ("Captured properties for '" + spawned_actor.get_actor_label() + "' at the end:") captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print ("\t" + captured_prop.get_full_display_string()) # Should only have the material property left assert len(captured_props) == 1 and captured_props[0].get_full_display_string() == "Static Mesh Component / Material[0]"
import unreal def get_selected_content_browser_assets(): editor_utility = unreal.EditorUtilityLibrary() selected_assets = editor_utility.get_selected_assets() return selected_assets def generate_new_name_for_asset(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_"}, ] } name = asset.get_name() # Log to see the type of the asset print(f"Asset {asset.get_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 return name def rename_assets(assets): for i in range(len(assets)): asset = assets[i] old_name = asset.get_name() asset_old_path = asset.get_path_name() asset_folder = unreal.Paths.get_path(asset_old_path) new_name = generate_new_name_for_asset(asset) new_path = asset_folder + "/" + new_name if new_name == old_name: print(f"Ignoring: {old_name} is already named as {new_name} in the same folder") continue print(f"Renaming {old_name} to {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) for i in range(len(selected_assets)): asset = selected_assets[i] old_name = asset.get_name() new_name = generate_new_name_for_asset(asset) print(f"Renaming {old_name} to {new_name}") run()
# /project/ # @CBgameDev Optimisation Script - Log No LODs On Static Meshes # /project/ import unreal import os EditAssetLib = unreal.EditorAssetLibrary() StatMeshLib = unreal.EditorStaticMeshLibrary() workingPath = "/Game/" # Using the root directory notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt" allAssets = EditAssetLib.list_assets(workingPath, True, False) selectedAssetsPath = workingPath LogStringsArray = [] numOfOptimisations = 0 with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST: ST.make_dialog(True) for asset in allAssets: _assetData = EditAssetLib.find_asset_data(asset) _assetName = _assetData.get_asset().get_name() _assetPathName = _assetData.get_asset().get_path_name() _assetClassName = _assetData.get_asset().get_class().get_name() if _assetClassName == "StaticMesh": _staticMeshAsset = unreal.StaticMesh.cast(_assetData.get_asset()) # unreal.log(StatMeshLib.get_lod_count(_assetData.get_asset())) if StatMeshLib.get_lod_count(_staticMeshAsset) <= 1: # 1 because no LOD is 1 LogStringsArray.append(" %s ------------> At Path: %s \n" % (_assetName, _assetPathName)) # unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName)) numOfOptimisations += 1 if ST.should_cancel(): break ST.enter_progress_frame(1, asset) # Write results into a log file # /project/ TitleOfOptimisation = "Log No LODs On Static Meshes" DescOfOptimisation = "Searches the entire project for static mesh assets that do not have any LODs setup" SummaryMessageIntro = "-- Static Mesh Assets Which Do Not Have any LODs Setup --" if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists os.remove(notepadFilePath) # if does remove it # Create new txt file and run intro text file = open(notepadFilePath, "a+") # we should only do this if have a count? file.write("OPTIMISING SCRIPT by @CBgameDev \n") file.write("==================================================================================================== \n") file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation) file.write(" DESCRIPTION: %s \n" % DescOfOptimisation) file.write("==================================================================================================== \n \n") if numOfOptimisations <= 0: file.write(" -- NONE FOUND -- \n \n") else: for i in range(len(LogStringsArray)): file.write(LogStringsArray[i]) # Run summary text file.write("\n") file.write("======================================================================================================= \n") file.write(" SUMMARY: \n") file.write(" %s \n" % SummaryMessageIntro) file.write(" Found: %s \n \n" % numOfOptimisations) file.write("======================================================================================================= \n") file.write(" Logged to %s \n" % notepadFilePath) file.write("======================================================================================================= \n") file.close() os.startfile(notepadFilePath) # Trigger the notepad file to open
from pxr import Usd, UsdGeom, Sdf import unreal import os from usd_unreal import exporting_utils from usd_unreal import level_exporter from usd_unreal.constants import * import usd_extra_export_scripts def import_context(context): if not context.world or not isinstance(context.world, unreal.World): unreal.log_error("UsdImportContext's 'world' member must point to a valid unreal.World object!") return context.root_layer_path = exporting_utils.sanitize_filepath(context.root_layer_path) unreal.log(f"Starting import from root layer: '{context.root_layer_path}'") with unreal.ScopedSlowTask(2, f"Importing level from '{context.root_layer_path}'") as slow_task: slow_task.make_dialog(True) # Collect prims to import: context.stage = Usd.Stage.Open(context.root_layer_path) def import_with_cdo_options(): options_cdo = unreal.get_default_object(unreal.USDExtraExportOptions) context = usd_extra_export_scripts.UsdExtraExportContext context.root_layer_path = options_cdo.file_name context.world = options_cdo.world context.options = options_cdo import_context(context)
import unreal import sys # # =====================================================read the assets # @unreal.uclass() # class EditorUtils(unreal.GlobalEditorUtilityBase): # pass # selectedAssets=EditorUtils().get_selected_assets() # for asset in selectedAssets: # unreal.log(asset.get_full_name()) # unreal.log(asset.get_fname()) # unreal.log(asset.get_class()) # unreal.log("**************************************") # =========================================================create blueprint blueprintName="test_blueprint" blueprintPath='/project/' createdAssetsCout=int(sys.argv[1]) createdAssetsName=str(sys.argv[2]) # createdAssetsName+='\d' factory=unreal.BlueprintFactory() factory.set_editor_property("ParentClass", unreal.GameMode) assetTools=unreal.AssetToolsHelpers.get_asset_tools() for x in range(createdAssetsCout): myFile=assetTools.create_asset(createdAssetsName+str(x),blueprintPath,None,factory) unreal.EditorAssetLibrary.save_loaded_asset(myFile)
import os import json import unreal from Utilities.Utils import Singleton class Shelf(metaclass=Singleton): ''' This is a demo tool for showing how to create Chamelon Tools in Python ''' MAXIMUM_ICON_COUNT = 12 Visible = "Visible" Collapsed = "Collapsed" def __init__(self, jsonPath:str): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.shelf_data = self.load_data() self.is_text_readonly = True self.ui_drop_at_last_aka = "DropAtLast" self.ui_drop_is_full_aka = "DropIsFull" self.update_ui(bForce=True) def update_ui(self, bForce=False): visibles = [False] * Shelf.MAXIMUM_ICON_COUNT for i, shortcut in enumerate(self.shelf_data.shortcuts): if i >= Shelf.MAXIMUM_ICON_COUNT: continue self.data.set_visibility(self.get_ui_button_group_name(i), Shelf.Visible) self.data.set_tool_tip_text(self.get_ui_button_group_name(i), self.shelf_data.shortcuts[i].get_tool_tips()) self.data.set_text(self.get_ui_text_name(i), self.shelf_data.shortcuts[i].text) # ITEM_TYPE_PY_CMD = 1 ITEM_TYPE_CHAMELEON = 2 ITEM_TYPE_ACTOR = 3 ITEM_TYPE_ASSETS = 4 ITEM_TYPE_ASSETS_FOLDER = 5 icon_name = ["PythonTextGreyIcon_40x.png", "PythonChameleonGreyIcon_40x.png", "LitSphere_40x.png", "Primitive_40x.png", "folderIcon.png"][shortcut.drop_type-1] if os.path.exists(os.path.join(os.path.dirname(__file__), f"Images/{icon_name}")): self.data.set_image_from(self.get_ui_img_name(i), f"Images/{icon_name}") else: unreal.log_warning("file: {} not exists in this tool's folder: {}".format(f"Images/{icon_name}", os.path.join(os.path.dirname(__file__)))) visibles[i] = True for i, v in enumerate(visibles): if not v: self.data.set_visibility(self.get_ui_button_group_name(i), Shelf.Collapsed) self.lock_text(self.is_text_readonly, bForce) bFull = len(self.shelf_data) == Shelf.MAXIMUM_ICON_COUNT self.data.set_visibility(self.ui_drop_at_last_aka, "Collapsed" if bFull else "Visible") self.data.set_visibility(self.ui_drop_is_full_aka, "Visible" if bFull else "Collapsed" ) def lock_text(self, bLock, bForce=False): if self.is_text_readonly != bLock or bForce: for i in range(Shelf.MAXIMUM_ICON_COUNT): self.data.set_text_read_only(self.get_ui_text_name(i), bLock) self.data.set_color_and_opacity(self.get_ui_text_name(i), [1,1,1,1] if bLock else [1,0,0,1]) self.data.set_visibility(self.get_ui_text_name(i), "HitTestInvisible" if bLock else "Visible" ) self.is_text_readonly = bLock def get_ui_button_group_name(self, index): return f"ButtonGroup_{index}" def get_ui_text_name(self, index): return f"Txt_{index}" def get_ui_img_name(self, index): return f"Img_{index}" def on_close(self): self.save_data() def get_data_path(self): return os.path.join(os.path.dirname(__file__), "saved_shelf.json") def load_data(self): saved_file_path = self.get_data_path() if os.path.exists(saved_file_path): return ShelfData.load(saved_file_path) else: return ShelfData() def save_data(self): # fetch text from UI for i, shortcut in enumerate(self.shelf_data.shortcuts): shortcut.text = self.data.get_text(self.get_ui_text_name(i)) saved_file_path = self.get_data_path() if self.shelf_data != None: ShelfData.save(self.shelf_data, saved_file_path) else: unreal.log_warning("data null") def clear_shelf(self): self.shelf_data.clear() self.update_ui() def set_item_to_shelf(self, index, shelf_item): if index >= len(self.shelf_data): self.shelf_data.add(shelf_item) else: self.shelf_data.set(index, shelf_item) self.update_ui() # add shortcuts def add_py_code_shortcut(self, index, py_code): shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_PY_CMD) shelf_item.py_cmd = py_code shelf_item.text=py_code[:3] self.set_item_to_shelf(index, shelf_item) def add_chameleon_shortcut(self, index, chameleon_json): short_name = os.path.basename(chameleon_json) if short_name.lower().startswith("chameleon") and len(short_name) > 9: short_name = short_name[9:] shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_CHAMELEON) shelf_item.chameleon_json = chameleon_json shelf_item.text = short_name[:3] self.set_item_to_shelf(index, shelf_item) def add_actors_shortcut(self, index, actor_names): shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ACTOR) shelf_item.actors = actor_names shelf_item.text = shelf_item.actors[0][:3] if shelf_item.actors else "" shelf_item.text += str(len(shelf_item.actors)) self.set_item_to_shelf(index, shelf_item) def add_assets_shortcut(self, index, assets): shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ASSETS) shelf_item.assets = assets if assets: first_asset = unreal.load_asset(assets[0]) if first_asset: shelf_item.text = f"{first_asset.get_name()[:3]}{str(len(shelf_item.assets)) if len(shelf_item.assets)>1 else ''}" else: shelf_item.text = "None" else: shelf_item.text = "" self.set_item_to_shelf(index, shelf_item) def add_folders_shortcut(self, index, folders): shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ASSETS_FOLDER) shelf_item.folders = folders if folders: shelf_item.text = f"{(os.path.basename(folders[0]))[:3]}{str(len(folders)) if len(folders)>1 else ''}" else: shelf_item.text = "" self.set_item_to_shelf(index, shelf_item) def get_dropped_by_type(self, *args, **kwargs): py_cmd = kwargs.get("text", "") file_names = kwargs.get("files", None) if file_names: json_files = [n for n in file_names if n.lower().endswith(".json")] chameleon_json = json_files[0] if json_files else "" else: chameleon_json = "" actors = kwargs.get("actors", []) assets = kwargs.get("assets", []) folders = kwargs.get("assets_folders", []) return py_cmd, chameleon_json, actors, assets, folders def on_drop(self, id, *args, **kwargs): print(f"OnDrop: id:{id} {kwargs}") py_cmd, chameleon_json, actors, assets, folders = self.get_dropped_by_type(*args, **kwargs) if chameleon_json: self.add_chameleon_shortcut(id, chameleon_json) elif py_cmd: self.add_py_code_shortcut(id, py_cmd) elif actors: self.add_actors_shortcut(id, actors) elif assets: self.add_assets_shortcut(id, assets) elif folders: self.add_folders_shortcut(id, folders) else: print("Drop python snippet, chameleon json, actors or assets.") def on_drop_last(self, *args, **kwargs): print(f"on drop last: {args}, {kwargs}") if len(self.shelf_data) <= Shelf.MAXIMUM_ICON_COUNT: self.on_drop(len(self.shelf_data) + 1, *args, **kwargs) def select_actors(self, actor_names): actors = [unreal.PythonBPLib.find_actor_by_name(name) for name in actor_names] unreal.PythonBPLib.select_none() for i, actor in enumerate(actors): if actor: unreal.PythonBPLib.select_actor(actor, selected=True, notify=True, force_refresh= i == len(actors)-1) def select_assets(self, assets): exists_assets = [asset for asset in assets if unreal.EditorAssetLibrary.does_asset_exist(asset)] unreal.PythonBPLib.set_selected_assets_by_paths(exists_assets) def select_assets_folders(self, assets_folders): print(f"select_assets_folders: {assets_folders}") unreal.PythonBPLib.set_selected_folder(assets_folders) def on_button_click(self, id): shortcut = self.shelf_data.shortcuts[id] if not shortcut: unreal.log_warning("shortcut == None") return if shortcut.drop_type == ShelfItem.ITEM_TYPE_PY_CMD: eval(shortcut.py_cmd) elif shortcut.drop_type == ShelfItem.ITEM_TYPE_CHAMELEON: unreal.ChameleonData.launch_chameleon_tool(shortcut.chameleon_json) elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ACTOR: self.select_actors(shortcut.actors) # do anything what you want elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ASSETS: self.select_assets(shortcut.assets) elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ASSETS_FOLDER: self.select_assets_folders(shortcut.folders) class ShelfItem: ITEM_TYPE_NONE = 0 ITEM_TYPE_PY_CMD = 1 ITEM_TYPE_CHAMELEON = 2 ITEM_TYPE_ACTOR = 3 ITEM_TYPE_ASSETS = 4 ITEM_TYPE_ASSETS_FOLDER = 5 def __init__(self, drop_type, icon=""): self.drop_type = drop_type self.icon = icon self.py_cmd = "" self.chameleon_json = "" self.actors = [] self.assets = [] self.folders = [] self.text = "" def get_tool_tips(self): if self.drop_type == ShelfItem.ITEM_TYPE_PY_CMD: return f"PyCmd: {self.py_cmd}" elif self.drop_type == ShelfItem.ITEM_TYPE_CHAMELEON: return f"Chameleon Tools: {os.path.basename(self.chameleon_json)}" elif self.drop_type == ShelfItem.ITEM_TYPE_ACTOR: return f"{len(self.actors)} actors: {self.actors}" elif self.drop_type == ShelfItem.ITEM_TYPE_ASSETS: return f"{len(self.assets)} actors: {self.assets}" elif self.drop_type == ShelfItem.ITEM_TYPE_ASSETS_FOLDER: return f"{len(self.folders)} folders: {self.folders}" class ShelfData: def __init__(self): self.shortcuts = [] def __len__(self): return len(self.shortcuts) def add(self, item): assert isinstance(item, ShelfItem) self.shortcuts.append(item) def set(self, index, item): assert isinstance(item, ShelfItem) self.shortcuts[index] = item def clear(self): self.shortcuts.clear() @staticmethod def save(shelf_data, file_path): with open(file_path, 'w') as f: f.write(json.dumps(shelf_data, default=lambda o: o.__dict__, sort_keys=True, indent=4)) print(f"Shelf data saved: {file_path}") @staticmethod def load(file_path): if not os.path.exists(file_path): return None with open(file_path, 'r') as f: content = json.load(f) instance = ShelfData() instance.shortcuts = [] for item in content["shortcuts"]: shelf_item = ShelfItem(item["drop_type"], item["icon"]) shelf_item.py_cmd = item["py_cmd"] shelf_item.chameleon_json = item["chameleon_json"] shelf_item.text = item["text"] shelf_item.actors = item["actors"] shelf_item.assets = item["assets"] shelf_item.folders = item["folders"] instance.shortcuts.append(shelf_item) return instance
# coding: utf-8 from asyncio.windows_events import NULL import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-vrm") parser.add_argument("-rig") parser.add_argument("-meta") args = parser.parse_args() print(args.vrm) reg = unreal.AssetRegistryHelpers.get_asset_registry(); ## rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() print(rigs) for r in rigs: s:str = r.get_path_name() ss:str = args.rig if (s.find(ss) < 0): print("no rig") else: rig = r #rig = rigs[10] hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig) h_con = hierarchy.get_controller() r_con = rig.get_controller() graph = r_con.get_graph() node = graph.get_nodes() for e in hierarchy.get_controls(True): h_con.remove_element(e) for e in hierarchy.get_nulls(True): h_con.remove_element(e) boneCount = 0 for e in hierarchy.get_bones(): p = hierarchy.get_first_parent(e) print('===') print(e) print(p) t = unreal.Transform() s = unreal.RigControlSettings() s.shape_visible = False v = unreal.RigControlValue() shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001]) if (boneCount == 0): n = h_con.add_null("{}_s".format(e.name), unreal.RigElementKey(), t) c = h_con.add_control(e.name, n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) else: p.type = unreal.RigElementType.CONTROL n = h_con.add_null("{}_s".format(e.name), p, t) c = h_con.add_control(e.name, n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) if ("{}".format(e.name) == "head"): parent = c n = h_con.add_null("eye_l_s", parent, t) c = h_con.add_control("eye_l", n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) n = h_con.add_null("eye_r_s", parent, t) c = h_con.add_control("eye_r", n, s, v) t = hierarchy.get_global_transform(n) hierarchy.set_global_transform(c, t, True) hierarchy.set_control_shape_transform(c, shape_t, True) boneCount += 1
""" Improved multi-job render script using common utilities """ import sys import os import time import json import tkinter as tk from tkinter import filedialog import unreal # Add the common directory to Python path common_dir = os.path.dirname(os.path.abspath(__file__)) if common_dir not in sys.path: sys.path.append(common_dir) from render_queue_validation import UE5RenderUtils class UE5MultiJobRenderer: """Handles multi-job rendering with proper state management""" def __init__(self): self.utils = UE5RenderUtils() self.mrq_subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem) self.executor = unreal.MoviePipelinePIEExecutor(self.mrq_subsystem) self.pipeline_queue = self.mrq_subsystem.get_queue() # State management self.current_job_index = 0 self.current_render_index = 0 self.current_pano_points = [] self.current_level_name = "" self.base_output_dir = "" def set_user_exposed_variable_path(self, job: unreal.MoviePipelineExecutorJob, path: str): """Set output directory for the job""" graph = job.get_graph_preset() variables = graph.get_variables() if not variables: unreal.log_warning("No variables are exposed on this graph, expose 'OutputDirectory' to set custom paths") return False for variable in variables: if variable.get_member_name() == "OutputDirectory": variable_assignment = job.get_or_create_variable_overrides(graph) variable_assignment.set_value_serialized_string(variable, unreal.DirectoryPath(path).export_text()) variable_assignment.set_variable_assignment_enable_state(variable, True) return True unreal.log_warning("OutputDirectory variable not found in job variables") return False def scopeout_output_dir(self): if not self.base_output_dir: unreal.log_error("No output directory selected. Exiting...") return False if not os.path.isdir(self.base_output_dir): try: os.mkdir(self.base_output_dir) except: unreal.log_error("Could not create output directory. Exiting...") return False self.progress_cache_file_path = os.path.join(self.base_output_dir, "render_progress_cache.json") validation_cache_file_path = os.path.join(self.base_output_dir, "validation_cache.json") if not os.listdir(self.base_output_dir): self.validate_cache() return True unreal.log_error("Invalid Folder") return False def validate_cache(self): validation_cache_file_path = os.path.join(self.base_output_dir, "validation_cache.json") if not os.path.isfile(validation_cache_file_path): unreal.log("Writing new Validation Data...") with open(validation_cache_file_path, "w") as validation_cache_file: json.dump(self.validation_data,validation_cache_file,indent = 4) return True with open(validation_cache_file_path, "r") as validation_cache_file: try: validation_cache = json.load(validation_cache_file) except json.JSONDecodeError: unreal.log_warning("validation_cache file is not valid JSON. Initializing empty validation_cache.") return False if self.validation_data != validation_cache: ##### Return True if validation data till progress is same, overwrite new validation unreal.log_error("Validation cache does not match current queue") return False unreal.log("Validation cache checked, same as current queue.") return True def select_output_directory(self): """Show directory picker and set base output directory""" root = tk.Tk() root.withdraw() # Hide the root window self.base_output_dir = filedialog.askdirectory(title="Select an output folder") root.destroy() if not self.base_output_dir: unreal.log_error("No output directory selected. Exiting...") return False unreal.log(f"Output directory set to: {self.base_output_dir}") return True def start_rendering(self): """Start the multi-job rendering process""" isQueueValid, validation_data = self.utils.validate_movie_render_queue() if not isQueueValid: return False self.validation_data = validation_data if not self.select_output_directory(): return False if not self.scopeout_output_dir(): return False unreal.log(f"Starting render process with {len(self.pipeline_queue.get_jobs())} jobs") self._process_next_job() return True def _process_next_job(self): """Process the next job in the queue""" self.current_job = self.pipeline_queue.get_jobs()[self.current_job_index] unreal.log(f"Processing job {self.current_job_index + 1}/{len(self.pipeline_queue.get_jobs())}: {self.current_job.job_name}") # Validate job using common utilities is_valid, level_name, job_comment, pano_point_names = self.utils.validate_render_job(self.current_job) if not is_valid: unreal.log_error(f"Job {self.current_job.job_name} failed validation. Skipping...") self.current_job_index += 1 self._process_next_job() return self.current_level_name = level_name # Get actors from the loaded level self.current_pano_points = sorted([actor for actor in self.utils.eas.get_all_level_actors() if actor.get_class() == self.utils.pano_point_class], key=lambda a: a.get_actor_label()) cameras = sorted([actor for actor in self.utils.eas.get_all_level_actors() if actor.get_class() == self.utils.camera_class], key=lambda a: a.get_actor_label()) self.current_camera = cameras[0] if not self.current_camera: unreal.log_error(f"VeroCineCam not found in level {level_name}") self.current_job_index += 1 self._process_next_job() return # Disable all jobs except current one for job in self.pipeline_queue.get_jobs(): job.set_is_enabled(job == self.current_job) # Start rendering pano points for this job self.current_render_index = 0 def main(): """Main function to start the rendering process""" renderer = UE5MultiJobRenderer() # Start rendering return renderer.start_rendering() 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 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 # Get all actors in the current level actors = unreal.EditorLevelLibrary.get_all_level_actors() # Print all actor names print(f"Total Actors in Scene: {len(actors)}") for actor in actors: print(f"Actor: {actor.get_name()}, Class: {actor.get_class().get_name()}")
# 폴더의 에셋의 레퍼런스 확인 import unreal def unused_asset_notifier(workingPath : str) -> list[str]: need_to_return = [] @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass editorAssetLib = GetEditorAssetLibrary() allAssets = editorAssetLib.list_assets(workingPath, True, False) if (len(allAssets) > 0): for asset in allAssets: deps = editorAssetLib.find_package_referencers_for_asset(asset, False) if (len(deps) == 0): print (">>>%s" % asset) need_to_return.append(asset) return need_to_return unused = unused_asset_notifier('/project/')
import unreal #instance of unreal classes editor_level_lib = unreal.EditorLevelLibrary() editor_filter_lib = unreal.EditorFilterLibrary() #get all actors and filter down to static mesh actors actors = editor_level_lib.get_all_level_actors() static_mesh = editor_filter_lib.by_class(actors, unreal.StaticMeshActor) #Keep track of the actor index index = 0 changed = 0 #loop trought the actors for sma in static_mesh: #collect the old label and get the substring for '_' old_label = sma.get_actor_label() split_label = old_label.split('_') #if the label actually contains the underscore and has a substring before it if len(split_label) > 1: prefix = split_label[0] #Create the new label and set it to the actor new_label = "{}_{}".format(prefix, index) sma.set_actor_label(new_label) changed += 1 index += 1 print("Done! Changed label for {} actors from {}.".format(changed, index))
import unreal import json import os def normalize_path(path): """ Normaliza una ruta para asegurar que comience con /Game/ """ if not path.startswith('/Game/'): path = path.strip('/') path = f'/Game/{path}' return path def force_delete_asset(asset_path): """ Fuerza la eliminación de un asset y sus referencias """ try: if unreal.EditorAssetLibrary.does_asset_exist(asset_path): # Intentar eliminar referencias unreal.EditorAssetLibrary.delete_loaded_asset(asset_path) print(f'Asset eliminado: {asset_path}') return True except Exception as e: print(f'Error al eliminar asset {asset_path}: {str(e)}') return False def create_blueprint(parent_class, name, folder_path, force_recreate=True): """ Crea un nuevo Blueprint con la clase padre y nombre especificados """ try: # Normalizar la ruta full_path = normalize_path(folder_path) package_path = f"{full_path}/{name}" # Si existe y force_recreate es True, intentar eliminar if force_recreate: force_delete_asset(package_path) # Crear el factory para Blueprints factory = unreal.BlueprintFactory() factory.set_editor_property('ParentClass', parent_class) # Obtener el asset tools asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Asegurarse de que el directorio existe package_name = unreal.Paths.get_base_filename(package_path) package_folder = unreal.Paths.get_path(package_path) if not unreal.EditorAssetLibrary.does_directory_exist(package_folder): unreal.EditorAssetLibrary.make_directory(package_folder) # Crear el Blueprint new_blueprint = asset_tools.create_asset( package_name, package_folder, unreal.Blueprint, factory ) if new_blueprint is not None: # Forzar la compilación del Blueprint unreal.EditorLoadingAndSavingUtils.save_dirty_packages( save_map_packages=True, save_content_packages=True ) print(f'Blueprint creado y guardado: {package_path}') return new_blueprint else: print(f'Error al crear Blueprint: {package_path}') return None except Exception as e: print(f'Error al crear Blueprint {name}: {str(e)}') return None def clean_directory(directory_path): """ Limpia un directorio eliminando todos los assets """ try: if unreal.EditorAssetLibrary.does_directory_exist(directory_path): assets = unreal.EditorAssetLibrary.list_assets(directory_path) for asset in assets: force_delete_asset(asset) print(f'Directorio limpiado: {directory_path}') except Exception as e: print(f'Error al limpiar directorio {directory_path}: {str(e)}') def setup_digital_twin(): """ Configura todos los Blueprints necesarios para el gemelo digital """ try: # Limpiar directorios existentes base_folders = [ 'Blueprints/Core', 'Blueprints/Security', 'Blueprints/Inventory', 'Blueprints/Customer', 'Blueprints/Layout', 'Blueprints/Help' ] print('Limpiando directorios existentes...') for folder in base_folders: path = normalize_path(folder) clean_directory(path) if not unreal.EditorAssetLibrary.does_directory_exist(path): unreal.EditorAssetLibrary.make_directory(path) print(f'Directorio creado: {path}') # Forzar una recolección de basura unreal.EditorLevelLibrary.editor_command('GC.CollectGarbage') print('Creando nuevos Blueprints...') # Crear GameMode principal game_mode = create_blueprint( unreal.GameModeBase.static_class(), 'BP_DigitalTwinGameMode', '/project/', force_recreate=True ) # Definir sistemas principales systems = { 'Blueprints/Security': { 'BP_SecurityCamera': unreal.Actor.static_class(), 'BP_SecuritySystem': unreal.Actor.static_class() }, 'Blueprints/Inventory': { 'BP_InventoryManager': unreal.Actor.static_class(), 'BP_Product': unreal.Actor.static_class() }, 'Blueprints/Customer': { 'BP_CustomerSimulation': unreal.Actor.static_class(), 'BP_VirtualCustomer': unreal.Character.static_class() }, 'Blueprints/Layout': { 'BP_LayoutEditor': unreal.Actor.static_class(), 'BP_LayoutValidator': unreal.Actor.static_class() }, 'Blueprints/Help': { 'WBP_HelpSystem': unreal.WidgetBlueprint.static_class(), 'BP_TutorialManager': unreal.Actor.static_class() } } created_blueprints = {} # Crear Blueprints para cada sistema for folder_path, blueprints in systems.items(): normalized_path = normalize_path(folder_path) folder_name = folder_path.split('/')[-1] created_blueprints[folder_name] = {} for bp_name, parent_class in blueprints.items(): bp = create_blueprint(parent_class, bp_name, normalized_path, force_recreate=True) if bp is not None: created_blueprints[folder_name][bp_name] = bp # Forzar guardado de todos los paquetes unreal.EditorLoadingAndSavingUtils.save_dirty_packages( save_map_packages=True, save_content_packages=True ) print('Configuración del gemelo digital completada') except Exception as e: print(f'Error durante la configuración: {str(e)}') def generate_websocket_blueprint(): # Configuración básica del Blueprint blueprint_name = '/project/' blueprint_factory = unreal.BlueprintFactory() blueprint_factory.set_editor_property('ParentClass', unreal.Actor) # Crear el Blueprint package_path = '/project/' blueprint = unreal.AssetToolsHelpers.get_asset_tools().create_asset( 'BP_WebSocketManager', package_path, unreal.Blueprint, blueprint_factory ) # Añadir variables blueprint_class = blueprint.get_blueprint_class() # Variables para WebSocket unreal.BlueprintVariable( 'WebSocketURL', unreal.EdGraphPinType( 'string', 'ESPMode::Type::ThreadSafe', None, unreal.EPinContainerType.NONE, False, unreal.FEdGraphTerminalType() ) ) # Funciones principales functions = [ { 'name': 'ConnectToServer', 'inputs': [], 'outputs': [('Success', 'bool')] }, { 'name': 'ProcessSensorData', 'inputs': [('SensorData', 'string')], 'outputs': [] }, { 'name': 'UpdateDigitalTwin', 'inputs': [ ('Temperature', 'float'), ('Humidity', 'float'), ('Pressure', 'float'), ('Motion', 'bool'), ('Stock', 'int') ], 'outputs': [] } ] # Crear funciones for func in functions: function = unreal.BlueprintFunctionLibrary.create_function( blueprint_class, func['name'] ) # Añadir inputs y outputs for input_name, input_type in func['inputs']: unreal.BlueprintFunctionLibrary.add_parameter( function, unreal.Parameter(input_name, input_type) ) for output_name, output_type in func['outputs']: unreal.BlueprintFunctionLibrary.add_return_value( function, unreal.Parameter(output_name, output_type) ) # Compilar Blueprint unreal.EditorLoadingAndSavingUtils.save_package( blueprint.get_outer(), '/project/' ) if __name__ == '__main__': setup_digital_twin() generate_websocket_blueprint()
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)