Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
15
267k
# -*- coding: utf-8 -*- import logging import unreal import inspect import types import Utilities from collections import Counter class attr_detail(object): def __init__(self, obj, name:str): self.name = name attr = None self.bCallable = None self.bCallable_builtin = None try: if hasattr(obj, name): attr = getattr(obj, name) self.bCallable = callable(attr) self.bCallable_builtin = inspect.isbuiltin(attr) except Exception as e: unreal.log(str(e)) self.bProperty = not self.bCallable self.result = None self.param_str = None self.bEditorProperty = None self.return_type_str = None self.doc_str = None self.property_rw = None if self.bCallable: self.return_type_str = "" if self.bCallable_builtin: if hasattr(attr, '__doc__'): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) # print(f"~~~~~ attr: {self.name} docForDisplay: {docForDisplay} paramStr: {paramStr}") # print(attr.__doc__) try: sig = inspect.getfullargspec(getattr(obj, self.name)) # print("+++ ", sig) args = sig.args argCount = len(args) if "self" in args: argCount -= 1 except TypeError: argCount = -1 if "-> " in docForDisplay: self.return_type_str = docForDisplay[docForDisplay.find(')') + 1:] else: self.doc_str = docForDisplay[docForDisplay.find(')') + 1:] if argCount == 0 or (argCount == -1 and (paramStr == '' or paramStr == 'self')): # Method with No params if '-> None' not in docForDisplay or self.name in ["__reduce__", "_post_init"]: try: if name == "get_actor_time_dilation" and isinstance(obj, unreal.Object): # call get_actor_time_dilation will crash engine if actor is get from CDO and has no world. if obj.get_world(): # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() else: self.result = "skip call, world == None." else: # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() except: self.result = "skip call.." else: print(f"docForDisplay: {docForDisplay}, self.name: {self.name}") self.result = "skip call." else: self.param_str = paramStr self.result = "" else: logging.error("Can't find p") elif self.bCallable_other: if hasattr(attr, '__doc__'): if isinstance(attr.__doc__, str): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) if name in ["__str__", "__hash__", "__repr__", "__len__"]: try: self.result = "{}".format(attr.__call__()) except: self.result = "skip call." else: # self.result = "{}".format(getattr(obj, name)) self.result = getattr(obj, name) def post(self, obj): if self.bOtherProperty and not self.result: try: self.result = getattr(obj, self.name) except: self.result = "skip call..." def apply_editor_property(self, obj, type_, rws, descript): self.bEditorProperty = True self.property_rw = "[{}]".format(rws) try: self.result = eval('obj.get_editor_property("{}")'.format(self.name)) except: self.result = "Invalid" def __str__(self): s = f"Attr: {self.name} paramStr: {self.param_str} desc: {self.return_type_str} result: {self.result}" if self.bProperty: s += ", Property" if self.bEditorProperty: s += ", Eidtor Property" if self.bOtherProperty: s += ", Other Property " if self.bCallable: s += ", Callable" if self.bCallable_builtin: s += ", Callable_builtin" if self.bCallable_other: s += ", bCallable_other" if self.bHasParamFunction: s+= ", bHasParamFunction" return s def check(self): counter = Counter([self.bOtherProperty, self.bEditorProperty, self.bCallable_other, self.bCallable_builtin]) # print("counter: {}".format(counter)) if counter[True] == 2: unreal.log_error(f"{self.name}: {self.bEditorProperty}, {self.bOtherProperty} {self.bCallable_builtin} {self.bCallable_other}") @property def bOtherProperty(self): if self.bProperty and not self.bEditorProperty: return True return False @property def bCallable_other(self): if self.bCallable and not self.bCallable_builtin: return True return False @property def display_name(self, bRichText=True): if self.bProperty: return f"\t{self.name}" else: # callable if self.param_str: return f"\t{self.name}({self.param_str}) {self.return_type_str}" else: if self.bCallable_other: return f"\t{self.name}" # __hash__, __class__, __eq__ 等 else: return f"\t{self.name}() {self.return_type_str}" @property def display_result(self) -> str: if self.bEditorProperty: return "{} {}".format(self.result, self.property_rw) else: return "{}".format(self.result) @property def bHasParamFunction(self): return self.param_str and len(self.param_str) != 0 def ll(obj): if not obj: return None if inspect.ismodule(obj): return None result = [] for x in dir(obj): attr = attr_detail(obj, x) result.append(attr) if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object): editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj) for name, type_, rws, descript in editorPropertiesInfos: # print(f"~~ {name} {type} {rws}, {descript}") index = -1 for i, v in enumerate(result): if v.name == name: index = i break if index != -1: this_attr = result[index] else: this_attr = attr_detail(obj, name) result.append(this_attr) # unreal.log_warning(f"Can't find editor property: {name}") this_attr.apply_editor_property(obj, type_, rws, descript) for i, attr in enumerate(result): attr.post(obj) return result def _simplifyDoc(content): def next_balanced(content, s="(", e = ")" ): s_pos = -1 e_pos = -1 balance = 0 for index, c in enumerate(content): match = c == s or c == e if not match: continue balance += 1 if c == s else -1 if c == s and balance == 1 and s_pos == -1: s_pos = index if c == e and balance == 0 and s_pos != -1 and e_pos == -1: e_pos = index return s_pos, e_pos return -1, -1 # bracketS, bracketE = content.find('('), content.find(')') if not content: return "", "" bracketS, bracketE = next_balanced(content, s='(', e = ')') arrow = content.find('->') funcDocPos = len(content) endSign = ['--', '\n', '\r'] for s in endSign: p = content.find(s) if p != -1 and p < funcDocPos: funcDocPos = p funcDoc = content[:funcDocPos] if bracketS != -1 and bracketE != -1: param = content[bracketS + 1: bracketE].strip() else: param = "" return funcDoc, param def _getEditorProperties(content, obj): # print("Content: {}".format(content)) lines = content.split('\r') signFound = False allInfoFound = False result = [] for line in lines: if not signFound and '**Editor Properties:**' in line: signFound = True if signFound: #todo re # nameS, nameE = line.find('``') + 2, line.find('`` ') nameS, nameE = line.find('- ``') + 4, line.find('`` ') if nameS == -1 or nameE == -1: continue typeS, typeE = line.find('(') + 1, line.find(')') if typeS == -1 or typeE == -1: continue rwS, rwE = line.find('[') + 1, line.find(']') if rwS == -1 or rwE == -1: continue name = line[nameS: nameE] type_str = line[typeS: typeE] rws = line[rwS: rwE] descript = line[rwE + 2:] allInfoFound = True result.append((name, type_str, rws, descript)) # print(name, type, rws) if signFound: if not allInfoFound: unreal.log_warning("not all info found {}".format(obj)) else: unreal.log_warning("can't find editor properties in {}".format(obj)) return result def log_classes(obj): print(obj) print("\ttype: {}".format(type(obj))) print("\tget_class: {}".format(obj.get_class())) if type(obj.get_class()) is unreal.BlueprintGeneratedClass: generatedClass = obj.get_class() else: generatedClass = unreal.PythonBPLib.get_blueprint_generated_class(obj) print("\tgeneratedClass: {}".format(generatedClass)) print("\tbp_class_hierarchy_package: {}".format(unreal.PythonBPLib.get_bp_class_hierarchy_package(generatedClass))) def is_selected_asset_type(types): selectedAssets = Utilities.Utils.get_selected_assets() for asset in selectedAssets: if type(asset) in types: return True; return False
from typing import List, Dict, Set import unreal class ColumnHandler: def __init__(self, table_name): self.table_name = table_name self.required_columns = [] self.handled_columns = set() def set_required_columns(self, columns): self.required_columns = columns self.handled_columns.update(columns) def add_handled_columns(self, columns): self.handled_columns.update(columns) def process_columns(self, data): if not data: return {'success': False, 'message': '데이터가 비어있습니다.'} # 데이터의 컬럼 목록 가져오기 columns = data[0].keys() if data else [] # 필수 컬럼 체크 missing_columns = [col for col in self.required_columns if col not in columns] if missing_columns: message = f"{self.table_name} 시트에서 다음 필수 컬럼이 누락되었습니다:\n" message += "\n".join([f"- {col}" for col in missing_columns]) return {'success': False, 'message': message} # 처리되지 않는 컬럼 체크 unhandled_columns = [col for col in columns if col not in self.handled_columns] if unhandled_columns: print(f"경고: {self.table_name} 시트에서 다음 컬럼은 처리되지 않습니다:") print("\n".join([f"- {col}" for col in unhandled_columns])) return {'success': True, 'message': ''} def add_handled_column(self, column: str): """처리된 컬럼 추가""" self.handled_columns.add(column) def add_handled_columns(self, columns: List[str]): """여러 처리된 컬럼 추가""" self.handled_columns.update(columns)
import unreal import math import json import pprint import datetime import os import csv import uuid from enum import Enum from typing import Any, List, Optional, Dict, TypeVar, Type, Callable, cast def load_csv(file_path): grid = [] with open(file_path, 'r') as file: reader = csv.reader(file) for row in reader: grid_row = [] for cell in row: if cell.strip() == '': grid_row.append(0) else: grid_row.append(int(cell)) grid.append(grid_row) return grid def create_collision(actor: unreal.PaperSpriteActor, x, y, tile_size): initial_children_count = actor.root_component.get_num_children_components() subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) root_data_handle = subsystem.k2_gather_subobject_data_for_instance(actor)[0] collision_component = unreal.BoxComponent() sub_handle, _ = subsystem.add_new_subobject(params=unreal.AddNewSubobjectParams(parent_handle=root_data_handle, new_class=collision_component.get_class())) subsystem.rename_subobject(handle=sub_handle, new_name=unreal.Text(f"LDTK_Collision_{uuid.uuid4()}")) new_component: unreal.BoxComponent = actor.root_component.get_child_component(initial_children_count) new_component.set_box_extent(unreal.Vector(tile_size / 2, tile_size / 2, 64)) new_component.set_relative_location_and_rotation(unreal.Vector((x + (tile_size / 2)), -32, -(y + (tile_size / 2))), unreal.Rotator(90, 0, 0),False, False) new_component.set_collision_profile_name("BlockAll") def spawn_collisions_from_grid(grid, actor: unreal.PaperSpriteActor, composite_width, composite_height): tile_size = 16 for row_index, row in enumerate(grid): for col_index, cell in enumerate(row): x = (col_index * tile_size) - (composite_width / 2) y = row_index * tile_size - (composite_height / 2) if cell == 1: create_collision(actor, x, y, tile_size) def find_all_subfolders(path): subfolders = [] for root, dirs, files in os.walk(path): for dir in dirs: subfolders.append(os.path.join(root, dir)) return subfolders DirectoryContents = Dict[str, Dict[str, Any]] def get_directory_contents(path: str) -> dict: directory_contents = {} for root, _, files in os.walk(path): root = os.path.normpath(root) filtered_files = [file for file in files if file.endswith(('_bg.png', '_composite.png', 'Bg_textures.png', 'Collisions.csv', 'Collisions.png', 'Collisions-int.png', 'data.json', 'Wall_shadows.png'))] if filtered_files: directory_contents[root] = {file: None for file in filtered_files} return directory_contents def importWorld(folder_name: str): level_files_location = "LdtkFiles/simplified" base_directory = "/Game" ldtk_files_directory = "LdtkFiles" ldtk_simplified_directory = "simplified" composite_filename = "_composite" data_filename = "data.json" collisions_filename = "Collisions.csv" if len(str(folder_name)) == 0: print("Unreal LDtk: No folder name provided. Exiting...") return else: folder_name = str(folder_name) base_path = os.path.join(base_directory, ldtk_files_directory, folder_name, ldtk_simplified_directory) content_directory = unreal.Paths.project_content_dir() level_directory = os.path.join(content_directory, ldtk_files_directory, folder_name, ldtk_simplified_directory).replace("\\", "/") directories = find_all_subfolders(level_directory) if directories.__len__() > 0: print(f"Unreal LDtk: Found {len(directories)} directories in {level_directory}. Beginning import...") else: print(f"Unreal LDtk: No directories found in {level_directory}. \nThis might be because you are missing the LdtkFiles directory, or that the folder level name is wrong. Exiting...") return entity_index_counter = 0 for index, directory in enumerate(directories): _, directory_name = os.path.split(directory) full_path_composite = os.path.join(base_path, directory_name, composite_filename) full_path_data = os.path.join(level_directory, directory_name, data_filename).replace("\\", "/") full_path_collisions = os.path.join(level_directory, directory_name, collisions_filename).replace("\\", "/") composite_exists = unreal.EditorAssetLibrary.does_asset_exist(full_path_composite) data_exists = os.path.exists(full_path_data) collisions_exists = os.path.exists(full_path_collisions) ## Creating Sprite ## if composite_exists: composite_texture = load_texture_asset(full_path_composite) composite_sprite = create_sprite_from_texture(composite_texture, directory_name) else: print(f"Unreal LDtk: Missing composite texture asset, skipping...") ## Reading JSON file ## if data_exists: data_file = open(full_path_data) data = json.load(data_file) data_file.close() composite_spawn_coords = (data['x'] + (data['width'] / 2), data['y'] + (data['height'] / 2), 0) else: print(f"Unreal LDtk: Missing data.json file, skipping...") if (composite_exists and data_exists): spawned_composite_actor = spawn_sprite_in_world(composite_sprite, (composite_spawn_coords)) ## Spawning Entities ## for _, entities in data['entities'].items(): for index, entity in enumerate(entities): spawn_entity_in_world(f"LDtk_{entity['id']}_{entity_index_counter}", data['x'] + entity['x'], data['y'] + entity['y']) entity_index_counter += 1 else: print(f"Unreal LDtk: Missing composite and/or data.json file, skipping entities...") ## Spawning Collisions ## if composite_exists and collisions_exists: grid = load_csv(full_path_collisions) spawn_collisions_from_grid(grid, spawned_composite_actor, data['width'], data['height']) else: print(f"Unreal LDtk: Missing Composite and/or Collisions.csv file, skipping collisions...") def check_and_delete_existing_sprite(sprite_name): sprite_path = "/project/" + sprite_name all_actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in all_actors: if actor.get_actor_label() == sprite_name: unreal.EditorLevelLibrary.destroy_actor(actor) print(f"Deleting existing composite sprite: {actor}") break if unreal.EditorAssetLibrary.does_asset_exist(sprite_path): unreal.EditorAssetLibrary.delete_asset(sprite_path) def check_and_delete_existing_entity(entity_name): all_actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in all_actors: if actor.get_actor_label() == entity_name: unreal.EditorLevelLibrary.destroy_actor(actor) print(f"Deleting existing entity: {actor}") break def load_texture_asset(texture_path): texture = unreal.EditorAssetLibrary.load_asset(texture_path) return texture def create_sprite_from_texture(texture_asset: unreal.PaperSprite, world_name): try: sprite_path = "/project/" sprite_name = f"LDtk_{world_name}_{texture_asset.get_name()}_sprite" check_and_delete_existing_sprite(sprite_name=sprite_name) sprite_package = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=sprite_name, package_path=sprite_path, asset_class=unreal.PaperSprite, factory=unreal.PaperSpriteFactory()) sprite_package.set_editor_property("source_texture", texture_asset) print("Sprite saved at: ", sprite_path) return sprite_package except: pass def spawn_entity_in_world(name, x, y): location = unreal.Vector(x, 1, -y) check_and_delete_existing_entity(name) actor: unreal.Actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.Actor().get_class(), location) if actor: actor.set_actor_label(name) print(f"Spawning entity: {actor.get_actor_label()}") return actor def spawn_sprite_in_world(sprite, location=(0, 0, 0), scale=(1, 1, 1)): spawn_location = unreal.Vector(location[0], location[2], -location[1]) scale_vector = unreal.Vector(scale[0], scale[1], scale[2]) actor_transform = unreal.Transform(spawn_location, unreal.Rotator(0, 0, 0), scale_vector) actor = unreal.EditorLevelLibrary.spawn_actor_from_object(sprite, spawn_location) if actor: sprite_component = actor.render_component if sprite_component: sprite_component.set_sprite(sprite) actor.set_actor_scale3d(scale_vector) actor.set_actor_transform(actor_transform, False, True) print(f"Spawning composite sprite: {actor.get_actor_label()}") return actor return None #noinspection PyUnresolvedReferences importWorld(folder_name) #noinspection PyUnresolvedReferences print(datetime.datetime.now())
import unreal # instances of unreal classes editor_level_lib = unreal.EditorLevelLibrary() editor_filter_lib = unreal.EditorFilterLibrary() # get all actors and then filter them by class or name actors = editor_level_lib.get_all_level_actors() static_meshes = editor_filter_lib.by_class(actors, unreal.StaticMeshActor) blueprints = editor_filter_lib.by_id_name(actors, "BP_") #extra classes could be added here count = 0 # create a mapping between folder names and actors mapping = { "StaticMeshes": static_meshes, "Blueprints": blueprints #Extra Items could be added here } for folder in mapping: # Loop through each actor and place them in folders for actor in mapping[folder]: actor_name = actor.get_fname() actor.set_folder_path(folder) unreal.log("Moved {} into {}".format(actor_name, folder)) count += 1 unreal.log("Moved {} actors moved".format(count))
# Copyright Epic Games, Inc. All Rights Reserved. import unreal # This example is an implementation of an "executor" which is responsible for # deciding how a queue is rendered, giving you complete control over the before, # during, and after of each render. # # This class is an example of how to make an executor which processes a job in a standalone executable launched with "-game". # You can follow this example to either do a simple integration (read arguments from the command line as suggested here), # or it can used to implement an advanced plugin which opens a socket or makes REST requests to a server to find out what # work it should do, such as for a render farm implementation. # # We're building a UClass implementation in Python. This allows the Python to # integrate into the system in a much more intuitive way but comes with some # restrictions: # Python classes cannot be serialized. This is okay for executors because they are # created for each run and are not saved into assets, but means that you cannot # implement a settings class as those do need to get saved into preset assets. # All class properties must be UProperties. This means you cannot use native # Python sockets. # # This class must inherit from unreal.MoviePipelinePythonHostExecutor. This class also # provides some basic socket and async http request functionality as a workaround for no # native Python member variables. # # If you are trying to write your own executor based on this example, you will need to create # a /project/ folder and place the custom python file within that folder. Then you will need # to create an "init_unreal.py" file within that folder and add "import <YourPyModuleName>" to it # so that Unreal will attempt to parse the class on engine load and it can be spawned by MRQ. # If your Python file is named MyExecutorWithExtraFeatures.py, then you would add # # import MyExecutorWithExtraFeatures # # to your init_unreal.py file. # # REQUIREMENTS: # Requires the "Python Editor Script Plugin" to be enabled in your project. # # USAGE: # Use the following command line argument to launch this: # UnrealEditor-Cmd.exe <path_to_uproject> <map_name> -game -MoviePipelineLocalExecutorClass=/project/.MoviePipelinePythonHostExecutor -ExecutorPythonClass=/project/.MoviePipelineExampleRuntimeExecutor -LevelSequence=<path_to_level_sequence> -windowed -resx=1280 -resy=720 -log # ie: # UnrealEditor-Cmd.exe "/project/.uproject" subwaySequencer_P -game -MoviePipelineLocalExecutorClass=/project/.MoviePipelinePythonHostExecutor -ExecutorPythonClass=/project/.MoviePipelineExampleRuntimeExecutor -LevelSequence="/project/.SubwaySequencerMASTER" -windowed -resx=1280 -resy=720 -log # # If you are looking for how to render in-editor using Python, see the MoviePipelineEditorExample.py script instead. @unreal.uclass() class MoviePipelineExampleRuntimeExecutor(unreal.MoviePipelinePythonHostExecutor): # Declare the properties of the class here. You can use basic # Python types (int, str, bool) as well as unreal properties. # You can use Arrays and Maps (Dictionaries) as well activeMoviePipeline = unreal.uproperty(unreal.MoviePipeline) exampleArray = unreal.Array(str) # An array of strings exampleDict = unreal.Map(str, bool) # A dictionary of strings to bools. # Constructor that gets called when created either via C++ or Python # Note that this is different than the standard __init__ function of Python def _post_init(self): # Assign default values to properties in the constructor self.activeMoviePipeline = None self.exampleArray.append("Example String") self.exampleDict["ExampleKey"] = True # Register a listener for socket messages and http messages (unused in this example # but shown here as an example) self.socket_message_recieved_delegate.add_function_unique(self, "on_socket_message"); self.http_response_recieved_delegate.add_function_unique(self, "on_http_response_recieved") # We can override specific UFunctions declared on the base class with # this markup. @unreal.ufunction(override=True) def execute_delayed(self, inPipelineQueue): # This function is called once the map has finished loading and the # executor is instantiated. If you needed to retrieve data from some # other system via a REST api or Socket connection you could do that here. for x in range(0, 25): unreal.log_error("This script is meant as an example to build your own and is not meant to be run on its own. Please read the source code (/project/.py) for details on how to make your own. This example automatically overrides various settings on jobs to serve as an example for how to do that in your own script if needed.") # If your executor needs to make async HTTP calls (such as fetching the value from a third party management library) # you can do that with the following code: # newIndex is a unique index for each send_http_request call that you can store # and retrieve in the on_http_response_recieved function to match the return back # up to the original intent. # newIndex = self.send_http_request("https://google.com", "GET", "", unreal.Map(str, str)) # If your executor wants to make TCP socket connections to send data back and forth with a third party software, # you can do that with the following code: # Here's an example of how to open a TCP socket connection. This example # doesn't need one, but is shown here in the event you wish to build a more # in depth integration into render farm software. #socketConnected = self.connect_socket("127.0.0.1", 6783) #if socketConnected == True: # # Send back a polite hello world message! It will be sent over the socket # # with a 4 byte size prefix so you know how many bytes to expect before # # the message is complete. # self.send_socket_message("Hello World!") #else: # unreal.log_warning("This is an example warning for when a socket fails to connect.") # Here's how we can scan the command line for any additional args such as the path to a level sequence. (cmdTokens, cmdSwitches, cmdParameters) = unreal.SystemLibrary.parse_command_line(unreal.SystemLibrary.get_command_line()) levelSequencePath = None try: levelSequencePath = cmdParameters['LevelSequence'] except: unreal.log_error("Missing '-LevelSequence=/project/.MySequence' argument") self.on_executor_errored() return # A movie pipeline needs to be initialized with a job, and a job # should be owned by a Queue so we will construct a queue, make one job # and then configure the settings on the job. If you want inPipelineQueue to be # valid, then you must pass a path to a queue asset via -MoviePipelineConfig. Here # we just make one from scratch with the one level sequence as we didn't implement # multi-job handling. self.pipelineQueue = unreal.new_object(unreal.MoviePipelineQueue, outer=self); unreal.log("Building Queue...") # Allocate a job. Jobs hold which sequence to render and what settings to render with. newJob = self.pipelineQueue.allocate_new_job(unreal.MoviePipelineExecutorJob) newJob.sequence = unreal.SoftObjectPath(levelSequencePath) # Now we can configure the job. Calling find_or_add_setting_by_class is how you add new settings. outputSetting = newJob.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting) outputSetting.output_resolution = unreal.IntPoint(1280, 720) outputSetting.file_name_format = "{sequence_name}.{frame_number}" # Ensure there is something to render newJob.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineDeferredPassBase) # Ensure there's a file output. newJob.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineImageSequenceOutput_PNG) # This is important. There are several settings that need to be # initialized (just so their default values kick in) and instead # of requiring you to add every one individually, you can initialize # them all in one go at the end. newJob.get_configuration().initialize_transient_settings() # Now that we've set up the minimum requirements on the job we can created # a movie render pipeline to run our job. Construct the new object self.activeMoviePipeline = unreal.new_object(self.target_pipeline_class, outer=self.get_last_loaded_world(), base_type=unreal.MoviePipeline); # Register to any callbacks we want self.activeMoviePipeline.on_movie_pipeline_work_finished_delegate.add_function_unique(self, "on_movie_pipeline_finished") # And finally tell it to start working. It will continue working # and then call the on_movie_pipeline_finished_delegate function at the end. self.activeMoviePipeline.initialize(newJob) # This function is called every frame and can be used to do simple countdowns, checks # for more work, etc. Can be entirely omitted if you don't need it. @unreal.ufunction(override=True) def on_begin_frame(self): # It is important that we call the super so that async socket messages get processed. super(MoviePipelineExampleRuntimeExecutor, self).on_begin_frame() if self.activeMoviePipeline: unreal.log("Progress: %f" % unreal.MoviePipelineLibrary.get_completion_percentage(self.activeMoviePipeline)) # This is NOT called for the very first map load (as that is done before Execute is called). # This means you can assume this is the resulting callback for the last open_level call. @unreal.ufunction(override=True) def on_map_load(self, inWorld): # We don't do anything here, but if you were processing a queue and needed to load a map # to render a job, you could call: # # unreal.GameplayStatics.open_level(self.get_last_loaded_world(), mapPackagePath, True, gameOverrideClassPath) # # And then know you can continue execution once this function is called. The Executor # lives outside of a map so it can persist state across map loads. # Don't call open_level from this function as it will lead to an infinite loop. pass # This needs to be overriden. Doens't have any meaning in runtime executors, only # controls whether or not the Render (Local) / Render (Remote) buttons are locked # in Editor executors. @unreal.ufunction(override=True) def is_rendering(self): return False # This declares a new UFunction and specifies the return type and the parameter types # callbacks for delegates need to be marked as UFunctions. @unreal.ufunction(ret=None, params=[unreal.MoviePipelineOutputData]) def on_movie_pipeline_finished(self, results): # We're not processing a whole queue, only a single job so we can # just assume we've reached the end. If your queue had more than # one job, now would be the time to increment the index of which # job you are working on, and start the next one (instead of calling # on_executor_finished_impl which should be the end of the whole queue) unreal.log("Finished rendering movie! Success: " + str(results.success)) self.activeMoviePipeline = None self.on_executor_finished_impl() @unreal.ufunction(ret=None, params=[str]) def on_socket_message(self, message): # Message is a UTF8 encoded string. The system expects # messages to be sent over a socket with a uint32 to describe # the message size (not including the size bytes) so # if you wanted to send "Hello" you would send # uint32 - 5 # uint8 - 'H' # uint8 - 'e' # etc. # Socket messages sent from the Executor will also be prefixed with a size. pass @unreal.ufunction(ret=None, params=[int, int, str]) def on_http_response_recieved(self, inRequestIndex, inResponseCode, inMessage): # This is called when an http response is returned from a request. # the request index will match the value returned when you made the original # call, so you can determine the original intent this response is for. pass
import unreal def spawn_coverage_actor(): # Percorso della Blueprint Class di CoverageActor blueprint_path = '/project/.CoverageActor_C' # Carica la Blueprint Class blueprint_class = unreal.load_asset(blueprint_path) if not blueprint_class: unreal.log_error(f"Blueprint class '{blueprint_path}' non trovata.") return False # Ottieni il mondo dell'editor editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) world = editor_subsystem.get_editor_world() # Controlla se un attore di questo tipo è già presente nella scena actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: if actor.get_class() == blueprint_class: unreal.log("Coverage Actor esiste già nella scena.") 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(blueprint_class, actor_location, actor_rotation) if not actor: unreal.log_error("Attore non è stato creato.") return False unreal.log("Coverage Actor creato con successo.") return True # Esegui la funzione per piazzare l'attore spawn_coverage_actor()
import unreal levelTools = unreal.Level editorLevelLibrary = unreal.EditorLevelLibrary levelSubSys = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) #levelTools = unreal.level #innit new level newLevel = "myNewLevel" #create new level myNewLevel = levelSubSys.new_level("/project/") #set level as current level levelSubSys.set_current_level_by_name(newLevel) #save level levelSubSys.save_current_level()
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal workingPath = "/Game/" @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass editorAssetLib = GetEditorAssetLibrary() allAssets = editorAssetLib.list_assets(workingPath, True, False) allAssetsCount = len(allAssets) selectedAssetPath = workingPath with unreal.ScopedSlowTask(allAssetsCount, selectedAssetPath) as slowTask: slowTask.make_dialog(True) for asset in allAssets: _assetData = editorAssetLib.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() _targetPathName = "/Game/%s%s%s%s%s" % (_assetClassName, "/", _assetName, ".", _assetName) editorAssetLib.rename_asset(_assetPathName, _targetPathName) if slowTask.should_cancel(): break slowTask.enter_progress_frame(1, asset)
# Copyright Epic Games, Inc. All Rights Reserved """ General Deadline utility functions """ # Built-in from copy import deepcopy import json import re import unreal def format_job_info_json_string(json_string, exclude_aux_files=False): """ Deadline Data asset returns a json string, load the string and format the job info in a dictionary :param str json_string: Json string from deadline preset struct :param bool exclude_aux_files: Excludes the aux files from the returned job info dictionary if True :return: job Info dictionary """ if not json_string: raise RuntimeError(f"Expected json string value but got `{json_string}`") job_info = {} try: intermediate_info = json.loads(json_string) except Exception as err: raise RuntimeError(f"An error occurred formatting the Job Info string. \n\t{err}") project_settings = unreal.get_default_object(unreal.DeadlineServiceEditorSettings) script_category_mappings = project_settings.script_category_mappings # The json string keys are camelCased keys which are not the expected input # types for Deadline. Format the keys to PascalCase. for key, value in intermediate_info.items(): # Remove empty values if not value: continue # Deadline does not support native boolean so make it a string if isinstance(value, bool): value = str(value).lower() pascal_case_key = re.sub("(^\S)", lambda string: string.group(1).upper(), key) if (pascal_case_key == "AuxFiles") and not exclude_aux_files: # The returned json string lists AuxFiles as a list of # Dictionaries but the expected value is a list of # strings. reformat this input into the expected value aux_files = [] for files in value: aux_files.append(files["filePath"]) job_info[pascal_case_key] = aux_files continue # Extra option that can be set on the job info are packed inside a # ExtraJobOptions key in the json string. # Extract this is and add it as a flat setting in the job info elif pascal_case_key == "ExtraJobOptions": job_info.update(value) continue # Resolve the job script paths to be sent to be sent to the farm. elif pascal_case_key in ["PreJobScript", "PostJobScript", "PreTaskScript", "PostTaskScript"]: # The path mappings in the project settings are a dictionary # type with the script category as a named path for specifying # the root directory of a particular script. The User interface # exposes the category which is what's in the json string. We # will use this category to look up the actual path mappings in # the project settings. script_category = intermediate_info[key]["scriptCategory"] script_name = intermediate_info[key]["scriptName"] if script_category and script_name: job_info[pascal_case_key] = f"{script_category_mappings[script_category]}/{script_name}" continue # Environment variables for Deadline are numbered key value pairs in # the form EnvironmentKeyValue#. # Conform the Env settings to the expected Deadline configuration elif (pascal_case_key == "EnvironmentKeyValue") and value: for index, (env_key, env_value) in enumerate(value.items()): job_info[f"EnvironmentKeyValue{index}"] = f"{env_key}={env_value}" continue # ExtraInfoKeyValue for Deadline are numbered key value pairs in the # form ExtraInfoKeyValue#. # Conform the setting to the expected Deadline configuration elif (pascal_case_key == "ExtraInfoKeyValue") and value: for index, (env_key, env_value) in enumerate(value.items()): job_info[f"ExtraInfoKeyValue{index}"] = f"{env_key}={env_value}" continue else: # Set the rest of the functions job_info[pascal_case_key] = value # Remove our custom representation of Environment and ExtraInfo Key value # pairs from the dictionary as the expectation is that these have been # conformed to deadline's expected key value representation for key in ["EnvironmentKeyValue", "ExtraInfoKeyValue"]: job_info.pop(key, None) return job_info def format_plugin_info_json_string(json_string): """ Deadline Data asset returns a json string, load the string and format the plugin info in a dictionary :param str json_string: Json string from deadline preset struct :return: job Info dictionary """ if not json_string: raise RuntimeError(f"Expected json string value but got `{json_string}`") plugin_info = {} try: info = json.loads(json_string) plugin_info = info["pluginInfo"] except Exception as err: raise RuntimeError(f"An error occurred formatting the Plugin Info string. \n\t{err}") # The plugin info is listed under the `plugin_info` key. # The json string keys are camelCased on struct conversion to json. return plugin_info def get_deadline_info_from_preset(job_preset=None, job_preset_struct=None): """ This method returns the job info and plugin info from a deadline preset :param unreal.DeadlineJobPreset job_preset: Deadline preset asset :param unreal.DeadlineJobPresetStruct job_preset_struct: The job info and plugin info in the job preset :return: Returns a tuple with the job info and plugin info dictionary :rtype: Tuple """ job_info = {} plugin_info = {} preset_struct = None # TODO: Make sure the preset library is a loaded asset if job_preset is not None: preset_struct = job_preset.job_preset_struct if job_preset_struct is not None: preset_struct = job_preset_struct if preset_struct: # Get the Job Info and plugin Info try: job_info = dict(unreal.DeadlineServiceEditorHelpers.get_deadline_job_info(preset_struct)) plugin_info = dict(unreal.DeadlineServiceEditorHelpers.get_deadline_plugin_info(preset_struct)) # Fail the submission if any errors occur except Exception as err: unreal.log_error( f"Error occurred getting deadline job and plugin details. \n\tError: {err}" ) raise return job_info, plugin_info def merge_dictionaries(first_dictionary, second_dictionary): """ This method merges two dictionaries and returns a new dictionary as a merger between the two :param dict first_dictionary: The first dictionary :param dict second_dictionary: The new dictionary to merge in :return: A new dictionary based on a merger of the input dictionaries :rtype: dict """ # Make sure we do not overwrite our input dictionary output_dictionary = deepcopy(first_dictionary) for key in second_dictionary: if isinstance(second_dictionary[key], dict): if key not in output_dictionary: output_dictionary[key] = {} output_dictionary[key] = merge_dictionaries(output_dictionary[key], second_dictionary[key]) else: output_dictionary[key] = second_dictionary[key] return output_dictionary def get_editor_deadline_globals(): """ Get global storage that will persist for the duration of the current interpreter/process. .. tip:: Please namespace or otherwise ensure unique naming of any data stored into this dictionary, as key clashes are not handled/safety checked. :return: Global storage :rtype: dict """ import __main__ try: return __main__.__editor_deadline_globals__ except AttributeError: __main__.__editor_deadline_globals__ = {} return __main__.__editor_deadline_globals__
from typing import Dict, Any import unreal import json def get_map_info() -> Dict[str, Any]: world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() if not world: return {"error": "No world loaded"} map_info = {} map_info["map_name"] = world.get_name() map_info["map_path"] = world.get_path_name() all_actors = unreal.get_editor_subsystem( unreal.EditorActorSubsystem ).get_all_level_actors() map_info["total_actors"] = len(all_actors) actor_types = {} for actor in all_actors: actor_class = actor.get_class().get_name() actor_types[actor_class] = actor_types.get(actor_class, 0) + 1 map_info["actor_types"] = dict( sorted(actor_types.items(), key=lambda x: x[1], reverse=True)[:15] ) lighting_info = {} lighting_info["has_lightmass_importance_volume"] = any( actor.get_class().get_name() == "LightmassImportanceVolume" for actor in all_actors ) lighting_info["directional_lights"] = sum( 1 for actor in all_actors if actor.get_class().get_name() == "DirectionalLight" ) lighting_info["point_lights"] = sum( 1 for actor in all_actors if actor.get_class().get_name() == "PointLight" ) lighting_info["spot_lights"] = sum( 1 for actor in all_actors if actor.get_class().get_name() == "SpotLight" ) map_info["lighting"] = lighting_info try: streaming_levels = unreal.EditorLevelLibrary.get_all_level_actors_of_class( unreal.LevelStreamingDynamic ) map_info["streaming_levels"] = len(streaming_levels) map_info["streaming_level_names"] = [ level.get_name() for level in streaming_levels ] except Exception: map_info["streaming_levels"] = 0 map_info["streaming_level_names"] = [] return map_info def main(): map_data = get_map_info() print(json.dumps(map_data, indent=2)) if __name__ == "__main__": main()
# 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)
# from wrmd_sim.wrmd_similarity import find_dist # import speech_recognition as sr # flag = 1 # while (flag): # r = sr.Recognizer() # with sr.Microphone() as source: # r.adjust_for_ambient_noise(source) # print("Please say something") # audio = r.listen(source) # print("Recognizing Now .... ") # # recognize speech using google # try: # print("\nYou have said: \n" + r.recognize_google(audio) + "\n") # user_input = input("Press\n- 0, if this is incorrec/project/- 1, if this is correct ") # if int(user_input) == 0: # flag = 1 # elif int(user_input) == 1: # flag = 0 # except Exception as e: # print("Error : " + str(e)) # # write audio # with open("recorded.wav", "wb") as f: # f.write(audio.get_wav_data()) import unreal import sng_parser import re from sentence_transformers import SentenceTransformer, util import torch from rdflib.namespace import FOAF, XMLNS, XSD, RDF, RDFS, OWL import rdflib.plugins.sparql as sparql from rdflib import Graph, URIRef, Literal, BNode, Namespace import networkx as nx import matplotlib.pyplot as plt import sng_parser populated_kg_path = "/project/.ttl" # Update KG of assets ################################################# import os import json # find if directory is '../Megascans Library/project/' or '../Megascans Library/UAssets' path_to_files = '/project/' from rdflib import Graph, URIRef, Literal, BNode, Namespace from rdflib.namespace import FOAF, XMLNS, XSD, RDF, RDFS, OWL import os g = Graph() g.parse(populated_kg_path, format = "ttl") n = Namespace("http://www.semanticweb.org/project/-assets-ontology#") # find if directory is '../Megascans Library/project/' or '../Megascans Library/UAssets' def trigger_update(folder_path): # g = Graph() # g.parse('Populated_Assets_KG.ttl', format = "ttl") # n = Namespace("http://www.semanticweb.org/project/-assets-ontology#") qres = g.query( """ PREFIX mega:<http://www.semanticweb.org/project/-assets-ontology#> SELECT ?s ?aID ?aName WHERE { ?s mega:assetID ?aID. ?s mega:assetName ?aName. FILTER BOUND(?aID) }""") cur_KG_assets = set() for row in qres: # check asset IDs currently loaded in the assets' KG - they have IDs same as their folder and json file names cur_KG_assets.add(row.aID.toPython()) cur_KG_assets = list(cur_KG_assets) # cur_dir = os.chdir(folder_path) # Get list of all asset folder names, then iteratively go through them. saved_folders = os.listdir(folder_path) saved_asset_paths = dict() # sf = asset folder name # sf - also asset ID for sf in saved_folders: try: if len(os.listdir(str(folder_path)+str(sf))) != 0 and str(sf)+'.json' in os.listdir(str(folder_path)+str(sf)+'/'): saved_asset_paths[sf] = str(folder_path)+str(sf)+'/'+str(sf)+'.json' except Exception as e: if str(e).find('NotADirectoryError') != -1: print("Actual error:", e) print("Paths for assets in file system: ", saved_asset_paths) new_paths_dict = dict() for key,value in saved_asset_paths.items(): if key not in cur_KG_assets: new_paths_dict[key] = value print("Assets not yet added to KG:", new_paths_dict) return new_paths_dict def update_KG(new_files_paths): print("New files path: ", new_files_paths,' ', len(new_files_paths)) # correct n = Namespace("http://www.semanticweb.org/project/-assets-ontology#") # json_files = [pos_json for pos_json in os.listdir( # new_files_paths) if pos_json.endswith('.json')] json_files = list(new_files_paths.values()) for fil in json_files: # Open asset file try: f = open(fil) data = json.load(f) # json file loaded as dictionary # Create asset and set asset name # obtain name of asset, convert it to RDF format literal name = data["name"] name_processed = re.sub("[^a-zA-Z0-9]", "_", name) # print("Created asset name = ", name) print(name_processed) # create a resource in the Assets Knowledge Graph (KG) asset = URIRef(str(n)+"Asset_"+name_processed) # print("Asset = ", asset) g.add((asset, RDF.type, n.Asset)) # Add triple to KG: {new Asset resource, nameRelation (from schema), name obtained from asset file} g.add((asset, n.assetName, Literal(name, datatype=XSD.string))) try: # Set asset ID id = Literal(str(data["id"]), datatype=XSD.string) g.add((asset, n.assetID, id)) print("Added assetID = ", id) except: print("No asset ID specified for asset", asset) try: # Set asset search tags tags = data["tags"] # print("number of tags = ", len(tags)) for t in tags: tag = Literal(str(t), datatype=XSD.string) g.add((asset, n.assetTag, tag)) # print("Added tag = ", tag) except: print("No search tags specified for asset", asset) try: # Create category individuals and set their names, then assign asset categories categories = data["categories"] # print("number of categories = ", len(categories)) for c in categories: category = Literal(c, datatype=XSD.string) g.add((asset, n.assetCategory, category)) # print("Adding category = ", category) except: print("No categories specified for asset", asset) properties = data["properties"] # print("number of properties = ", len(properties)) for prop in properties: key = list(prop.keys())[0] value = list(prop.values())[0] # print("prop['key'] = ", prop["key"]) # print("prop['value'] = ", prop["value"]) try: properties = data["properties"] # print("number of properties = ", len(properties)) for prop in properties: key = list(prop.keys())[0] value = list(prop.values())[0] # print("prop['key'] = ", prop["key"]) # print("prop['value'] = ", prop["value"]) # print("prop key = ", key) if prop["key"] == "size": # print(value, Literal(value)) if prop["value"] == "tiny": g.add((asset, n.assetSize, n.tiny)) # print("Added asset size = ", n.tiny) elif prop["value"] == "small": g.add((asset, n.assetSize, n.small)) # print("Added asset size = ", n.small) elif prop["value"] == "medium": g.add((asset, n.assetSize, n.medium)) # print("Added asset size = ", n.medium) elif prop["value"] == "large": g.add((asset, n.assetSize, n.large)) # print("Added asset size = ", n.large) else: g.add((asset, n.assetSize, n.extra_large)) # print("Added asset size = ", n.extra_large) elif prop["key"] == "age": age = Literal(prop["value"], datatype=XSD.string) g.add((asset, n.assetAge, age)) # print("Added asset age = ", age) except: print("No properties specified for asset", asset) try: # Set asset average color avg_color = Literal(str(data["averageColor"]), datatype=XSD.string) g.add((asset, n.assetAvgColor, avg_color)) # print("Added asset average color = ", avg_color) except: print("No asset avg color specified for asset", asset) print(len(g)) f.close() except Exception as e: print('Update error: ', e) g.serialize(destination='Populated_Assets_KG.ttl', format='turtle') ################################################# def find_dist_cosine(sen_a, sen_b): return util.cos_sim(sen_a, sen_b) def sub_closest_prep(preposition): # above prep_list = [ "on","back","front","right","left","behind","beneath","in","over","under","besides"] min_dist = -1000 target_prep = "" for candidate in prep_list: dist = find_dist_cosine(create_embedding_tensor(candidate), create_embedding_tensor(preposition)) if dist > min_dist: min_dist = dist target_prep = ""+candidate print("Closest preposition for ", preposition, " is ", target_prep) return target_prep def find_dist(sen_a, sen_b, model_name): loaded_model = FastText.load(model_name) wv = loaded_model.wv distance = wv.wmdistance(sen_a, sen_b) # print(f"Word Movers Distance is {distance} (lower means closer)") return distance N_id = 1 jar_path = 'stanford-corenlp-4.5.1/stanford-corenlp-4.5.1.jar' models_jar_path = 'stanford-corenlp-4.5.1/stanford-corenlp-4.5.1-models.jar' def formatAssetWriting(entity_asset_tuple, subject_all_objects_dict): formattedDict = dict() # In the new dict, store in subject_all_objects_dict values, but format its keys to # AssetName_AssetID (entity_asset_dict.keys) +_+<entityID> (subject_all_objects_dict.keys) # Compare - from subject_all_objects_dict, remove from keys and value tuples, everything after & including the last '_' # - replace remaining keys & values in subject_all_objects_dict with values of keys that match with them # EXAMPLE # Entity Asset Dictionary: # {'Cow': 'Wooden_Chair_uknkaffaw', 'sidewalk': 'Brick_Wall_vgvmcgf', 'city area': 'Brick_Wall_vgvmcgf', 'shops': 'Wooden_Chair_uknkaffaw'} # All Subject-Objects Dictionary: # {'Cow_0': [('on', 'sidewalk_1'), ('in', 'city area_2')], 'city area_2': [('near', 'shops_3')]} # RESULT # {'Wooden_Chair_uknkaffaw_0': [('on', 'Brick_Wall_vgvmcgf_1'), ('in', 'Brick_Wall_vgvmcgf_2')], 'Brick_Wall_vgvmcgf_2': [('near', 'Wooden_Chair_uknkaffaw_3')]} for k, v in subject_all_objects_dict.items(): formattedKey = k formattedVal = v # print("Entity Asset Dic/project/", entity_asset_dict) # if 'Cow_0'.repl # if k[:k.rfind('_')] in list(entity_asset_dict.keys()): if k[:k.rfind('_')] == entity_asset_tuple[0]: print('entity_asset_tuple:', entity_asset_tuple[2].replace( ' ', '_') + '_' + entity_asset_tuple[1] + k[k.rfind('_'):]) formattedKey = entity_asset_tuple[2].replace( ' ', '_') + '_' + entity_asset_tuple[1] + k[k.rfind('_'):] for values in v: prep, val = list(values) if val[:val.rfind('_')] == entity_asset_tuple[0]: print('preposiiton - entity_asset_tuple:', prep, ' ', entity_asset_tuple[2].replace( ' ', '_') + '_' + entity_asset_tuple[1] + val[val.rfind('_'):]) formattedVal = ( prep, entity_asset_tuple[2].replace( ' ', '_') + '_' + entity_asset_tuple[1] + val[val.rfind('_'):]) print("Formatted prep-values = ", prep + ' ' + val) try: # case: if key exists check = formattedDict[formattedKey] formattedDict[formattedKey].append(formattedVal) except: # case: if key is not yet added to dictionary formattedDict[formattedKey] = [formattedVal] return formattedDict def subjectAllObjectsDict(scenegraph): # function to take in scene graph, return dictionary with key being the subject+'_'+uniqueEntityID from relations_list, and value being a list of all the objects and their relations with the subject # e.g. A green leaf sits on a gray boulder and under a pebble. # {'leaf_0': [(on, boulder_1), (under, pebble_2)]} print("Obtained scene graph:", scenegraph) objects = [] entities_list = scenegraph["entities"] print("Entities List: ", entities_list) for entity in entities_list: objects.append(entity["head"]) # if : relations_list = scenegraph["relations"] print("relations", relations_list) max_ID = 0 print('Printing relations: ', '\n') subject_objects_dict = dict() for relation in relations_list: # subject+'_'+uniqueEntityID subject = objects[relation.get("subject")]+'_'+str(relation['subject']) if relation['subject'] > max_ID: max_ID = relation['subject'] relation_object = ( relation['relation'], objects[relation.get("object")]+'_'+str(relation['object'])) if relation['object'] > max_ID: max_ID = relation['object'] if subject in list(subject_objects_dict.keys()): subject_objects_dict[subject].append(relation_object) else: subject_objects_dict[subject] = [relation_object] print("Setting key-value ", subject, ": ", subject_objects_dict[subject]) for entity in entities_list: if entity['head'] not in list(subject_objects_dict.keys()) and entity['head'] not in list(subject_objects_dict.values()): max_ID+=1 print("No relation found.") subject_objects_dict[entity['head']+'_'+str(max_ID)] = [("", "")] return subject_objects_dict def scenegraphGraph(scenegraph): G = nx.DiGraph() objects = [] similarity_input = {} # HEAD entities_list = scenegraph["entities"] for entity in entities_list: val = entity["head"] similarity_input[val] = [] objects.append(val) G.add_node(val) # MODIFIERS for entity in entities_list: for modifier_dict in entity["modifiers"]: modifier = modifier_dict.get("span") G.add_node(modifier) object = entity["head"] G.add_edge(object, modifier) similarity_input[object].append(modifier) # RELATIONS relations_list = scenegraph["relations"] print('Printing relations: ', '\n') for relation in relations_list: print(relation) G.add_edge(objects[relation.get("subject")], objects[relation.get( "object")], label=relation.get("relation")) pos = nx.spring_layout(G) node_size = 800 nx.draw(G, with_labels=True, node_size=node_size) edge_labels = nx.get_edge_attributes(G, "label") label_pos = 0.5 nx.draw_networkx_edge_labels( G, pos, edge_labels=edge_labels, label_pos=label_pos) plt.show() return similarity_input def spanList(scenegraph): entities_list = scenegraph["entities"] for entity in entities_list: print(entity["lemma_span"]) def scenegraphTable(sentence): # Here we just use the default parser. parserOutput = sng_parser.parse(sentence) print('Default Parser Output: \n', parserOutput) sng_parser.tprint(parserOutput) return scenegraphGraph(parserOutput), parserOutput # Scene graph parsing completed here ######################################################### print("Loading SentenceTransformer Model...") sentence_model = SentenceTransformer('all-MiniLM-L6-v2') print("Loaded.") g = Graph() g.parse(populated_kg_path, format="ttl") n = Namespace("http://www.semanticweb.org/project/-assets-ontology#") ####################################################################### # util functions def create_embedding_tensor(text): embedding_tensor = sentence_model.encode(text) # print() return embedding_tensor def str_to_tensor(string): str_list = string.split(',') float_list = [float(x) for x in str_list] tenser_res = torch.tensor(float_list) return tenser_res def tensor_to_str(tensor): tensor_list = tensor.tolist() tensor_list_string = "" for l in tensor_list: tensor_list_string += str(l) + ',' tensor_list_string = tensor_list_string[:-1] # remove last ',' return tensor_list_string def concatAssetIntoSen(KG_info): assetSentenceForm = dict() try: for k, v in list(KG_info[1].items()): # dict of asset ID and Name # print("setting for asset id:", k.replace(k[:k.rfind("_"), ""])) assetSentenceForm[k[k.rfind('_')+1:]] = ""+v except Exception as e: print("Name adding unsuccessful", e) try: for k, v in list(KG_info[2].items()): # dict of asset Tag assetSentenceForm[k[k.rfind('_')+1:]] += ' ' + v except: print("Tag adding unsuccessful") try: # dict of asset Size - placed size at start for k, v in list(KG_info[3].items()): assetSentenceForm[k[k.rfind('_')+1:]] = v[v.rfind('#')+1:] + ' sized ' + \ assetSentenceForm[k[k.rfind('_')+1:]] except: print("Size adding unsuccessful") # print("After concatenating assets into sentences des/project/", assetSentenceForm) return assetSentenceForm def find_similar_asset_cos(in_asset_desc_pair, KG_info): wrmd_scores = [] in_asset_Name = list(in_asset_desc_pair.keys())[0] in_asset_Desc = list(in_asset_desc_pair.values())[0] # KG_info -> [assetID dict, asset Names dict, asset Tags dict, asset Sizes dict] KG_info_dict = concatAssetIntoSen(KG_info) print() KG_sentences_vals = list(KG_info_dict.values()) for val in KG_sentences_vals: wrmd_scores.append(find_dist_cosine(create_embedding_tensor( in_asset_Desc), create_embedding_tensor(val))) # cosine_scores = util.cos_sim(input_string, list(KG_tensor_dict.values())) # Find the pair with the highest cosine similarity score max_score = -1 max_index = -1 for i in range(len(wrmd_scores)): if wrmd_scores[i] > max_score: max_score = wrmd_scores[i] max_index = i closest_asset_ID = "" for id, sen in KG_info_dict.items(): if sen == KG_sentences_vals[max_index]: closest_asset_ID = id break try: KG_info[0][str( 'http://www.semanticweb.org/project/-assets-ontology#Asset_') + closest_asset_ID] except Exception as e: print("e for asset ID: ", e) try: KG_info[1][str( 'http://www.semanticweb.org/project/-assets-ontology#Asset_') + closest_asset_ID] except Exception as e: print("e for asset Name: ", e) try: KG_info[2][str( 'http://www.semanticweb.org/project/-assets-ontology#Asset_') + closest_asset_ID] except Exception as e: print("e for asset Tags: ", e) try: KG_info[3][str( 'http://www.semanticweb.org/project/-assets-ontology#Asset_') + closest_asset_ID] except Exception as e: print("e for asset Size: ", e) # now return the entity name against which the match was being asset ID and Name for file writing formatting return in_asset_Name, KG_info[0][str('http://www.semanticweb.org/project/-assets-ontology#Asset_') + closest_asset_ID], KG_info[1][str('http://www.semanticweb.org/project/-assets-ontology#Asset_') + closest_asset_ID] def find_similar_asset(input_string, KG_info): cosine_scores = [] KG_tensor_dict = KG_info[0] KG_tensors_values = list(KG_tensor_dict.values()) for val in KG_tensors_values: cosine_scores.append(util.cos_sim(input_string, val)) # cosine_scores = util.cos_sim(input_string, list(KG_tensor_dict.values())) # Find the pair with the highest cosine similarity score max_score = -1 max_index = -1 for i in range(len(cosine_scores)): if cosine_scores[i] > max_score: max_score = cosine_scores[i] max_index = i closest_asset_ID = "" for id, tensor in KG_tensor_dict.items(): if torch.equal(tensor, KG_tensors_values[max_index]): closest_asset_ID = id break return KG_info[0][closest_asset_ID], KG_info[1][closest_asset_ID], KG_info[2][closest_asset_ID] ####################################################################### # form embeddings for entities mentioned in input def scene_graph_list(sceneGraph_dict): print("\nSCENE GRAPH DICT\n:", sceneGraph_dict) all_spawning_asset_desc = [] asset_list_dict = dict() entities = list(sceneGraph_dict.keys()) for key, value in sceneGraph_dict.items(): desc = "" for modifier in value: desc += modifier + ' ' all_spawning_asset_desc.append(desc+key) # list of all tensors for all nouns and their modifiers - later for matching with assets all_spawning_asset_list = [] for i in range(len(entities)): # for str_desc in all_spawning_asset_desc: asset_desc = all_spawning_asset_desc[i] all_spawning_asset_list.append(asset_desc) asset_list_dict[entities[i]] = asset_desc return all_spawning_asset_list, asset_list_dict def scene_graph_tensors(sceneGraph_dict): all_spawning_asset_desc = [] asset_tensor_dict = dict() entities = list(sceneGraph_dict.keys()) for key, value in sceneGraph_dict.items(): desc = "" for modifier in value: desc += modifier + ' ' all_spawning_asset_desc.append(desc+key) # list of all tensors for all nouns and their modifiers - later for matching with assets all_spawning_asset_tensor = [] for i in range(len(entities)): # for str_desc in all_spawning_asset_desc: asset_tensor_desc = create_embedding_tensor(all_spawning_asset_desc[i]) all_spawning_asset_tensor.append(asset_tensor_desc) asset_tensor_dict[entities[i]] = asset_tensor_desc return all_spawning_asset_tensor, asset_tensor_dict def get_asset_concatTags_dict(tags_list): asset_concatTags_dict = {} # iterate over list - for all elements[0] being same, concatenate to tags_by_asset_xyz to form a sentence for elem in tags_list: if elem[0] in asset_concatTags_dict.keys(): asset_concatTags_dict[elem[0] ] += str(' ' + asset_concatTags_dict[elem[1]]) else: asset_concatTags_dict[elem[0]] = str( asset_concatTags_dict[elem[1]]) print("Finally, assets with all tags in sentenc/project/", asset_concatTags_dict) return asset_concatTags_dict def get_KG_assets(): qres = g.query( """ PREFIX mega:<http://www.semanticweb.org/project/-assets-ontology#> SELECT ?s ?aID ?aName ?aTag ?aSize WHERE { {?s mega:assetTag ?aTag} UNION {?s mega:assetID ?aID} UNION {?s mega:assetName ?aName} UNION {?s mega:assetSize ?aSize} } """) asset_Tag_dict = {} asset_ID_dict = {} asset_Name_dict = {} asset_Size_dict = {} count = 0 for row in qres: try: asset_ID_dict[row.s.toPython()] = row.aID.toPython() except Exception as e: count += 1 try: asset_Name_dict[row.s.toPython()] = row.aName.toPython() except Exception as e: count += 1 try: asset_Size_dict[row.s.toPython()] = row.aSize.toPython() except Exception as e: count += 1 try: if row.aTag is not None: # print("Adding tags for ", row.s.toPython()) asset_Tag_dict[row.s.toPython()] += ' ' + row.aTag.toPython() # print("Updated asset tags list") except Exception as e: if row.aTag is not None: asset_Tag_dict[row.s.toPython()] = row.aTag.toPython() count += 1 return asset_ID_dict, asset_Name_dict, asset_Tag_dict, asset_Size_dict def get_KG_asset_tensors(): qres = g.query( """ PREFIX mega:<http://www.semanticweb.org/project/-assets-ontology#> SELECT ?s ?aID ?aName ?aTensor WHERE { {?s mega:assetTensor ?aTensor} UNION {?s mega:assetID ?aID} UNION {?s mega:assetName ?aName} } """) asset_Tensor_dict = {} asset_ID_dict = {} asset_Name_dict = {} count = 0 for row in qres: try: asset_Tensor_dict[row.s.toPython()] = str_to_tensor( row.aTensor.toPython()) except Exception as e: count += 1 try: asset_ID_dict[row.s.toPython()] = row.aID.toPython() except Exception as e: count += 1 try: asset_Name_dict[row.s.toPython()] = row.aName.toPython() except Exception as e: count += 1 return asset_Tensor_dict, asset_ID_dict, asset_Name_dict def entity_sub_id(entity, all_assets_dicts): print("entity = ", entity) print("all_assets_dict = ", all_assets_dicts) # if type(entity) == 'list': # for elem in entity: # entity_sub_id(elem, all_assets_dicts) # elif type(entity) == 'tuple': # entity1 = entity[1] if type(entity) == 'tuple': entity1 = entity[1] else: entity1 = entity if entity1[:entity1.rfind('_')] in list(all_assets_dicts.keys()): return all_assets_dicts[entity1[:entity1.rfind('_')]] + entity1[entity1.rfind('_'):] def write_all_prep_to_file(all_chosen_assets, subj_obj_dict): print("subj_obj_dict = ", subj_obj_dict) print("all_chosen_assets = ", all_chosen_assets) formattedDict = dict() # copy and edit subj_obj_dict # k = Cow_0, v= [('on', 'sidewalk_1'), ('in', 'city area_2')] for k, v in subj_obj_dict.items(): # if v[0] == ("", "") if len(v[0][0]) != 0 and len(v[0][1]) != 0: print("k,v pair = ", k, '\t', v, '\n') # try: if entity_sub_id(k, all_chosen_assets) in list(formattedDict.keys()): for elem in v: print("Inner tuple: ", elem) formattedDict[entity_sub_id(k, all_chosen_assets)].append( (elem[0], entity_sub_id(elem[1], all_chosen_assets))) else: for elem in v: print("Inner tuple: ", elem) # if elem[0] formattedDict[entity_sub_id(k, all_chosen_assets)] = [( elem[0], entity_sub_id(elem[1], all_chosen_assets))] else: formattedDict[entity_sub_id(k, all_chosen_assets)] = [("", "")] # formattedDict[k] = ("", "") # except Exception as e: # print("e = ", e, " when k = ", k, " v = ", v) print("final Formatted Dict = ", formattedDict) # In the new dict, store in subject_all_objects_dict values, but format its keys to # AssetName_AssetID (entity_asset_dict.keys) +_+<entityID> (subject_all_objects_dict.keys) # Compare - from subject_all_objects_dict, remove from keys and value tuples, everything after & including the last '_' # - replace remaining keys & values in subject_all_objects_dict with values of keys that match with them # EXAMPLE # Entity Asset Dictionary: # {'Cow': 'Wooden_Chair_uknkaffaw', 'sidewalk': 'Brick_Wall_vgvmcgf', 'city area': 'Brick_Wall_vgvmcgf', 'shops': 'Wooden_Chair_uknkaffaw'} # All Subject-Objects Dictionary: # {'Cow_0': [('on', 'sidewalk_1'), ('in', 'city area_2')], 'city area_2': [('near', 'shops_3')]} # RESULT # {'Wooden_Chair_uknkaffaw_0': [('on', 'Brick_Wall_vgvmcgf_1'), ('in', 'Brick_Wall_vgvmcgf_2')], 'Brick_Wall_vgvmcgf_2': [('near', 'Wooden_Chair_uknkaffaw_3')]} # fil = open("/project/.txt", "a") # for k, v in list(formattedDict.items()): # for obj in v: # print("writing tuple - ", obj) # fil.write(obj[1] + '\n') # fil.write(obj[0] + '\n') # fil.write(k + '\n') # fil.write('\n') # print("Written to file") return formattedDict # Lady_Fern_wdvlditia_3 # near # Mossy_Boulder_ulldfii_2 def write_to_file(chosen_asset, subj_obj_dict): # write_prep_to_file() formatted_writing = formatAssetWriting(chosen_asset, subj_obj_dict) line = re.sub(" ", "_", chosen_asset[2]) line += "_"+chosen_asset[1] # append mode fil = open("/project/.txt", "a") fil.write(line) fil.write("\n\n\n") fil.close() def match_KG_input_cos(KG_info, desc_dict, subj_obj_dict): # asset_Tag_dict, asset_Size_dict, asset_ID_dict, asset_Name_dict entity_asset_dict = dict() # input_tensors # [entity_tensors, entityName_tensor_dictionary] # print("Input Desc:", desc_dict) all_chosen_assets = dict() for k, v in desc_dict.items(): # for in_tensor in input_tensors[0]: # for each input entity, find closest assetID and path+append to file: 'assetName_assetID' chosen_asset = find_similar_asset_cos({k: v}, KG_info) print("Chosen asset = ", chosen_asset) all_chosen_assets[chosen_asset[0]] = chosen_asset[2].replace( ' ', '_')+'_'+chosen_asset[1] entity_asset_dict[k] = re.sub( " ", "_", chosen_asset[2]) + "_" + chosen_asset[1] return entity_asset_dict, write_all_prep_to_file(all_chosen_assets, subj_obj_dict) def match_KG_input(KG_info, input_tensors): entity_asset_dict = dict() for k, v in input_tensors[1].items(): chosen_asset = find_similar_asset(v, KG_info) entity_asset_dict[k] = re.sub( " ", "_", chosen_asset[1]) + "_" + chosen_asset[0] write_to_file(chosen_asset) return entity_asset_dict def spawn_object_behind(first_actor, second_actor): print("In BEHIND Function") camera_location, camera_rotation = unreal.EditorLevelLibrary.get_level_viewport_camera_info() #camera_rotation.get_forward_vector() #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_width = first_actor_bounding_box.box_extent.x #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_width = second_actor_bounding_box.box_extent.x vec = unreal.Vector(first_actor_width+ second_actor_width + 200.0, 0, 0) second_actor.set_actor_location(first_actor_loc - vec, False, True) def spawn_object_at_back_of(first_actor, second_actor): print("In BACK OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_width = first_actor_bounding_box.box_extent.x #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_width = second_actor_bounding_box.box_extent.x vec = unreal.Vector(first_actor_width+ second_actor_width, 0, 0) second_actor.set_actor_location(first_actor_loc - vec, False, True) def spawn_object_in_front_of(first_actor, second_actor): print("In FRONT OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_width = first_actor_bounding_box.box_extent.x #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_width = second_actor_bounding_box.box_extent.x vec = unreal.Vector(first_actor_width+ second_actor_width, 0, 0) second_actor.set_actor_location(first_actor_loc + vec, False, True) def spawn_object_at_right_of(first_actor, second_actor): print("In RIGHT OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_length = first_actor_bounding_box.box_extent.y #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_length = second_actor_bounding_box.box_extent.y vec = unreal.Vector(0,first_actor_length+ second_actor_length, 0) second_actor.set_actor_location(first_actor_loc + vec, False, True) def spawn_object_at_left_of(first_actor, second_actor): print("In LEFT OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_length = first_actor_bounding_box.box_extent.y #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_length = second_actor_bounding_box.box_extent.y vec = unreal.Vector(0,first_actor_length+ second_actor_length, 0) second_actor.set_actor_location(first_actor_loc - vec, False, True) def spawn_object_on(first_actor, second_actor): print("In ON OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_height = first_actor_bounding_box.box_extent.z #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_height = second_actor_bounding_box.box_extent.z vec = unreal.Vector( 0, 0,first_actor_height + second_actor_height) second_actor.set_actor_location(first_actor_loc + vec, False, True) def spawn_object_beneath(first_actor, second_actor): print("In BENEATH OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_height = first_actor_bounding_box.box_extent.z #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_height = second_actor_bounding_box.box_extent.z vec = unreal.Vector( 0, 0,first_actor_height + second_actor_height) first_actor.set_actor_location(second_actor_loc + vec, False, True) def spawn_object_in(first_actor, second_actor): print("In IN OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_height = first_actor_bounding_box.box_extent.z #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_height = second_actor_bounding_box.box_extent.z #vec = unreal.Vector( 0, 0,first_actor_height + second_actor_height) #first_actor.set_actor_location(second_actor_loc + vec, False, True) def spawn_object_over(first_actor, second_actor): print("In OVER OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_height = first_actor_bounding_box.box_extent.z #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_height = second_actor_bounding_box.box_extent.z vec = unreal.Vector( 0, 0,first_actor_height + second_actor_height + 250) second_actor.set_actor_location(first_actor_loc + vec, False, True) def spawn_object_under(first_actor, second_actor): print("In UNDER OF Function") #Fisrt Actor first_actor_loc = first_actor.get_actor_location() first_actor_static_mesh_component = first_actor.get_component_by_class(unreal.StaticMeshComponent) first_actor_static_mesh = first_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component first_actor_bounding_box = first_actor_static_mesh.get_bounds() # Extract the height from the bounding box first_actor_height = first_actor_bounding_box.box_extent.z #Second Actor second_actor_loc = second_actor.get_actor_location() second_actor_static_mesh_component = second_actor.get_component_by_class(unreal.StaticMeshComponent) second_actor_static_mesh = second_actor_static_mesh_component.static_mesh # Get the bounding box of the static mesh component second_actor_bounding_box = second_actor_static_mesh.get_bounds() # Extract the height from the bounding box second_actor_height = second_actor_bounding_box.box_extent.z vec = unreal.Vector( 0, 0,first_actor_height + second_actor_height+ 250) first_actor.set_actor_location(second_actor_loc + vec, False, True) def spawn_object_besides(first_actor, second_actor): spawn_object_at_right_of(first_actor, second_actor) def spawn_assets(asset_dicts): asset_directory = "/project/" file1 = open('/project/.txt', 'r') Lines = file1.readlines() #class_path = "/project/.CustomizableActor" for sub,objs in asset_dicts.items(): print(f"Asset = {sub}") prev_actor = spawn_an_asset(sub) if prev_actor != None: for obj in objs: if obj[0] != "" and obj[1] != "": print(f"Obj1 = {obj[1]}") actor = spawn_an_asset(obj[1]) if actor!= None: if obj[0] == "on": spawn_object_on(prev_actor, actor) elif obj[0] == "back": spawn_object_at_back_of(prev_actor, actor) elif obj[0] == "front": spawn_object_in_front_of(prev_actor, actor) elif obj[0] == "right": spawn_object_at_right_of(prev_actor, actor) elif obj[0] == "left": spawn_object_at_left_of(prev_actor, actor) elif obj[0] == "behind": spawn_object_behind(prev_actor, actor) elif obj[0] == "beneath": spawn_object_beneath(prev_actor, actor) elif obj[0] == "in": spawn_object_in(prev_actor, actor) elif obj[0] == "over": spawn_object_over(prev_actor, actor) elif obj[0] == "under": spawn_object_under(prev_actor, actor) elif obj[0] == "besides": spawn_object_besides(prev_actor, actor) else: print("first actor didnt spawn") def spawn_an_asset(asset_name): asset_directory = "/project/" world = unreal.EditorLevelLibrary.get_editor_world() # Spawn an actor actor_location = unreal.Vector(0.0, 0.0, 0.0) actor_rotation = unreal.Rotator(0.0, 0.0, 0.0) actor_class = unreal.EditorAssetLibrary.load_blueprint_class("/project/") actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, actor_location, actor_rotation) asset_registry_module = unreal.AssetRegistryHelpers.get_asset_registry() assets = asset_registry_module.get_assets_by_path(asset_directory , recursive=True, include_only_on_disk_assets=False) filter = unreal.ARFilter(recursive_paths=True) filter.class_names.append("StaticMesh") assets = asset_registry_module.run_assets_through_filter(assets, filter) #print(f"assets = {assets}") f_asset_name = asset_name[:asset_name.rfind('_')] for asset in assets: asset_str = str(asset.asset_name) asset_str = asset_str.strip() line_str = "S_" + f_asset_name.strip() line_str = line_str.strip() if asset_str.find(line_str) != -1: print("Matched ", asset_str, " to ", line_str) print(asset) #actor.static_mesh_component.set_static_mesh(static_mesh) static_mesh = unreal.EditorAssetLibrary.load_asset(str(asset.object_path)) static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent) # Set the static mesh of the component static_mesh_component.set_static_mesh(static_mesh) editor_world = unreal.EditorLevelLibrary.get_editor_world() if editor_world: print("Hello") camera_location, camera_rotation = unreal.EditorLevelLibrary.get_level_viewport_camera_info() # Calculate the spawn location in front of the camera spawn_distance = 500.0 # How far in front of the camera to spawn the asset print(f"forward vector{camera_rotation}") spawn_location = camera_location + (camera_rotation.get_forward_vector() * spawn_distance) spawn_location.z = 0.0 # Set the Z coordinate to ground level actor.set_actor_location(spawn_location, False, True) return actor return None def main(sentence): # sentence = "There is a small green leaf under the gray rock." # sentence = 'There is a small green leaf on a large gray boulder.' # sentence = 'There is a small green leaf on a large gray boulder. The boulder sits in a wide river bank.' # sentence = 'There is a small green leaf on a large gray boulder. The boulder with pebbles around it is in a wide river.' # Co-reference resolution issue + in,has not detected as relations # sentence = 'A small green leaf lies on a large gray boulder. The boulder is in a wide river and has small pebbles around it.' # sentence = 'A small green leaf lies on a large gray boulder. The boulder sits in a wide river. The leaf has small pebbles around it.' #sentence = 'Cow standing on sidewalk in city area near shops .' # sentence = 'Place a rock besides a boulder.' #sentence = 'place a small rock next to a wall' # sentence = 'There is a small green leaf on a large gray boulder.' # KG_info = get_KG_asset_tensors() # new_file_paths = trigger_update(path_to_files) # update_KG(new_file_paths) KG_assets_only_info = get_KG_assets() # print('Input your own sentence. Type q to quit.') # while True: # sentence = input('> ') # if sent.strip() == 'q': # break fil = open("/project/.txt", "w") fil.close() res_dict, parserOutput = scenegraphTable(sentence) res_dict = scene_graph_list(res_dict)[1] subject_all_objects_dict = subjectAllObjectsDict(parserOutput) print("subject_all_objects_dict = ", subject_all_objects_dict) entity_asset_dict, spawning_dict = match_KG_input_cos( KG_assets_only_info, res_dict, subject_all_objects_dict) print("Entity Asset Dictionar/project/", entity_asset_dict) final_spawning_dict = dict() for k, v in list(spawning_dict.items()): final_spawning_dict[k] = [] for tuple in v: if len(v[0][0]) != 0 and len(v[0][1]) != 0: final_spawning_dict[k].append( (sub_closest_prep(tuple[0]), tuple[1])) else: final_spawning_dict[k].append(("","")) print("Final Spawning Dict Format: \n", final_spawning_dict) spawn_assets(final_spawning_dict) #if __name__ == '__main__': #main(sentence)
import unreal file_a = "/project/.fbx" file_b = "/project/.fbx" imported_scenes_path = "/project/" print 'Preparing import options...' advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions() advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512) advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64) advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True) advanced_mesh_options.set_editor_property('remove_degenerates', True) base_options = unreal.DatasmithImportBaseOptions() base_options.set_editor_property('include_geometry', True) base_options.set_editor_property('include_material', True) base_options.set_editor_property('include_light', True) base_options.set_editor_property('include_camera', True) base_options.set_editor_property('include_animation', True) base_options.set_editor_property('static_mesh_options', advanced_mesh_options) base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL) base_options.set_editor_property('asset_options', []) # Not used vred_options = unreal.DatasmithVREDImportOptions() vred_options.set_editor_property('merge_nodes', False) vred_options.set_editor_property('optimize_duplicated_nodes', False) vred_options.set_editor_property('import_var', True) vred_options.set_editor_property('var_path', "") vred_options.set_editor_property('import_light_info', True) vred_options.set_editor_property('light_info_path', "") vred_options.set_editor_property('import_clip_info', True) vred_options.set_editor_property('clip_info_path', "") vred_options.set_editor_property('textures_dir', "") vred_options.set_editor_property('import_animations', True) vred_options.set_editor_property('intermediate_serialization', unreal.DatasmithVREDIntermediateSerializationType.DISABLED) vred_options.set_editor_property('colorize_materials', False) vred_options.set_editor_property('generate_lightmap_u_vs', False) vred_options.set_editor_property('import_animations', True) # Direct import to scene and assets: print 'Importing directly to scene...' unreal.VREDLibrary.import_(file_a, imported_scenes_path, base_options, None, True) #2-stage import step 1: print 'Parsing to scene object...' scene = unreal.DatasmithVREDSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, vred_options) print 'Resulting datasmith scene: ' + str(scene) print '\tProduct name: ' + str(scene.get_product_name()) print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors())) print '\tLight actor count: ' + str(len(scene.get_all_light_actors())) print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors())) print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors())) print '\tMaterial count: ' + str(len(scene.get_all_materials())) print '\tAnimNode count: ' + str(len(scene.get_all_anim_nodes())) print '\tAnimClip count: ' + str(len(scene.get_all_anim_clips())) print '\tExtra light info count: ' + str(len(scene.get_all_extra_lights_info())) print '\tVariant count: ' + str(len(scene.get_all_variants())) # Modify one of the AnimNodes # Warning: The AnimNode nested structure is all USTRUCTs, which are value types, and the Array accessor returns # a copy. Meaning something like anim_nodes[0].name = 'new_name' will set the name on the COPY of anim_nodes[0] anim_nodes = scene.get_all_anim_nodes() if len(anim_nodes) > 0: node_0 = anim_nodes[0] old_name = node_0.name print 'Anim node old name: ' + old_name node_0.name += '_MODIFIED' modified_name = node_0.name print 'Anim node modified name: ' + modified_name anim_nodes[0] = node_0 scene.set_all_anim_nodes(anim_nodes) # Check modification new_anim_nodes = scene.get_all_anim_nodes() print 'Anim node retrieved modified name: ' + new_anim_nodes[0].name assert new_anim_nodes[0].name == modified_name, "Node modification didn't work!" # Restore to previous state node_0 = new_anim_nodes[0] node_0.name = old_name new_anim_nodes[0] = node_0 scene.set_all_anim_nodes(new_anim_nodes) # 2-stage import step 2: print 'Importing assets and actors...' result = scene.import_scene() print 'Import results: ' print '\tImported actor count: ' + str(len(result.imported_actors)) print '\tImported mesh count: ' + str(len(result.imported_meshes)) print '\tImported level sequences: ' + str([a.get_name() for a in result.animations]) print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name()) if result.import_succeed: print 'Import succeeded!' else: print 'Import failed!'
import unreal # Get the current editor world editor_world = unreal.EditorLevelLibrary.get_editor_world() #editor_world = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) #Get post process settings # Define the location and rotation for the PostProcessVolume location = unreal.Vector(0, 0, 0) rotation = unreal.Rotator(0, 0, 0) # Spawn the PostProcessVolume post_process_volume = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PostProcessVolume.static_class(), location, rotation) post_process_volume.unbound = True # Affect whole scene # Disable autoexposure for more control # NOTE: This just sets the values, you still need to activate these properties in the editor # TODO: Figure out if this can be done from Python settings = post_process_volume. settings.bloom_intensity = 100.0 settings.auto_exposure_method = unreal.AutoExposureMethod.AEM_MANUAL settings.auto_exposure_apply_physical_camera_exposure = False #post_process_volume.set_editor_property('Bloom', unreal.PostProcessSettings.bloom_intensity, True) #ppv.settings.set_editor_property("AutoExposureMethod", unreal.AutoExposureMethod.AEM_MANUAL, unreal.PropertyAccessChangeNotifyMode.ALWAYS)
import unreal import os.path import json class bone_limits_struct(): bone_limit_x_min = 0.0 bone_limit_x_max = 0.0 bone_limit_y_min = 0.0 bone_limit_y_max = 0.0 bone_limit_z_min = 0.0 bone_limit_z_max = 0.0 def get_x_range(self): return abs(self.bone_limit_x_max - self.bone_limit_x_min) def get_y_range(self): return abs(self.bone_limit_y_max - self.bone_limit_y_min) def get_z_range(self): return abs(self.bone_limit_z_max - self.bone_limit_z_min) # For getting the preferred angle, it seems like we want the largest angle, not the biggest range def get_x_max_angle(self): return max(abs(self.bone_limit_x_max), abs(self.bone_limit_x_min)) def get_y_max_angle(self): return max(abs(self.bone_limit_y_max), abs(self.bone_limit_y_min)) def get_z_max_angle(self): return max(abs(self.bone_limit_z_max), abs(self.bone_limit_z_min)) def get_preferred_angle(self): if(self.get_x_max_angle() > self.get_y_max_angle() and self.get_x_max_angle() > self.get_z_max_angle()): if abs(self.bone_limit_x_min) > abs(self.bone_limit_x_max): return self.bone_limit_x_min, 0.0, 0.0 return self.bone_limit_x_max, 0.0, 0.0 if(self.get_y_max_angle() > self.get_x_max_angle() and self.get_y_max_angle() > self.get_z_max_angle()): if abs(self.bone_limit_y_min) > abs(self.bone_limit_y_max): return 0.0, self.bone_limit_y_min, 0.0 return 0.0, self.bone_limit_y_max, 0.0 if(self.get_z_max_angle() > self.get_x_max_angle() and self.get_z_max_angle() > self.get_y_max_angle()): if abs(self.bone_limit_z_min) > abs(self.bone_limit_z_max): return 0.0, 0.0, self.bone_limit_z_min return 0.0, 0.0, self.bone_limit_z_max def get_up_vector(self): x, y, z = self.get_preferred_angle() primary_axis = unreal.Vector(x, y, z) primary_axis.normalize() up_axis = unreal.Vector(-1.0 * z, y, -1.0 * x) return up_axis.normal() def get_bone_limits(dtu_json, skeletal_mesh_force_front_x): limits = dtu_json['LimitData'] bone_limits_dict = {} for bone_limits in limits.values(): bone_limits_data = bone_limits_struct() # Get the name of the bone bone_limit_name = bone_limits[0] # Get the bone limits bone_limits_data.bone_limit_x_min = bone_limits[2] bone_limits_data.bone_limit_x_max = bone_limits[3] bone_limits_data.bone_limit_y_min = bone_limits[4] * -1.0 bone_limits_data.bone_limit_y_max = bone_limits[5] * -1.0 bone_limits_data.bone_limit_z_min = bone_limits[6] * -1.0 bone_limits_data.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_limits_data.bone_limit_y_min = bone_limits[2] * -1.0 bone_limits_data.bone_limit_y_max = bone_limits[3] * -1.0 bone_limits_data.bone_limit_z_min = bone_limits[4] * -1.0 bone_limits_data.bone_limit_z_max = bone_limits[5] * -1.0 bone_limits_data.bone_limit_x_min = bone_limits[6] bone_limits_data.bone_limit_x_max = bone_limits[7] bone_limits_dict[bone_limit_name] = bone_limits_data return bone_limits_dict def get_bone_limits_from_skeletalmesh(skeletal_mesh): asset_import_data = skeletal_mesh.get_editor_property('asset_import_data') fbx_path = asset_import_data.get_first_filename() dtu_file = fbx_path.rsplit('.', 1)[0] + '.dtu' dtu_file = dtu_file.replace('/UpdatedFBX/', '/') print(dtu_file) if os.path.exists(dtu_file): dtu_data = json.load(open(dtu_file)) force_front_x = asset_import_data.get_editor_property('force_front_x_axis') bone_limits = get_bone_limits(dtu_data, force_front_x) return bone_limits return [] def get_character_type(dtu_json): asset_id = dtu_json['Asset Id'] if asset_id.lower().startswith('genesis8'): return 'Genesis8' if asset_id.lower().startswith('genesis9'): return 'Genesis9' return 'Unknown' def set_control_shape(blueprint, bone_name, shape_type): hierarchy = blueprint.hierarchy control_name = bone_name + '_ctrl' control_settings_root_ctrl = unreal.RigControlSettings() control_settings_root_ctrl.animation_type = unreal.RigControlAnimationType.ANIMATION_CONTROL control_settings_root_ctrl.control_type = unreal.RigControlType.EULER_TRANSFORM control_settings_root_ctrl.display_name = 'None' control_settings_root_ctrl.draw_limits = True control_settings_root_ctrl.shape_color = unreal.LinearColor(1.000000, 0.000000, 0.000000, 1.000000) control_settings_root_ctrl.shape_visible = True control_settings_root_ctrl.is_transient_control = False control_settings_root_ctrl.limit_enabled = [unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False)] control_settings_root_ctrl.minimum_value = unreal.RigHierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[0.000000,0.000000,0.000000])) control_settings_root_ctrl.maximum_value = unreal.RigHierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[0.000000,0.000000,0.000000])) control_settings_root_ctrl.primary_axis = unreal.RigControlAxis.X if shape_type == "root": control_settings_root_ctrl.shape_name = 'Square_Thick' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[10.000000,10.000000,10.000000]), True) if shape_type == "hip": control_settings_root_ctrl.shape_name = 'Hexagon_Thick' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[10.000000,10.000000,10.000000]), True) if shape_type == "iktarget": control_settings_root_ctrl.shape_name = 'Box_Thin' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) #hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[10.000000,10.000000,10.000000]), True) if shape_type == "large_2d_bend": control_settings_root_ctrl.shape_name = 'Arrow4_Thick' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[8.000000,8.000000,8.000000]), True) if shape_type == "slider": control_settings_root_ctrl.control_type = unreal.RigControlType.FLOAT control_settings_root_ctrl.primary_axis = unreal.RigControlAxis.Y control_settings_root_ctrl.limit_enabled = [unreal.RigControlLimitEnabled(True, True)] control_settings_root_ctrl.minimum_value = unreal.RigHierarchy.make_control_value_from_float(0.000000) control_settings_root_ctrl.maximum_value = unreal.RigHierarchy.make_control_value_from_float(1.000000) control_settings_root_ctrl.shape_name = 'Arrow2_Thin' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[0.5,0.5,0.5]), True) last_construction_link = 'PrepareForExecution' construction_y_pos = 200 def create_construction(blueprint, bone_name): global last_construction_link global construction_y_pos rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() 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(1000.0, construction_y_pos), 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(1300.0, construction_y_pos), 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 construction_y_pos = construction_y_pos + 250 last_backward_solver_link = 'InverseExecution.ExecuteContext' def create_backward_solver(blueprint, 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 = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() #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 parent_control_to_control(hierarchy_controller, parent_control_name ,control_name): hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=parent_control_name), False) def parent_control_to_bone(hierarchy_controller, parent_bone_name, control_name): hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.RigElementKey(type=unreal.RigElementType.BONE, name=parent_bone_name), False) next_forward_execute = 'BeginExecution.ExecuteContext' node_y_pos = 200.0 def create_control(blueprint, bone_name, parent_bone_name, shape_type): global next_forward_execute global node_y_pos hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() 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) hierarchy_controller.remove_element(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_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) #hierarchy_controller.remove_all_parents(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), True) transform = hierarchy.get_global_transform(key, True) hierarchy.set_control_offset_transform(control_key, transform, True) hierarchy.set_control_offset_transform(control_key, transform, False) #hierarchy.set_global_transform(control_key, unreal.Transform(), True) #hierarchy.set_global_transform(control_key, unreal.Transform(), False) #hierarchy.set_global_transform(control_key, transform, False) # if bone_name in control_list: # create_direct_control(bone_name) # elif bone_name in effector_list: # create_effector(bone_name) #create_direct_control(bone_name) create_construction(blueprint, bone_name) create_backward_solver(blueprint, bone_name) set_control_shape(blueprint, bone_name, shape_type) if shape_type in ['iktarget', 'large_2d_bend', 'slider']: return control_name # Link Control to Bone get_transform_node_name = bone_name + "_GetTransform" # blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(49.941063, node_y_pos), get_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(get_transform_node_name + '.Item', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Name', control_name, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Type', 'Control', True) set_transform_node_name = bone_name + "_SetTransform" blueprint.get_controller_by_name('RigVMModel').add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren)', unreal.Vector2D(701.941063, node_y_pos), set_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(set_transform_node_name + '.Item', False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Weight', '1.000000') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.bPropagateToChildren', 'True') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Item.Name', bone_name, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Item.Type', 'Bone', True) #blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Transform', '(Rotation=(X=0.000000,Y=0.000000,Z=0.000000,W=1.000000),Translation=(X=0.000000,Y=0.000000,Z=0.000000),Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))', True) blueprint.get_controller_by_name('RigVMModel').add_link(get_transform_node_name + '.Transform', set_transform_node_name + '.Value') blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, set_transform_node_name + '.ExecuteContext') next_forward_execute = set_transform_node_name + '.ExecuteContext' if parent_bone_name: parent_control_name = parent_bone_name + '_ctrl' #hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=parent_control_name), True) node_y_pos = node_y_pos + 200 return control_name def create_limb_ik(blueprint, skeleton, bone_limits, root_bone_name, end_bone_name, shape_type): global next_forward_execute global node_y_pos end_bone_ctrl = end_bone_name + '_ctrl' hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() rig_controller = blueprint.get_controller_by_name('RigVMModel') limb_ik_node_name = end_bone_name + '_FBIK' rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PBIK', 'Execute', unreal.Vector2D(370.599976, node_y_pos), limb_ik_node_name) rig_controller.set_pin_default_value(limb_ik_node_name + '.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(limb_ik_node_name + '.Root', root_bone_name, False) root_FBIK_settings = rig_controller.insert_array_pin(limb_ik_node_name + '.BoneSettings', -1, '') rig_controller.set_pin_default_value(root_FBIK_settings + '.Bone', 'pelvis', False) rig_controller.set_pin_default_value(root_FBIK_settings + '.RotationStiffness', '1.0', False) rig_controller.set_pin_default_value(root_FBIK_settings + '.PositionStiffness', '1.0', False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(limb_ik_node_name + '.Settings.RootBehavior', 'PinToInput', False) get_transform_node_name = end_bone_name + "_GetTransform" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(49.941063, node_y_pos), get_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(get_transform_node_name + '.Item', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Name', end_bone_ctrl, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Type', 'Control', True) pin_name = rig_controller.insert_array_pin(limb_ik_node_name + '.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_node_name + '.Transform', pin_name + '.Transform') rig_controller.set_pin_default_value(pin_name + '.Bone', end_bone_name, False) # if(bone_name in guide_list): # rig_controller.set_pin_default_value(pin_name + '.StrengthAlpha', '0.200000', False) # Limb Root Bone Settings # bone_settings_name = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(limb_ik_node_name + '.BoneSettings', -1, '') # blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.Bone', root_bone_name, False) # blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.RotationStiffness', '1.000000', False) # blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.PositionStiffness', '1.000000', False) # Joint Bone Settings joint_bone_name = unreal.DazToUnrealBlueprintUtils.get_joint_bone(skeleton, root_bone_name, end_bone_name); bone_settings_name = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(limb_ik_node_name + '.BoneSettings', -1, '') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.Bone', joint_bone_name, False) #blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.RotationStiffness', '1.000000', False) #blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.PositionStiffness', '1.000000', False) #print(bone_limits) x_preferred, y_preferred, z_preferred = bone_limits[str(joint_bone_name)].get_preferred_angle() # Figure out preferred angles, the primary angle is the one that turns the furthest from base pose rig_controller.set_pin_default_value(bone_settings_name + '.bUsePreferredAngles', 'true', False) rig_controller.set_pin_default_value(bone_settings_name + '.PreferredAngles.X', str(x_preferred), False) rig_controller.set_pin_default_value(bone_settings_name + '.PreferredAngles.Y', str(y_preferred), False) rig_controller.set_pin_default_value(bone_settings_name + '.PreferredAngles.Z', str(z_preferred), False) blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, limb_ik_node_name + '.ExecuteContext') node_y_pos = node_y_pos + 400 next_forward_execute = limb_ik_node_name + '.ExecuteContext' def create_2d_bend(blueprint, skeleton, bone_limits, start_bone_name, end_bone_name, shape_type): global node_y_pos global next_forward_execute ctrl_name = create_control(blueprint, start_bone_name, None, 'large_2d_bend') distribute_node_name = start_bone_name + "_to_" + end_bone_name + "_DistributeRotation" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_DistributeRotationForItemArray', 'Execute', unreal.Vector2D(365.055382, node_y_pos), distribute_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.RotationEaseType', 'Linear') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.Weight', '0.25') item_collection_node_name = start_bone_name + "_to_" + end_bone_name + "_ItemCollection" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_CollectionChainArray', 'Execute', unreal.Vector2D(120.870192, node_y_pos), item_collection_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.FirstItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.LastItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.Reverse', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem.Name', start_bone_name, False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem.Name', end_bone_name, False) blueprint.get_controller_by_name('RigVMModel').add_link(item_collection_node_name + '.Items', distribute_node_name + '.Items') get_transform_node_name = ctrl_name + "_2dbend_GetTransform" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(49.941063, node_y_pos), get_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(get_transform_node_name + '.Item', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Name', ctrl_name, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Type', 'Control', True) rotation_pin = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(distribute_node_name + '.Rotations', -1, '') print(rotation_pin) blueprint.get_controller_by_name('RigVMModel').add_link(get_transform_node_name + '.Transform.Rotation', rotation_pin + '.Rotation') #blueprint.get_controller_by_name('RigVMModel').add_link('rHand_GetTransform.Transform.Rotation', 'abdomenLower_to_chestUpper_DistributeRotation.Rotations.0.Rotation') blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, distribute_node_name + '.ExecuteContext') node_y_pos = node_y_pos + 350 next_forward_execute = distribute_node_name + '.ExecuteContext' def create_slider_bend(blueprint, skeleton, bone_limits, start_bone_name, end_bone_name, parent_control_name): global node_y_pos global next_forward_execute hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() ctrl_name = create_control(blueprint, start_bone_name, None, 'slider') distribute_node_name = start_bone_name + "_to_" + end_bone_name + "_DistributeRotation" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_DistributeRotationForItemArray', 'Execute', unreal.Vector2D(800.0, node_y_pos), distribute_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.RotationEaseType', 'Linear') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.Weight', '0.25') rotation_pin = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(distribute_node_name + '.Rotations', -1, '') item_collection_node_name = start_bone_name + "_to_" + end_bone_name + "_ItemCollection" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_CollectionChainArray', 'Execute', unreal.Vector2D(120.0, node_y_pos), item_collection_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.FirstItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.LastItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.Reverse', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem.Name', start_bone_name, False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem.Name', end_bone_name, False) blueprint.get_controller_by_name('RigVMModel').add_link(item_collection_node_name + '.Items', distribute_node_name + '.Items') # Create Rotation Node rotation_node_name = start_bone_name + "_to_" + end_bone_name + "_Rotation" x_preferred, y_preferred, z_preferred = bone_limits[start_bone_name].get_preferred_angle() blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionFromEuler', 'Execute', unreal.Vector2D(350.0, node_y_pos), rotation_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler', '(X=0.000000,Y=0.000000,Z=0.000000)') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(rotation_node_name + '.Euler', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.RotationOrder', 'ZYX') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler.X', str(x_preferred * -1.0), False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler.Y', str(y_preferred), False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler.Z', str(z_preferred), False) # Get Control Float control_float_node_name = start_bone_name + "_to_" + end_bone_name + "_ControlFloat" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetControlFloat', 'Execute', unreal.Vector2D(500.0, node_y_pos), control_float_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(control_float_node_name + '.Control', 'None') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(control_float_node_name + '.Control', ctrl_name, False) blueprint.get_controller_by_name('RigVMModel').add_link(rotation_node_name + '.Result', rotation_pin + '.Rotation') blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, distribute_node_name + '.ExecuteContext') blueprint.get_controller_by_name('RigVMModel').add_link(control_float_node_name + '.FloatValue', distribute_node_name + '.Weight') parent_control_to_control(hierarchy_controller, parent_control_name, ctrl_name) # Offset the control so it's not in the figure. Not working... up_vector = bone_limits[start_bone_name].get_up_vector() #up_transform = unreal.Transform(location=up_vector,rotation=[0.000000,0.000000,0.000000],scale=[1.000000,1.000000,1.000000]) #up_transform = unreal.Transform(location=[0.0, 0.0, 50.0],rotation=[0.000000,0.000000,0.000000],scale=[1.000000,1.000000,1.000000]) #hierarchy.set_control_offset_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=ctrl_name), up_transform) node_y_pos = node_y_pos + 350 next_forward_execute = distribute_node_name + '.ExecuteContext'
import unreal import taichi as ti from Utilities.Utils import Singleton ti.init(arch=ti.gpu) n = 120 pixels = ti.field(dtype=float, shape=(n * 2, n)) @ti.func def complex_sqr(z): return ti.Vector([z[0]**2 - z[1]**2, z[1] * z[0] * 2]) @ti.kernel def paint(t: float): for i, j in pixels: # Parallelized over all pixels c = ti.Vector([-0.8, ti.cos(t) * 0.2]) z = ti.Vector([i / n - 1, j / n - 0.5]) * 2 iterations = 0 while z.norm() < 20 and iterations < 50: z = complex_sqr(z) + c iterations += 1 pixels[i, j] = 1 - iterations * 0.02 class Taichi_fractal(metaclass=Singleton): def __init__(self, jsonPath:str): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_image = "taichi_fractal_image" self.colors = [unreal.LinearColor(1, 1, 1, 1) for _ in range(2 * n * n)] self.tick_count = 0 def on_tick(self): paint(self.tick_count * 0.03) x_np = pixels.to_numpy() width = 2 * n height = n for x, v in enumerate(x_np): for y, c in enumerate(v): index = y * width + x self.colors[index].r = self.colors[index].g = self.colors[index].b = float(c) self.data.set_image_pixels(self.ui_image, self.colors, width, height) self.tick_count += 1 def on_button_click(self): self.tick_count = 0
import os import xml.etree.ElementTree as ET CRY_ENGINE_OUTPUT_FOLDER_ROOT = "D:/project/" LEVEL_ROOT_FOLDER = "data/levels" # Removed leading slash for consistency LEVEL_LAYERS_FOLDER = "layers" LEVEL_EDITOR_XML = "level.editor_xml" PREFAB_ROOT_FOLDER = 'prefabs' LEVEL_NAME = "rataje" LAYER_WHITELIST = [ "Rataje", ] class StaticMesh: def __init__(self): self.name = None self.pos = None self.rotate = None self.scale = None self.mesh_path = None def init_from_brush_xml(self, xml_node): self.name = xml_node.get("Name") if "Name" in xml_node.attrib else None self.pos = xml_node.get("Pos") if "Pos" in xml_node.attrib else "0.0,0.0,0.0" self.rotate = xml_node.get("Rotate") if "Rotate" in xml_node.attrib else "0.0,0.0,0.0,0.0" self.scale = xml_node.get("Scale") if "Scale" in xml_node.attrib else "1.0,1.0,1.0" self.mesh_path = xml_node.get("Prefab") if "Prefab" in xml_node.attrib else None def init_from_geo_xml(self, xml_node): self.name = xml_node.get("Name") if "Name" in xml_node.attrib else None self.pos = xml_node.get("Pos") if "Pos" in xml_node.attrib else "0.0,0.0,0.0" self.rotate = xml_node.get("Rotate") if "Rotate" in xml_node.attrib else "0.0,0.0,0.0,0.0" self.scale = xml_node.get("Scale") if "Scale" in xml_node.attrib else "1.0,1.0,1.0" self.mesh_path = xml_node.get("Geometry") if "Geometry" in xml_node.attrib else None class PrefabActor: def __init__(self): self.name = None self.pos = None self.rotate = None self.scale = None self.prefab_name = None def init_from_brush_xml(self, xml_node): self.name = xml_node.get("Name") if "Name" in xml_node.attrib else None self.pos = xml_node.get("Pos") if "Pos" in xml_node.attrib else "0.0,0.0,0.0" self.rotate = xml_node.get("Rotate") if "Rotate" in xml_node.attrib else "0.0,0.0,0.0,0.0" self.scale = xml_node.get("Scale") if "Scale" in xml_node.attrib else "1.0,1.0,1.0" self.prefab_name = xml_node.get("PrefabName") if "PrefabName" in xml_node.attrib else None class Layer: def __init__(self, name): self.name = name self.prefab_actors = [] self.static_meshes = [] self.child_layers = [] def init_from_xml(self, xml_node): # self.name = xml_node.get("Name") if "Name" in xml_node.attrib else None self.prefab_actors = [] self.static_meshes = [] self.child_layers = [] # Iterate through child objects objects_node = xml_node.find(".//LayerObjects") if objects_node is not None: for obj_node in objects_node.findall("Object"): obj_type = obj_node.get("Type") if obj_type == "Prefab": prefab_actor = PrefabActor() prefab_actor.init_from_brush_xml(obj_node) self.prefab_actors.append(prefab_actor) elif obj_type == "GeomEntity": static_mesh = StaticMesh() static_mesh.init_from_geo_xml(obj_node) self.static_meshes.append(static_mesh) elif obj_type == "Brush": static_mesh = StaticMesh() static_mesh.init_from_brush_xml(obj_node) self.static_meshes.append(static_mesh) child_layers_node = xml_node.find(".//ChildLayers") layers_node = child_layers_node.findall("Layer") if child_layers_node is not None else None if layers_node is not None: for layer_node in layers_node: fullname = layer_node.get("FullName") name = layer_node.get("Name") layer_xml_path = os.path.join(CRY_ENGINE_OUTPUT_FOLDER_ROOT, LEVEL_ROOT_FOLDER, LEVEL_NAME, LEVEL_LAYERS_FOLDER, f"{fullname}.lyr") if os.path.exists(layer_xml_path): tree = ET.parse(layer_xml_path) root = tree.getroot() layer = Layer(name) layer.init_from_xml(root) self.child_layers.append(layer) else: print(f"Layer file not found: {layer_xml_path}") print(f"Layer: {self.name}") print(f"Prefab Actors: {[actor.name for actor in self.prefab_actors]}") def get_mesh_paths(self): mesh_paths = set() for static_mesh in self.static_meshes: if static_mesh.mesh_path: mesh_paths.add(static_mesh.mesh_path) for child_layer in self.child_layers: child_mesh_paths = child_layer.get_mesh_paths() mesh_paths.update(child_mesh_paths) return mesh_paths def get_prefab_paths(self): prefab_actor_paths = set() for prefab_actor in self.prefab_actors: if prefab_actor.prefab_name: prefab_actor_paths.add(prefab_actor.prefab_name) for child_layer in self.child_layers: child_prefab_actor_paths = child_layer.get_prefab_paths() prefab_actor_paths.update(child_prefab_actor_paths) return prefab_actor_paths class Prefab: def __init__(self): self.name = None self.library = None self.static_meshes = [] def init_from_xml(self, xml_node): self.name = xml_node.get("Name") if "Name" in xml_node.attrib else None self.library = xml_node.get("Library") if "Library" in xml_node.attrib else None self.static_meshes = [] # Iterate through child objects objects_node = xml_node.find("Objects") if objects_node is not None: for obj_node in objects_node.findall("Object"): obj_type = obj_node.get("Type") if obj_type == "GeomEntity": static_mesh = StaticMesh() static_mesh.init_from_geo_xml(obj_node) self.static_meshes.append(static_mesh) elif obj_type == "Brush": static_mesh = StaticMesh() static_mesh.init_from_brush_xml(obj_node) self.static_meshes.append(static_mesh) def get_prefab_name(self): return f"{self.library}.{self.name}" if self.library else self.name def get_mesh_paths(self): mesh_paths = set() for static_mesh in self.static_meshes: if static_mesh.mesh_path: mesh_paths.add(static_mesh.mesh_path) return mesh_paths class Level: def __init__(self): self.name = None self.prefabs = {} self.layers = [] def get_all_mesh_paths(self): all_mesh_paths = set() all_mesh_paths = set() for layer in self.layers: layer_mesh_paths = layer.get_mesh_paths() all_mesh_paths.update(layer_mesh_paths) all_prefab_paths = layer.get_prefab_paths() for prefab in self.prefabs.values(): if prefab in all_prefab_paths: prefab_mesh_paths = prefab.get_mesh_paths() all_mesh_paths.update(prefab_mesh_paths) return all_mesh_paths def parse_prefabs_library(prefabs_library_node): prefabs = [] libraries = [] # Parse LevelLibrary for prefabs level_library_node = prefabs_library_node.find("LevelLibrary") if level_library_node is not None: for prefab_node in level_library_node.findall("Prefab"): prefab = Prefab() prefab.init_from_xml(prefab_node) prefabs.append(prefab) # Parse Library names for library_node in prefabs_library_node.findall("Library"): library_name = library_node.get("Name") if library_name: libraries.append(library_name) for library_name in libraries: library_path = os.path.join(CRY_ENGINE_OUTPUT_FOLDER_ROOT, PREFAB_ROOT_FOLDER, f"{library_name.lower()}.xml") if os.path.exists(library_path): tree = ET.parse(library_path) root = tree.getroot() for prefab_node in root.findall("Prefab"): prefab = Prefab() prefab.init_from_xml(prefab_node) prefabs.append(prefab) prefab_dict = {} for prefab in prefabs: prefab_dict[prefab.get_prefab_name()] = prefab return prefab_dict def parse_level(): level = Level() level.name = LEVEL_NAME # Extract and parse the PrefabsLibrary contents file_path = os.path.join(CRY_ENGINE_OUTPUT_FOLDER_ROOT, LEVEL_ROOT_FOLDER, LEVEL_NAME, LEVEL_EDITOR_XML) if os.path.exists(file_path): tree = ET.parse(file_path) root = tree.getroot() prefabs_library_node = root.find("PrefabsLibrary") if prefabs_library_node is not None: level.prefabs = parse_prefabs_library(prefabs_library_node) # # Print all prefab names # for prefab in level.prefabs.keys(): # print(prefab) else: print("No <PrefabsLibrary> element found in the XML.") layers = [] # Properly locate ChildLayers nodes under ObjectLayers -> RootLayer object_layers_node = root.find(".//ObjectLayers") if object_layers_node is not None: root_layer_nodes = object_layers_node.findall("RootLayer") # if root_layer_node is not None: # child_layers_node = root_layer_node.find("ChildLayers") # if child_layers_node is not None: for layer_node in root_layer_nodes: fullname = layer_node.get("FullName") name = layer_node.get("Name") if name not in LAYER_WHITELIST: print(f"Layer {name} not in whitelist, skipping.") continue layer_xml_path = os.path.join(CRY_ENGINE_OUTPUT_FOLDER_ROOT, LEVEL_ROOT_FOLDER, LEVEL_NAME, LEVEL_LAYERS_FOLDER, f"{fullname}.lyr") if os.path.exists(layer_xml_path): tree = ET.parse(layer_xml_path) root = tree.getroot() layer = Layer(name) layer.init_from_xml(root) layers.append(layer) else: print(f"Layer file not found: {layer_xml_path}") level.layers = layers else: print(f"File not found: {file_path}") return level import unreal editor_level_lib = unreal.EditorLevelLibrary() level_editor_sub = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) editor_asset_sub = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) data_layer_sub = unreal.get_editor_subsystem(unreal.DataLayerEditorSubsystem) PLACE_HOLDER_SM= "/project/" place_holder_sm_obj = unreal.EditorAssetLibrary.load_asset(PLACE_HOLDER_SM) PREFAB_PACKAGE_PATH = "/project/" INPUT_PACKAGE_ROOT = "/project/" import math def quaternion_to_euler(quaternion): """ Converts a quaternion (x, y, z, w) to Euler angles (pitch, yaw, roll) in degrees. """ x, y, z, w = quaternion # Roll (X-axis rotation) sinr_cosp = 2 * (w * x + y * z) cosr_cosp = 1 - 2 * (x * x + y * y) roll = math.atan2(sinr_cosp, cosr_cosp) # Pitch (Y-axis rotation) sinp = 2 * (w * y - z * x) if abs(sinp) >= 1: pitch = math.copysign(math.pi / 2, sinp) # Use 90 degrees if out of range else: pitch = math.asin(sinp) # Yaw (Z-axis rotation) siny_cosp = 2 * (w * z + x * y) cosy_cosp = 1 - 2 * (y * y + z * z) yaw = math.atan2(siny_cosp, cosy_cosp) # Convert radians to degrees roll = math.degrees(roll) pitch = math.degrees(pitch) yaw = math.degrees(yaw) return pitch, yaw, roll def convert_cryengine_to_unreal_rotation(cryengine_rotate): """ Converts CryEngine quaternion rotation to Unreal Engine rotator. Assumes the input quaternion is in (w, x, y, z) order. For example, a CryEngine rotation "0.90630782,0.42261824,0,0" represents a 50° rotation about the X axis and should produce an Unreal rotator of (Pitch: 50.0, Yaw: 0.0, Roll: 0.0). """ # Parse the quaternion string into floats (expected order: w, x, y, z) input_quat = [float(coord) for coord in cryengine_rotate.split(",")] # Reorder to (x, y, z, w) for our conversion formulas q = [input_quat[1], input_quat[2], input_quat[3], input_quat[0]] # Compute Euler angles using the standard conversion: # This returns (pitch, yaw, roll) where roll is rotation about X-axis. computed_pitch, computed_yaw, computed_roll = quaternion_to_euler(q) # Remap to Unreal's Rotator: # Unreal expects (Pitch, Yaw, Roll), but we want the CryEngine X-rotation # (computed as roll) to map to Unreal's Pitch. unreal_pitch = computed_roll # X-axis rotation becomes Pitch unreal_yaw = -1.0*computed_pitch # Y-axis rotation remains Yaw unreal_roll = -1.0*computed_yaw # Z-axis rotation becomes Roll return unreal_pitch, unreal_yaw, unreal_roll def recreate_level_in_unreal(level_data): with unreal.ScopedSlowTask(len(level_data.layers), "Importing Layers...") as slow_task: # display the dialog slow_task.make_dialog(True) for layer in level_data.layers: if slow_task.should_cancel(): break slow_task.enter_progress_frame(1, "Importing Layer {}".format(layer.name)) recreate_layer_in_unreal(layer) def recreate_layer_in_unreal(layer, parent_layer=None): data_layer_instance = data_layer_sub.get_data_layer_from_label(layer.name) if not data_layer_instance: data_layer_create_param = unreal.DataLayerCreationParameters() data_layer_create_param.data_layer_asset = None data_layer_create_param.is_private = True data_layer_instance = data_layer_sub.create_data_layer_instance(data_layer_create_param) result = unreal.PythonFunctionLibrary().set_data_layer_short_name(data_layer_instance, layer.name) if parent_layer: data_layer_sub.set_parent_data_layer(data_layer_instance, parent_layer) spawned_actors = [] # Iterate through prefab actors and static meshes for prefab_actor in layer.prefab_actors: prefab_actor = spawn_prefab_actor(prefab_actor) spawned_actors.append(prefab_actor) for static_mesh in layer.static_meshes: static_mesh_actor = spawn_static_mesh(static_mesh) spawned_actors.append(static_mesh_actor) result = data_layer_sub.add_actors_to_data_layer(spawned_actors, data_layer_instance) for layer in layer.child_layers: recreate_layer_in_unreal(layer, data_layer_instance) def spawn_actor_common(actor, actor_class): pos_str = actor.pos pos = [float(coord)*100.0 for coord in pos_str.split(",")] rotate = convert_cryengine_to_unreal_rotation(actor.rotate) scale_str = actor.scale scale = [float(coord) for coord in scale_str.split(",")] mesh_actor = editor_level_lib.spawn_actor_from_class(actor_class, unreal.Vector(pos[0], -1.0*pos[1], pos[2])) mesh_actor.set_actor_rotation(unreal.Rotator(rotate[0], rotate[1], rotate[2]), False) mesh_actor.set_actor_scale3d(unreal.Vector(scale[0], scale[1], scale[2])) return mesh_actor def spawn_static_mesh(static_mesh): mesh_actor = spawn_actor_common(static_mesh, unreal.StaticMeshActor) mesh_actor.set_actor_label(static_mesh.name) mesh_component = mesh_actor.get_component_by_class(unreal.StaticMeshComponent) mesh_package_path = INPUT_PACKAGE_ROOT + '/' + static_mesh.mesh_path.replace('.cgf', '') if editor_asset_sub.does_asset_exist(mesh_package_path): static_mesh_obj = editor_asset_sub.load_asset(mesh_package_path) mesh_component.set_static_mesh(static_mesh_obj) else: mesh_component.set_static_mesh(place_holder_sm_obj) return mesh_actor def spawn_prefab_actor(prefab_actor): prefab_path = prefab_actor.prefab_name.replace('.', '/') prefab_path = PREFAB_PACKAGE_PATH + "/" + prefab_path level_instance_actor = spawn_actor_common(prefab_actor, unreal.LevelInstance) world_asset = unreal.EditorAssetLibrary.load_asset(prefab_path) level_instance_actor.set_editor_property("world_asset", world_asset) level_instance_actor.set_actor_label(prefab_actor.name) return level_instance_actor def generated_all_prefabs(level_data: Level): for prefab in level_data.prefabs.values(): create_level_prefab(prefab) def create_level_prefab(prefab: Prefab): print(prefab.get_prefab_name()) new_level_path = prefab.get_prefab_name().replace('.', '/') new_level_path = PREFAB_PACKAGE_PATH + "/" + new_level_path print(new_level_path) level_editor_sub.new_level(new_level_path, False) for static_mesh in prefab.static_meshes: spawn_static_mesh(static_mesh) level_editor_sub.save_current_level() if __name__ == "__main__": level_data = parse_level() # generated_all_prefabs(level_data) recreate_level_in_unreal(level_data) # all_mesh_paths = level_data.get_all_mesh_paths() # print(all_mesh_paths) # for mesh_path in all_mesh_paths: # print(mesh_path)
# Copyright 2020 Tomoaki Yoshida<[email protected]> # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/project/.0/. # # # # You need following modules to run this script # + pillow # + numpy # + gdal # # You can install these modules by running following commands on a posh prompt # PS> cd /project/ Files\Epic Games\UE_4.25\Engine\Binaries\ThirdParty\Python\Win64 # PS> ./python.exe -m pip install pillow numpy # GDAL cannot install by this simple method. You need to download whl file from # https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal # and then, install it by the similar command # PS> ./python.exe -m pip install /project/-2.2.4-cp27-cp27m-win_amd64.whl # # You may want to add # --target="/project/ Files\Epic Games\UE_4.25\Engine\Source\ThirdParty\Python\Win64\Lib\site-packages" # to each pip install command. Without this --target option, modules will be installed in this folder. # /project/ Files\Epic Games\UE_4.25\Engine\Binaries\ThirdParty\Python\Win64\Lib\site-packages import unreal import gdal import osr import os from PIL import Image, ImageTransform, ImageMath import numpy as np import math import sys al=unreal.EditorAssetLibrary el=unreal.EditorLevelLibrary sdir=os.path.dirname(os.path.abspath(__file__)) projdir=os.path.join(sdir,"..","..") # Utilities # FVector ([deg], [min], [sec]) -> float [deg] def Decode60(vec): return ((vec.z/60.)+vec.y)/60.+vec.x; # float [deg] -> FVector ([deg], [min], [sec]) def Encode60(v): d=math.floor(v) m=math.floor((v-d)*60.) s=(v-d-m/60.)*3600. return unreal.Vector(d,m,s) class LandscapeParams: def __init__(self): self.setStepSize(10) self.setZScale(10) self.setZEnhance(1) # landscale cell size [cm] def setStepSize(self, size): self.stepSize=size return self # landscape z scale value 100-> +/-256 [m], 10-> +/-25.6 [m] 1-> +/-256 [cm] def setZScale(self, scale): self.toUEScale=100.*128./scale self.zScale=scale return self # optional z scaling factor def setZEnhance(self, enh): self.zEnhance=enh return self class GeoTIFF: def __init__(self, file, lp): self.stepSize=lp.stepSize self.gt = gdal.Open(file, gdal.GA_ReadOnly) #self.rast = np.array([self.gt.GetRasterBand(1).ReadAsArray()]) self.image = Image.fromarray(self.gt.GetRasterBand(1).ReadAsArray()) self.src_cs = osr.SpatialReference() self.dst_cs = osr.SpatialReference() self.dst_cs.ImportFromWkt(self.gt.GetProjectionRef()) self.setSrcEPSG(6668) # default to JGD2011 # inverse transform from GeoTIFF(UV) to GeoTIFF(Logical) self.mat = self.gt.GetGeoTransform() d = 1./(self.mat[5]*self.mat[1]-self.mat[4]*self.mat[2]) self.iaf = np.array([[ self.mat[5],-self.mat[2]], [-self.mat[4], self.mat[1]]])*d self.offset = np.array([[self.mat[0]], [self.mat[3]]]) self.af=np.array([[self.mat[1], self.mat[2]], [self.mat[4], self.mat[5]]]) def setSrcEPSG(self, epsg): self.src_cs = osr.SpatialReference() self.src_cs.ImportFromEPSG(epsg) self.transS2G = osr.CoordinateTransformation(self.src_cs, self.dst_cs) # Geotiff CS to Interface CS self.transG2S=osr.CoordinateTransformation(self.dst_cs,self.src_cs) def getBL(self,uv): u=uv[0] v=uv[1] bl=np.dot(self.af,np.array([[u],[v]]))+self.offset sbl=self.transG2S.TransformPoint(bl[1][0],bl[0][0]) return (sbl[0],sbl[1]) def getBBoxBL(self): # Geotiff CS to Interface CS return (self.getBL((0,0)),self.getBL((self.gt.RasterXSize,self.gt.RasterYSize))) def sanitizedBounds(self, bbox=None): if bbox is None: bbox=self.getBBoxBL() tl,br=bbox bmin, bmax = tl[0], br[0] if bmin>bmax: bmin, bmax = bmax, bmin lmin, lmax = tl[1], br[1] if lmin>lmax: lmin, lmax = lmax, lmin return ((bmin,bmax,lmin,lmax)) def getIntersection(self, bboxBL): bbox=self.sanitizedBounds(bboxBL) sbbox=self.sanitizedBounds() bmin=max(bbox[0],sbbox[0]) bmax=min(bbox[1],sbbox[1]) lmin=max(bbox[2],sbbox[2]) lmax=min(bbox[3],sbbox[3]) if lmax < lmin or bmax < bmin: # No intersection return None return ((bmax,lmin),(bmin,lmax)) # North-East, South-West def getUV(self, srcBL): gtBL = self.transS2G.TransformPoint(srcBL[1], srcBL[0]) bl=np.array([[gtBL[0]],[gtBL[1]]]) uv = np.dot(self.iaf, bl-self.offset) return (uv[0][0], uv[1][0]) def getLandscapeBBox(lp): # search for landscape proxy actors w=el.get_all_level_actors() theFirst=True for a in w: if(a.get_class().get_name().startswith("Landscape") and not a.get_class().get_name().startswith("LandscapeGizmo")): #print("Landscape Found : "+ a.get_name()) o,box=a.get_actor_bounds(True) h=o+box l=o-box if(theFirst): lx=l.x ly=l.y hx=h.x hy=h.y theFirst=False else: if(lx>l.x): lx=l.x if(ly>l.y): ly=l.y if(hx<h.x): hx=h.x if(hy<h.y): hy=h.y print("Landscape bounding box: ({0}, {1} - {2}, {3})".format(lx,ly,hx,hy)) print("Landscape size: {0} x {1}".format(hx-lx,hy-ly)) size=(int((hx-lx)/lp.stepSize+1),int((hy-ly)/lp.stepSize+1)) print("Landscape grid size: {0}".format(size)) return (lx,ly,hx,hy,size) def getGeoReference(): w=el.get_all_level_actors() theFirst=True for a in w: if(a.get_class().get_name().startswith("GeoReferenceBP")): print("GeoReference Found") ref=a ref.initialize_geo_conv() return ref class LayerGenerator: # lp: LandscapeParams def __init__(self, lp): self.lp=lp # Landscape quad in BL coordinate lx,ly,hx,hy,size=getLandscapeBBox(lp) self.size=size self.ref=getGeoReference() self.tl=tuple(map(Decode60, self.ref.get_bl(lx,ly))) self.bl=tuple(map(Decode60, self.ref.get_bl(lx,hy))) self.br=tuple(map(Decode60, self.ref.get_bl(hx,hy))) self.tr=tuple(map(Decode60, self.ref.get_bl(hx,ly))) print("Reference Quad=tl:{0} bl:{1} br:{2} tr:{3}".format(self.tl, self.bl, self.br, self.tr)) self.zo=self.ref.get_actor_location() self.zobl=tuple(map(Decode60, self.ref.get_bl(self.zo.x,self.zo.y))) print("GeoReference in BL {0} {1}".format(self.zobl[0], self.zobl[1])) print("GeoReference in UE {0}".format(self.zo)) # Clip lowest height [m] (None for no clipping) def setZClipping(self, zClipping): self.zClipping=zClipping def resample(self, sourceFile, slow_task): # Landscape quad on geotiff image in UV coordinate gt=GeoTIFF(sourceFile,self.lp) tluv=gt.getUV(self.tl) bluv=gt.getUV(self.bl) bruv=gt.getUV(self.br) truv=gt.getUV(self.tr) zouv=gt.getUV(self.zobl) uvquad=tluv+bluv+bruv+truv if self.zClipping is not None: imageref=Image.new(gt.image.mode,gt.image.size,self.zClipping) clippedimg=ImageMath.eval("max(a,b)",a=gt.image,b=imageref) #clippedimg.save(os.path.join(projdir,"Assets","clipped.tif")) else: clippedimg=gt.image # resample geotiff image slow_task.enter_progress_frame(1,"Transforming image region") img=clippedimg.transform(self.size,Image.QUAD,data=uvquad,resample=Image.BICUBIC)#, fillcolor=sys.float.min) slow_task.enter_progress_frame(1,"Transforming height values") zov=gt.image.getpixel(zouv) zos=32768-(zov*self.lp.zEnhance-self.zo.z/100.)*self.lp.toUEScale # 32768: mid point (height=0) # convert height value [m] to unreal height value slow_task.enter_progress_frame(1,"Converting to 16bit grayscale") iarrf=np.array(img.getdata())*self.lp.toUEScale*self.lp.zEnhance + zos return iarrf.clip(0,65535), img.size
#Author Josh Whiteside 18/project/ import unreal def get_all_level_boundaries(): r = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(),unreal.LevelStreamingVolume) return r def get_closest_level_boundary(a,boundaries): largestLength = 99999999999 #that should do it. for b in boundaries: tempVector = b.get_actor_transform().translation.subtract(a.get_actor_transform().translation) tempLength = tempVector.length() if tempLength < largestLength: l = b largestLength = tempLength return l def main(): selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() level_boundaries = get_all_level_boundaries() total_frames = len(selected_actors) text_label = "Sorting objects" with unreal.ScopedSlowTask(total_frames, text_label) as slow_task: slow_task.make_dialog(True) for x in selected_actors: if slow_task.should_cancel(): break b = get_closest_level_boundary(x, level_boundaries) #Calls c++ function that will find the level streaming of the respective name ls = unreal.LevelBoundarySortUtilities.get_level_streaming_from_name(b.streaming_level_names[0],x) a = [x] #Puts the current actor in an array for move actors to level (EditorLevelUtils wants it in an array) #moves actors to level unreal.EditorLevelUtils.move_actors_to_level(a,ls,True) slow_task.enter_progress_frame(1) main()
# -*- coding: utf-8 -*- import logging import unreal import inspect import types import Utilities from collections import Counter class attr_detail(object): def __init__(self, obj, name:str): self.name = name attr = None self.bCallable = None self.bCallable_builtin = None try: if hasattr(obj, name): attr = getattr(obj, name) self.bCallable = callable(attr) self.bCallable_builtin = inspect.isbuiltin(attr) except Exception as e: unreal.log(str(e)) self.bProperty = not self.bCallable self.result = None self.param_str = None self.bEditorProperty = None self.return_type_str = None self.doc_str = None self.property_rw = None if self.bCallable: self.return_type_str = "" if self.bCallable_builtin: if hasattr(attr, '__doc__'): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) # print(f"~~~~~ attr: {self.name} docForDisplay: {docForDisplay} paramStr: {paramStr}") # print(attr.__doc__) try: sig = inspect.getargspec(getattr(obj, self.name)) # print("+++ ", sig) args = sig.args argCount = len(args) if "self" in args: argCount -= 1 except TypeError: argCount = -1 if "-> " in docForDisplay: self.return_type_str = docForDisplay[docForDisplay.find(')') + 1:] else: self.doc_str = docForDisplay[docForDisplay.find(')') + 1:] if argCount == 0 or (argCount == -1 and paramStr == ''): # Method with No params if '-> None' not in docForDisplay or self.name in ["__reduce__", "_post_init"]: try: if name == "get_actor_time_dilation" and isinstance(obj, unreal.Object): # call get_actor_time_dilation will crash engine if actor is get from CDO and has no world. if obj.get_world(): # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() else: self.result = "skip call, world == None." else: # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() except: self.result = "skip call.." else: print(f"docForDisplay: {docForDisplay}, self.name: {self.name}") self.result = "skip call." else: self.param_str = paramStr self.result = "" else: logging.error("Can't find p") elif self.bCallable_other: if hasattr(attr, '__doc__'): if isinstance(attr.__doc__, str): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) if name in ["__str__", "__hash__", "__repr__", "__len__"]: try: self.result = "{}".format(attr.__call__()) except: self.result = "skip call." else: # self.result = "{}".format(getattr(obj, name)) self.result = getattr(obj, name) def post(self, obj): if self.bOtherProperty and not self.result: try: self.result = getattr(obj, self.name) except: self.result = "skip call..." def apply_editor_property(self, obj, type_, rws, descript): self.bEditorProperty = True self.property_rw = "[{}]".format(rws) try: self.result = eval('obj.get_editor_property("{}")'.format(self.name)) except: self.result = "Invalid" def __str__(self): s = f"Attr: {self.name} paramStr: {self.param_str} desc: {self.return_type_str} result: {self.result}" if self.bProperty: s += ", Property" if self.bEditorProperty: s += ", Eidtor Property" if self.bOtherProperty: s += ", Other Property " if self.bCallable: s += ", Callable" if self.bCallable_builtin: s += ", Callable_builtin" if self.bCallable_other: s += ", bCallable_other" if self.bHasParamFunction: s+= ", bHasParamFunction" return s def check(self): counter = Counter([self.bOtherProperty, self.bEditorProperty, self.bCallable_other, self.bCallable_builtin]) # print("counter: {}".format(counter)) if counter[True] == 2: unreal.log_error(f"{self.name}: {self.bEditorProperty}, {self.bOtherProperty} {self.bCallable_builtin} {self.bCallable_other}") @property def bOtherProperty(self): if self.bProperty and not self.bEditorProperty: return True return False @property def bCallable_other(self): if self.bCallable and not self.bCallable_builtin: return True return False @property def display_name(self, bRichText=True): if self.bProperty: return f"\t{self.name}" else: # callable if self.param_str: return f"\t{self.name}({self.param_str}) {self.return_type_str}" else: if self.bCallable_other: return f"\t{self.name}" # __hash__, __class__, __eq__ 等 else: return f"\t{self.name}() {self.return_type_str}" @property def display_result(self) -> str: if self.bEditorProperty: return "{} {}".format(self.result, self.property_rw) else: return "{}".format(self.result) @property def bHasParamFunction(self): return self.param_str and len(self.param_str) != 0 def ll(obj): if not obj: return None if inspect.ismodule(obj): return None result = [] for x in dir(obj): attr = attr_detail(obj, x) result.append(attr) if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object): editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj) for name, type_, rws, descript in editorPropertiesInfos: # print(f"~~ {name} {type} {rws}, {descript}") index = -1 for i, v in enumerate(result): if v.name == name: index = i break if index != -1: this_attr = result[index] else: this_attr = attr_detail(obj, name) result.append(this_attr) # unreal.log_warning(f"Can't find editor property: {name}") this_attr.apply_editor_property(obj, type_, rws, descript) for i, attr in enumerate(result): attr.post(obj) return result def _simplifyDoc(content): def next_balanced(content, s="(", e = ")" ): s_pos = -1 e_pos = -1 balance = 0 for index, c in enumerate(content): match = c == s or c == e if not match: continue balance += 1 if c == s else -1 if c == s and balance == 1 and s_pos == -1: s_pos = index if c == e and balance == 0 and s_pos != -1 and e_pos == -1: e_pos = index return s_pos, e_pos return -1, -1 # bracketS, bracketE = content.find('('), content.find(')') if not content: return "", "" bracketS, bracketE = next_balanced(content, s='(', e = ')') arrow = content.find('->') funcDocPos = len(content) endSign = ['--', '\n', '\r'] for s in endSign: p = content.find(s) if p != -1 and p < funcDocPos: funcDocPos = p funcDoc = content[:funcDocPos] if bracketS != -1 and bracketE != -1: param = content[bracketS + 1: bracketE].strip() else: param = "" return funcDoc, param def _getEditorProperties(content, obj): # print("Content: {}".format(content)) lines = content.split('\r') signFound = False allInfoFound = False result = [] for line in lines: if not signFound and '**Editor Properties:**' in line: signFound = True if signFound: #todo re # nameS, nameE = line.find('``') + 2, line.find('`` ') nameS, nameE = line.find('- ``') + 4, line.find('`` ') if nameS == -1 or nameE == -1: continue typeS, typeE = line.find('(') + 1, line.find(')') if typeS == -1 or typeE == -1: continue rwS, rwE = line.find('[') + 1, line.find(']') if rwS == -1 or rwE == -1: continue name = line[nameS: nameE] type_str = line[typeS: typeE] rws = line[rwS: rwE] descript = line[rwE + 2:] allInfoFound = True result.append((name, type_str, rws, descript)) # print(name, type, rws) if signFound: if not allInfoFound: unreal.log_warning("not all info found {}".format(obj)) else: unreal.log_warning("can't find editor properties in {}".format(obj)) return result def log_classes(obj): print(obj) print("\ttype: {}".format(type(obj))) print("\tget_class: {}".format(obj.get_class())) if type(obj.get_class()) is unreal.BlueprintGeneratedClass: generatedClass = obj.get_class() else: generatedClass = unreal.PythonBPLib.get_blueprint_generated_class(obj) print("\tgeneratedClass: {}".format(generatedClass)) print("\tbp_class_hierarchy_package: {}".format(unreal.PythonBPLib.get_bp_class_hierarchy_package(generatedClass))) def is_selected_asset_type(types): selectedAssets = Utilities.Utils.get_selected_assets() for asset in selectedAssets: if type(asset) in types: return True; return False
import unreal output_list:list[list[str, str]] = [[]] selected_assets:list[unreal.Object] = unreal.EditorUtilityLibrary.get_selected_assets() asset_index = 0 for asset in selected_assets: loaded_asset = unreal.EditorAssetLibrary.load_asset(asset.get_path_name().split('.')[0]) all_metadata = unreal.EditorAssetLibrary.get_metadata_tag_values(loaded_asset) for tag_name, value in all_metadata.items(): output_list[asset_index]=[str(tag_name), value] unreal.log("Value of tag " + str(tag_name) + " for asset " + ": " + value) asset_index += 1 print(output_list)
import unreal file_a = "/project/.fbx" file_b = "/project/.fbx" imported_scenes_path = "/project/" print 'Preparing import options...' advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions() advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512) advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64) advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True) advanced_mesh_options.set_editor_property('remove_degenerates', True) base_options = unreal.DatasmithImportBaseOptions() base_options.set_editor_property('include_geometry', True) base_options.set_editor_property('include_material', True) base_options.set_editor_property('include_light', True) base_options.set_editor_property('include_camera', True) base_options.set_editor_property('include_animation', True) base_options.set_editor_property('static_mesh_options', advanced_mesh_options) base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL) base_options.set_editor_property('asset_options', []) # Not used vred_options = unreal.DatasmithVREDImportOptions() vred_options.set_editor_property('merge_nodes', False) vred_options.set_editor_property('optimize_duplicated_nodes', False) vred_options.set_editor_property('import_var', True) vred_options.set_editor_property('var_path', "") vred_options.set_editor_property('import_light_info', True) vred_options.set_editor_property('light_info_path', "") vred_options.set_editor_property('import_clip_info', True) vred_options.set_editor_property('clip_info_path', "") vred_options.set_editor_property('textures_dir', "") vred_options.set_editor_property('import_animations', True) vred_options.set_editor_property('intermediate_serialization', unreal.DatasmithVREDIntermediateSerializationType.DISABLED) vred_options.set_editor_property('colorize_materials', False) vred_options.set_editor_property('generate_lightmap_u_vs', False) vred_options.set_editor_property('import_animations', True) # Direct import to scene and assets: print 'Importing directly to scene...' unreal.VREDLibrary.import_(file_a, imported_scenes_path, base_options, None, True) #2-stage import step 1: print 'Parsing to scene object...' scene = unreal.DatasmithVREDSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, vred_options) print 'Resulting datasmith scene: ' + str(scene) print '\tProduct name: ' + str(scene.get_product_name()) print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors())) print '\tLight actor count: ' + str(len(scene.get_all_light_actors())) print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors())) print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors())) print '\tMaterial count: ' + str(len(scene.get_all_materials())) print '\tAnimNode count: ' + str(len(scene.get_all_anim_nodes())) print '\tAnimClip count: ' + str(len(scene.get_all_anim_clips())) print '\tExtra light info count: ' + str(len(scene.get_all_extra_lights_info())) print '\tVariant count: ' + str(len(scene.get_all_variants())) # Modify one of the AnimNodes # Warning: The AnimNode nested structure is all USTRUCTs, which are value types, and the Array accessor returns # a copy. Meaning something like anim_nodes[0].name = 'new_name' will set the name on the COPY of anim_nodes[0] anim_nodes = scene.get_all_anim_nodes() if len(anim_nodes) > 0: node_0 = anim_nodes[0] old_name = node_0.name print 'Anim node old name: ' + old_name node_0.name += '_MODIFIED' modified_name = node_0.name print 'Anim node modified name: ' + modified_name anim_nodes[0] = node_0 scene.set_all_anim_nodes(anim_nodes) # Check modification new_anim_nodes = scene.get_all_anim_nodes() print 'Anim node retrieved modified name: ' + new_anim_nodes[0].name assert new_anim_nodes[0].name == modified_name, "Node modification didn't work!" # Restore to previous state node_0 = new_anim_nodes[0] node_0.name = old_name new_anim_nodes[0] = node_0 scene.set_all_anim_nodes(new_anim_nodes) # 2-stage import step 2: print 'Importing assets and actors...' result = scene.import_scene() print 'Import results: ' print '\tImported actor count: ' + str(len(result.imported_actors)) print '\tImported mesh count: ' + str(len(result.imported_meshes)) print '\tImported level sequences: ' + str([a.get_name() for a in result.animations]) print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name()) if result.import_succeed: print 'Import succeeded!' else: print 'Import failed!'
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
20