示例#1
0
def main():
    """Execute the main functionality of the example script"""
    locations = []
    for x in range(ACTOR_COUNT_DIMENSIONS[0]):
        for y in range(ACTOR_COUNT_DIMENSIONS[1]):
            for z in range(ACTOR_COUNT_DIMENSIONS[2]):
                locations.append((x * ACTOR_SEPARATION_DISTANCE,
                                  y * ACTOR_SEPARATION_DISTANCE,
                                  z * ACTOR_SEPARATION_DISTANCE))

    total_frames = len(locations)
    text_label = 'Generating Example Sequence'

    new_sequence = create_new_level_sequence('/Game', 'ExamplePythonSequence')
    with unreal.ScopedSlowTask(total_frames, text_label) as example_task:
        example_task.make_dialog(True)
        for cube_location in locations:
            if example_task.should_cancel():
                break

            cube = spawn_actor(unreal.Vector(*cube_location))

            # Add the cube to the generated sequence
            add_actor_to_sequence(new_sequence, cube)

            # Move the progress bar
            example_task.enter_progress_frame()

    # Automatically open the sequence
    unreal.AssetToolsHelpers.get_asset_tools().open_editor_for_assets(
        [new_sequence])
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)
示例#3
0
    def get_dict(self):
        info = {}
        with tempfile.TemporaryDirectory() as temp_dir:
            total_frames =  len(self)
            with unreal.ScopedSlowTask(total_frames, "Getting Info...") as slow_task:
                slow_task.make_dialog(True)

                for name, texture in self.items():

                    slow_task.enter_progress_frame(1, 'Getting Info: ' + name)

                    if slow_task.should_cancel():
                        raise BaseException("Aborted.")

                    t3d_filename = os.path.join(temp_dir, name + '.t3d')
                    unreal.ObjectExporterT3D.run_asset_export_task(get_export_task(t3d_filename , texture))

                    with open(t3d_filename, 'r',encoding='utf-8') as t3d_file:
                        t3d = parse_t3d(t3d_file.readlines())

                    format = t3d['subitems'][0]['attrs']['Source']['Format']

                    info[name] = {
                        'flip_green_channel': texture.flip_green_channel,
                        'is_bugged_bgr': format == "TSF_RGBA16",
                        'format': format
                    }
        return info
示例#4
0
def unreal_progress(tasks):
    with unreal.ScopedSlowTask(len(tasks), u"读取资源") as task:
        task.make_dialog(True)
        for i, item in enumerate(tasks):
            if task.should_cancel():
                break
            task.enter_progress_frame(1, "进度 %s/%s" % (i, len(tasks)))
            yield i, item
示例#5
0
def setMaterialBySlotName():

    # Gets all materials instances & material slot info dict
    materials = getMaterialInstances()
    slot_info = getMaterialSlotInformation()

    # Collects the name of our materials and their paths
    material_asset_name = [str(m.asset_name) for m in materials]
    material_paths = [str(m.object_path) for m in materials]

    # Create a dictionary from two lists with the material name used as the key
    material_dictionary = dict(zip(material_asset_name, material_paths))

    # Dumps dictionary into a json file
    # with open(material_list, "w") as write_file:
    # json.dump(material_dictionary, write_file, sort_keys=True, indent=4)

    # Retrieves the value information for each slot
    material_slot_values = [v.values() for v in slot_info]

    # Begins a slow task dialog box for unique material slot
    with unreal.ScopedSlowTask(len(material_slot_values)) as slow_task:
        slow_task.make_dialog(True)
        for x in range(len(material_slot_values)):
            # Add an option to cancel out of the material assignment
            if slow_task.should_cancel():
                break
            slow_task.enter_progress_frame(
                1,
                "Assigning materials to slots... " + str(x) + " / " +
                str(len(material_slot_values)),
            )
            for v in material_slot_values:
                material_index = v[0]
                material_name = v[1]
                # Runs a check to find a match material in our library
                if material_name in material_dictionary:

                    # Collects  our static mesh
                    static_mesh = getMeshes()
                    mesh = static_mesh[0]
                    # print 'found ' + material_name

                    # Sets the material path for our material
                    material_path = material_dictionary[material_name]

                    # Iterates over each static mesh, takes our material slot info, and sets the material
                    for d in mesh:
                        mesh_path = d.get_full_name()
                        mesh_example = unreal.EditorAssetLibrary.load_asset(
                            mesh_path)
                        material_example = unreal.EditorAssetLibrary.load_asset(
                            material_path)
                        mesh_example.set_material(int(material_index),
                                                  material_example)
                else:
                    pass
                    print("no matches found")
示例#6
0
def unreal_progress(tasks, label=u"进度", total=None):
    total = total if total else len(tasks)
    with unreal.ScopedSlowTask(total, label) as task:
        task.make_dialog(True)
        for i, item in enumerate(tasks):
            if task.should_cancel():
                break
            task.enter_progress_frame(1, "%s %s/%s" % (label, i, total))
            yield i, item
示例#7
0
    def execute(cls, label, callback, iteratable):
        if len(iteratable) != 0:
            with unreal.ScopedSlowTask(len(iteratable), label) as task:
                task.make_dialog(True)

                for row in iteratable:
                    if task.should_cancel():
                        break

                    callback(row)
                    task.enter_progress_frame(1)
示例#8
0
    def map(cls, label, callback, iteratable):
        result = []
        if len(iteratable) != 0:
            with unreal.ScopedSlowTask(len(iteratable), label) as task:
                task.make_dialog()

                result = map(
                    lambda x: ProcessSlotTask.map_internal(task, x, callback),
                    iteratable)

        return result
示例#9
0
def executeSlowTask_EXAMPLE():
    quantity_steps_in_slow_task = 1000
    with unreal.ScopedSlowTask(quantity_steps_in_slow_task,
                               'My Slow Task Text ...') as slow_task:
        slow_task.make_dialog(True)
        for x in range(quantity_steps_in_slow_task):
            if slow_task.should_cancel_EXAMPLE():
                break
            slow_task.enter_progress_frame(
                1, 'My Slow Task Text ... ' + str(x) + ' / ' +
                str(quantity_steps_in_slow_task))
            # Execute slow logic here
            print 'Executing Slow Task'
def executeSlowTask():
    quantity_steps_in_slow_task = 10
    with unreal.ScopedSlowTask(quantity_steps_in_slow_task,
                               'My Slow Task Text ...') as slow_task:
        slow_task.make_dialog(True)
        for x in range(quantity_steps_in_slow_task):
            if slow_task.should_cancel():
                break
            slow_task.enter_progress_frame(
                1, 'My Slow Task Text ...' + str(x) + ' / ' +
                str(quantity_steps_in_slow_task))
            # Execute slow logic
            deferredSpawnActor()
            time.sleep(1)
示例#11
0
def export(assets, dir_path):
    
    textures = Textures()
    materials = Materials(textures)
    meshes = Meshes(materials)
    
    for asset in assets:

        type = asset.__class__.__name__
    
        if type in ('StaticMesh', 'SkeletalMesh'):
            meshes.append(asset)

        elif type in ('Material', 'MaterialInstanceConstant'):
            materials.append(asset)
            
        elif type in ('Texture2D', 'Texture'):
            textures.append(asset)

        else:
            print(f"Asset '{asset.get_name()}' has unsupported type '{type}'.")
    
    if not any((textures, materials, meshes)):
        return
    
    os.makedirs(dir_path, exist_ok = True)

    texture_info = textures.get_dict()
    info = { 
        "meshes": meshes.get_dict(), 
        "materials": materials.get_dict(texture_info),
        "textures": texture_info
    }
    
    info_path = os.path.join(dir_path, "__unreal_assets__.json")
    with open(info_path, 'w') as info_file:
        json.dump(info, info_file, indent = 4, ensure_ascii = False)

    total_frames =  len(textures) + len(meshes)
    with unreal.ScopedSlowTask(total_frames, "Exporting...") as slow_task:
        slow_task.make_dialog(True)
        
        import itertools
        for name in itertools.chain(textures.export_iter(dir_path, texture_info), meshes.export_iter(dir_path)):
            if slow_task.should_cancel():
                break
            slow_task.enter_progress_frame(1, 'Exporting: ' + name)
示例#12
0
def spawn_preview_mesh():
    materials = get_material_instances()
    material_asset_name = [str(m.asset_name) for m in materials]
    material_paths = [str(m.object_path) for m in materials]
    material_dictionary = sorted(dict(zip(material_asset_name, material_paths)), reverse=True)
    mesh = get_mesh_by_name()

    with unreal.ScopedSlowTask(len(material_dictionary), 'Spawning meshes... ') as slow_task:
        slow_task.make_dialog(True)
        for x in range(len(material_dictionary)):
            if slow_task.should_cancel():
                break
            slow_task.enter_progress_frame(1, 'Assigning meshes... ' + str(x) + ' / ' + str(len(material_dictionary)))
            # unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor.static_class(), unreal.Vector(
            # 0, 0, 0), unreal.Rotator(0, 0, 0))
    for d in material_dictionary:
        print(d)
示例#13
0
def delete_unused_assets():
	editorAssetLib = GetEditorAssetLibrary()
	workingPath = "/Game"
	allAssets = editorAssetLib.list_assets(workingPath, True, False)
	processingAssetPath = ""
	allAssetsCount = len(allAssets)
	if ( allAssetsCount > 0):
		with unreal.ScopedSlowTask(allAssetsCount, processingAssetPath) as slowTask:
			slowTask.make_dialog(True)
			for asset in allAssets:
				processingAssetPath = asset
				deps = editorAssetLib.find_package_referencers_for_asset(asset, False)
				if (len(deps) <= 0):
					print ">>> Deleting >>> %s" % asset
					editorAssetLib.delete_asset(asset)
				if slowTask.should_cancel():
					break
				slowTask.enter_progress_frame(1, processingAssetPath)
示例#14
0
def prefix_all_assets():
	#You can set the prefix of your choice here
	prefixAnimationBlueprint    = "Anim_BP"
	prefixAnimationSequence     = "Seq"
	prefixAnimation             = "Anim"
	prefixBlendSpace            = "BS"
	prefixBlueprint             = "BP"
	prefixCurveFloat            = "crvF"
	prefixCurveLinearColor      = "crvL"
	prefixLevel                 = "Lv"
	prefixMaterial              = "M"
	prefixMaterialFunction      = "MF"
	prefixMaterialInstance      = "MI"
	prefixParticleSystem        = "FX"
	prefixPhysicsAsset          = "Phy"
	prefixSkeletalMesh          = "SKM"
	prefixSkeleton              = "SK"
	prefixSoundCue              = "Cue"
	prefixSoundWave             = "wv"
	prefixStaticMesh            = "SM"
	prefixTexture2D             = "T"
	prefixTextureCube           = "HDRI"

	def GetProperPrefix(className):
		_prefix = ""
		if className == "AnimBlueprint":
			_prefix = prefixAnimationBlueprint
		elif className == "AnimSequence":
			_prefix = prefixAnimationSequence
		elif className == "Animation":
			_prefix = prefixAnimation
		elif className == "BlendSpace1D":
			_prefix = prefixBlendSpace
		elif className == "Blueprint":
			_prefix = prefixBlueprint
		elif className == "CurveFloat":
			_prefix = prefixCurveFloat
		elif className == "CurveLinearColor":
			_prefix = prefixCurveLinearColor
		elif className == "Material":
			_prefix = prefixMaterial
		elif className == "MaterialFunction":
			_prefix = prefixMaterialFunction
		elif className == "MaterialInstance":
			_prefix = prefixMaterialInstance
		elif className == "ParticleSystem":
			_prefix = prefixParticleSystem
		elif className == "PhysicsAsset":
			_prefix = prefixPhysicsAsset
		elif className == "SkeletalMesh":
			_prefix = prefixSkeletalMesh
		elif className == "Skeleton":
			_prefix = prefixSkeleton
		elif className == "SoundCue":
			_prefix = prefixSoundCue
		elif className == "SoundWave":
			_prefix = prefixSoundWave
		elif className == "StaticMesh":
			_prefix = prefixStaticMesh
		elif className == "Texture2D":
			_prefix = prefixTexture2D
		elif className == "TextureCube":
			_prefix = prefixTextureCube
		else:
			_prefix = ""
		return _prefix

	editorAssetLib = GetEditorAssetLibrary()
	workingPath = "/Game"
	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()
			_assetPathOnly = _assetPathName.replace((_assetName + "." + _assetName), "")
			_assetClassName = _assetData.get_asset().get_class().get_name()
			_assetPrefix = GetProperPrefix(_assetClassName)

			if _assetPrefix in _assetName:
				continue
			elif _assetPrefix == "":
				continue
			else:
				_targetPathName = _assetPathOnly + ("%s%s%s%s%s%s%s" % (_assetPrefix, "_", _assetName, ".", _assetPrefix, "_", _assetName))

				editorAssetLib.rename_asset(_assetPathName, _targetPathName)
				print ">>> Renaming [%s] to [%s]" % (_assetPathName, _targetPathName)

			if slowTask.should_cancel():
				break
			slowTask.enter_progress_frame(1, asset)
import unreal

# Collect all assets
all_asset_string = unreal.EditorAssetLibrary.list_assets("/Game/", True, False)
num_target_assets = len(all_asset_string)

referenced_assets = []
non_referenced_assets = []

with unreal.ScopedSlowTask(num_target_assets) as slow_find_task:
    slow_find_task.make_dialog(True)
    for asset_string in all_asset_string:
        asset_data = unreal.EditorAssetLibrary.find_asset_data(asset_string)
        if (asset_data.is_valid() and not asset_data.is_redirector()):
            # Find referencers
            referencers = unreal.EditorAssetLibrary.find_package_referencers_for_asset(
                asset_string, False)

            if (len(referencers) > 0):
                referenced_assets.append(asset_string)
            else:
                non_referenced_assets.append(asset_string)

        # if pressed "Cancel" button on dialog, task is cancel.
        if slow_find_task.should_cancel():
            print("Task cancelled.")
            del referenced_assets[:]
            del non_referenced_assets[:]
            break

        # Advance progress
示例#16
0
                # save level
                saved_level = unreal.EditorLevelLibrary.save_all_dirty_levels()
                if not saved_level:
                    print("Error: Cannot save level")
    return


# get the number of JT files in the directory
nb_jt_files = count_jt_files_in_directory(input_directory)

# global variable
file_index = 0

# progress bar
with unreal.ScopedSlowTask(nb_jt_files, "Data Preparation") as slow_task:
    slow_task.make_dialog(True)

    level_path = content_folder + "/ImportedLevel"
    if unreal.EditorAssetLibrary.does_asset_exist(level_path):
        # if the level already exists, we just load it
        unreal.EditorLevelLibrary.load_level(level_path)
    else:
        # create a new level to hold the imported scene
        created_new_level = unreal.EditorLevelLibrary.new_level_from_template(
            level_path, "/Engine/Maps/Templates/Template_Default")
        if not created_new_level:
            print("Error: Cannot create new level")
            quit()

    process_directory(input_directory, None, slow_task)
示例#17
0
import unreal
import time

total_frames = 90
text_label = 'Working...'
with unreal.ScopedSlowTask(total_frames, text_label) as slow_task:
    slow_task.make_dialog(True)
    for i in range(total_frames):
        if slow_task.should_cancel():
            break
        slow_task.enter_progress_frame(1)
        time.sleep(1)
        print(i)
示例#18
0
start_time = time.time()

# instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
editor_asset_lib = unreal.EditorAssetLibrary()

# get the selected assets
selected_assets = editor_util.get_selected_assets()
num_assets = len(selected_assets)
num_copies = 50
total_num_copies = num_assets * num_copies
text_label = "Duplicating Assets"
running = True

with unreal.ScopedSlowTask(total_num_copies, text_label) as slow_task:
    slow_task.make_dialog(True)

    for asset in selected_assets:
        # get the asset name and path to be duplicate
        asset_name = asset.get_fname()
        asset_path = editor_asset_lib.get_path_name_for_loaded_asset(asset)
        source_path = os.path.dirname(asset_path)

        for i in range(num_copies):
            # if user pressed the cancel button, stop duplicate
            if slow_task.should_cancel():
                running = False
                break

            new_name = "{}_{}".format(asset_name, i)
示例#19
0
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)
示例#20
0
    for a in w:
        if (a.get_class().get_name().startswith("GeoReferenceBP")):
            print("GeoReference Found")
            ref = a
    ref.initialize_geo_conv()
    return ref


# ----------------------------------------------------------------------------------------

lx, ly, hx, hy, size = getLandscapeBBox()
ref = getGeoReference()

text_label = "Projecting coordinates"
nFrames = 5
with unreal.ScopedSlowTask(nFrames, text_label) as slow_task:
    slow_task.make_dialog(True)

    tl = tuple(map(Decode60, ref.get_bl(lx, ly)))
    bl = tuple(map(Decode60, ref.get_bl(lx, hy)))
    br = tuple(map(Decode60, ref.get_bl(hx, hy)))
    tr = tuple(map(Decode60, ref.get_bl(hx, ly)))
    print("Reference Quad=tl:{0} bl:{1} br:{2} tr:{3}".format(tl, bl, br, tr))
    zo = ref.get_actor_location()
    zobl = tuple(map(Decode60, ref.get_bl(zo.x, zo.y)))
    print("GeoReference in BL {0} {1}".format(zobl[0], zobl[1]))
    print("GeoReference in UE {0}".format(zo))
    print(ref.get_xy(Encode60(zobl[0]), Encode60(zobl[1])))

    gt = GeoTIFF(inputGeotiff)
    tluv = gt.getUV(tl)
示例#21
0
import random
import unreal

all_actors = unreal.EditorLevelLibrary.get_all_level_actors()

unreal.log_warning("total actors: {}".format(len(all_actors)))

#for act in all_actors:
#	name = act.get_name()
#	rand = random.randint(1,100)
#	if(name.startswith("SM_ProductWithAN") and rand < 25):
#		unreal.log_warning("delete {}".format(name))
#		act.destroy_actor()

with unreal.ScopedSlowTask(len(all_actors), "Removing Products Randomly") as slow_task:
	slow_task.make_dialog(True)
	frame = 1
	for act in all_actors:
		if slow_task.should_cancel():
			break
		frame += 1
		slow_task.enter_progress_frame(frame)
		
		name = act.get_name()
		rand = random.randint(1,100)
		if(name.startswith("SM_ProductWithAN") and rand < 75):
			unreal.log_warning("delete {}".format(name))
			act.destroy_actor()
workingPath = "/Game/"


@unreal.uclass()
class GetEditorAssetLibrary(unreal.EditorAssetLibrary):
    pass


editorAssetLib = GetEditorAssetLibrary()

processAssetPath = ""

allAssets = editorAssetLib.list_assets(workingPath, True, False)
allAssetsCount = len(allAssets)

with unreal.ScopedSlowTask(allAssetsCount, processAssetPath) as slowTask:
    slowTask.make_dialog(True)
    for processAsset in allAssets:
        _processAssetData = editorAssetLib.find_asset_data(processAsset)
        _processAsset = _processAssetData.get_asset()
        _processAssetName = _processAssetData.get_asset().get_name()
        processAssetPath = _processAssetData.get_asset().get_path_name()

        assetsMatching = []

        for asset in allAssets:
            _assetData = editorAssetLib.find_asset_data(asset)
            _assetName = _assetData.get_asset().get_name()

            if (_assetName == _processAssetName):
                if (asset != processAssetPath):
示例#23
0
___________________________________
""")

editor_selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
content_browser_selected_assets = unreal.EditorUtilityLibrary.get_selected_assets(
)
if not editor_selected_actors or not content_browser_selected_assets:
    unreal.log_warning(
        "Select actors from the level to be replaced with the asset selected from the content browser!"
    )
else:
    asset_name = content_browser_selected_assets[0].get_full_name()
    loading_text = "Replacing actors..."
    actors_count = len(editor_selected_actors)

    with unreal.ScopedSlowTask(actors_count, loading_text) as ST:
        ST.make_dialog(True)
        for actor in editor_selected_actors:
            if ST.should_cancel():
                break

            # Get actor rotation
            rotation = actor.get_actor_eyes_view_point()[1]
            # Get actor position
            location = actor.get_actor_location()
            # Get actor name
            actor_name = actor.get_name()
            # Spawn asset at [location, rotation]
            unreal.EditorLevelLibrary.spawn_actor_from_object(
                content_browser_selected_assets[0], location, rotation)
            # Delete actor