コード例 #1
0
    def readTextureCSV(self):
        #TODO: search for texture in directory and link to that if it exists (swap in materials csv?)
        #TODO: figure out how to mark a texture as used in the surfaces directory in blender. Can do in UE4
        try:
            with open(self.textureCSVPath, mode='r') as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                line_count = 0
                parameterNames = []
                for row in csv_reader:
                    if line_count == 0:
                        unreal.log("Parameters To Import: " + " | ".join(row))
                        parameterNames = row
                        line_count += 1
                    else:
                        #Add texture to import list
                        self.createTexture(
                            filepath=row[1],
                            importLocation=self.UETextureDirectory,
                            overwrite=row[4],
                            textureName=row[0])
                        line_count += 1

                unreal.log('Processed ' + str(line_count - 1) + ' textures')
                unreal.EditorAssetLibrary.save_directory(
                    self.UETextureDirectory)
        except Exception:
            unreal.log_warning("Issue reading texture csv file")
コード例 #2
0
    def createTexture(self , filepath = '', importLocation = '' , overwrite = "" , textureName = "test"):
        import_tasks = []
        
        if overwrite == "y" or overwrite == "True" or overwrite == "yes" or overwrite == "Y" or overwrite == "TRUE" or overwrite == "true":
            replace = True
            
        else:
            replace = False
        if "." in textureName:
            textureName = textureName.split(".")[0]
        textureName = self.legalizeName(textureName)
        
        
        
        if unreal.EditorAssetLibrary.does_asset_exist(importLocation + '/' +  textureName):# or not replace:
            unreal.log_warning("texture " + textureName + " already exists, skipping")
        else:
            if not os.path.exists(filepath):
                if os.path.exists(os.path.join(UEImporter.rootImportFolder,filepath)):
                    filepath = os.path.join(UEImporter.rootImportFolder,filepath)
                else:
                    filepath = os.path.join(UEImporter.rootImportFolder,"textures",filepath)

        #unreal.log_error(filepath)    
        if os.path.exists(filepath):
            AssetImportTask = unreal.AssetImportTask()
            AssetImportTask.set_editor_property('filename', filepath)
            AssetImportTask.set_editor_property('destination_path', importLocation)
            AssetImportTask.set_editor_property('replace_existing',True)
            AssetImportTask.set_editor_property('save', True)
            import_tasks.append(AssetImportTask)
            self.AssetTools.import_asset_tasks(import_tasks) #import all textures
    def execute(self):
        search_path = "/Game/"
        try:
            search_path += sys.argv[1]
        except IndexError:
            pass

        if unreal.EditorAssetLibrary.does_directory_exist(search_path) != True:
            unreal.log_warning(
                'search directory is not found: {}'.format(search_path))
            return

        all_assets = filter(
            lambda x: x.is_redirector != True,
            unreal.AssetRegistryHelpers.get_asset_registry().
            get_assets_by_path(
                unreal.Paths.normalize_directory_name(search_path), True))

        ProcessSlotTask.execute('checking all assets',
                                lambda x: self.check_duplicate(x), all_assets)

        for asset_name in self.dict_duplicates:
            paths = list(self.dict_duplicates[asset_name].keys())
            paths.sort()
            self.report(asset_name, paths)
コード例 #4
0
def add_component_material_list_to_usd_prim(usd_prim, smc):
    xform_prim = usd_prim
    material_list = smc.get_editor_property("override_materials")
    usd_material_list = []
        #for now, because the material are not exported when exporting the assets,
        #if we do not overide the materials on the actor, we will still do an override on the usd nod
    
    sm = smc.static_mesh
    slot = 0
        #we're only considering the LOD 0
    num_sections = sm.get_num_sections(0)
    
    if len(material_list) == 0 :
        while slot< num_sections:
            material = sm.get_material(slot)
            if (material != None):
                usd_material_list.append(material.get_path_name())
            slot = slot +1
        
    for material in material_list :
        if (material != None):
            usd_material_list.append(material.get_path_name())
        else:
            if slot < num_sections:
                unreal.log_warning("in here with slot = " + str(slot))
                mat2 = sm.get_material(slot)
                if (mat2 != None):
                    usd_material_list.append(mat2.get_path_name())
        slot = slot+1
        
    if usd_material_list != [] :
        unrealMaterials = xform_prim.CreateAttribute("unrealMaterials", Sdf.ValueTypeNames.StringArray)
        unrealMaterials.Set(usd_material_list)
コード例 #5
0
def add_actor_to_stage(actor,stage):
    global file_path
    global root_name
    global relative_directory
    #print("root_name ="+root_name)
    folder = actor.get_folder_path()
    
    if folder.is_none() == False :
        folder_name = usd_unreal.utils.clean_node_name(str(folder))
        name = root_name + '/' + folder_name +  usd_unreal.utils.get_usd_path_from_actor_labels(actor)
    else :
        name = root_name + usd_unreal.utils.get_usd_path_from_actor_labels(actor)
   
    unreal.log_warning("adding actor " + name)
    nf = stage.DefinePrim(name, 'Xform')

    #reference the usd asset file
    usd_asset_name = get_usd_asset_filename_from_actor(actor,relative_directory)
    nf.GetReferences().AddReference(usd_asset_name)

    #add transform information
    handle_transform(nf, actor)

    
    #since we are referencing the static mesh actor, the actual mesh is one level below
    #to assign the materials, we need to override the referenced usd_prim
    if actor.static_mesh_component.static_mesh is not None:
        usd_child_name = name +"/" + actor.static_mesh_component.static_mesh.get_name()
        usd_prim = stage.OverridePrim(usd_child_name)
        add_component_material_list_to_usd_prim(usd_prim,actor.static_mesh_component)
        #check visibility
        export_visibility(actor, usd_prim, stage)
コード例 #6
0
def import_skeletal_mesh(fbx_path, game_path, asset_name):
    """
    Import a single skeletalMesh into the engine provided an FBX.

    :param str fbx_path: Path to fbx.
    :param str game_path: Game path asset location.
    :param str asset_name: Name of asset.
    :return:
    """
    # Create an import task.
    import_task = unreal.AssetImportTask()

    # Set base properties on the import task.
    import_task.filename = fbx_path
    import_task.destination_path = game_path
    import_task.destination_name = asset_name
    import_task.automated = True  # Suppress UI.

    # Set the skeletal mesh options on the import task.
    import_task.options = _get_skeletal_mesh_import_options()

    # Import the skeletalMesh.
    unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(
        [import_task]  # Expects a list for multiple import tasks.
    )
    imported_assets = import_task.get_editor_property("imported_object_paths")

    if not imported_assets:
        unreal.log_warning("No assets were imported!")
        return

    # Return the instance of the imported SkeletalMesh
    return unreal.load_asset(imported_assets[0])
コード例 #7
0
def run_Capture_Screenshot_Virtual_Cameras(deltatime):
    global i
    for actor in actors[i:]:
        i += 1
        # Actor->name
        actor_name = actor.get_name()
        # Actor->type
        actor_type = str(actor).split("'")[-2]

        if actor_type == camera_type:
            unreal.log_warning("Camera Detected --> " + actor_name)
            # Get actor rotation
            rotation = actor.get_actor_eyes_view_point()[1]
            # Get actor position
            position = actor.get_actor_location()
            # Snap viewport to camera
            unreal.EditorLevelLibrary.set_level_viewport_camera_info(
                position, rotation)
            # Take screenshot
            unreal.AutomationLibrary.take_high_res_screenshot(
                screen_x, screen_y, actor_name + "." + output_format)
            '''
            Stop run_Capture_Screenshot_Virtual_Cameras() 
            to allow unreal to process the current iteration
            [STOP run_Capture_Screenshot_Virtual_Cameras() --> START Unreal]
            '''
            try:
                unreal.unregister_slate_pre_tick_callback(
                    run_Capture_Screenshot_Virtual_Cameras)
            except:
                break
コード例 #8
0
def copy_sockets_to_target(source_skeletal_mesh, target_skeletal_mesh):
    """
    Copies the sockets from one SkeletalMesh to another.

    :param SkeletalMesh source_skeletal_mesh: Copy from SkeletalMesh.
    :param SkeletalMesh target_skeletal_mesh: Copy to SkeletalMesh.
    :return: Returns the sockets copied on to the target SkeletalMesh.
    :rtype: list(SkeletalMeshSocket)
    """

    # early return if no sockets are found on the source asset
    if not source_skeletal_mesh.num_sockets():
        asset_name = source_skeletal_mesh.get_full_name()
        unreal.log_warning(
            "No sockets could be found for '{asset_name}'!".format(
                asset_name=asset_name))
        return

    # get the sockets from the source SkeletalMesh
    source_sockets = get_sockets(source_skeletal_mesh)

    # copy the sockets to the target skeleton
    [copy_socket_to_target(s, target_skeletal_mesh) for s in source_sockets]

    # return the new sockets on the target SkeletalMesh
    return get_sockets(target_skeletal_mesh)
コード例 #9
0
def warning(message):
    """
    Prints a warning message
    :param message: str
    :return:
    """

    unreal.log_warning(message)
コード例 #10
0
ファイル: AssetLibs.py プロジェクト: kingmax/ue4py
def do_import_tasks(tasks):
    # unreal.AssetToolsHelpers  https://api.unrealengine.com/INT/PythonAPI/class/AssetToolsHelpers.html
    # unreal.AssetTools [Abstract Class? baseClass is unreal.Interface]
    # https://api.unrealengine.com/INT/PythonAPI/class/AssetTools.html
    unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
    for task in tasks:
        for path in task.get_editor_property('imported_object_paths'):
            unreal.log_warning('Imported: %s' % path)
コード例 #11
0
def get_actor_from_name(actorName):
    unreal.log_warning(actorName)
    listActors = unreal.EditorLevelLibrary.get_all_level_actors()
    myActor = unreal.EditorFilterLibrary.by_id_name(listActors, actorName)
    if len(myActor)>0:
        return myActor[0]
    else:
        return None
コード例 #12
0
def run():
    # Create the processor with preconfigured inputs
    global _g_processor
    _g_processor = ProcessHDAExample(get_test_hda(),
                                     node_inputs=build_inputs())
    # Activate the processor, this will starts instantiation, and then cook
    if not _g_processor.activate():
        unreal.log_warning('Activation failed.')
    else:
        unreal.log('Activated!')
コード例 #13
0
 def run_callbacks(cls):
     for func_name, func_param in cls._callbacks.items():
         func, args, kws = func_param
         unreal.log_warning(
             "execute {} with param {} keywords: {}".format(func.__name__, args, kws)
         )
         try:
             func(*args, **kws)
         except Exception as why:
             unreal.log_error("failed to run with error:\n{}".format(why))
コード例 #14
0
def exchangeEnvironment(index):
    global all_actors
    global texture_cube_assets

    if not len(texture_cube_assets) > 0:
        unreal.log_error("No cubemap textures found!")
    else:
        for actor in all_actors:
            if not actor.get_name().find("light_HDRIBackdrop") == -1: # get HDRIBackdrop actor in scene
                actor.set_editor_property("Cubemap", texture_cube_assets[index])
                unreal.log_warning("New cubemap: {}".format(actor.get_editor_property("Cubemap")))
コード例 #15
0
def getActor(actorName):
    filtered_list = unreal.EditorFilterLibrary.by_actor_label(
        gl_level_actors, actorName,
        unreal.EditorScriptingStringMatchType.EXACT_MATCH)

    if len(filtered_list) == 0:
        unreal.log_warning(
            'Did not find any actor with label: "{}"'.format(actorName))
    if len(filtered_list) > 1:
        unreal.log_warning(
            'More then one actor with label: "{}"'.format(actorName))
    return filtered_list
コード例 #16
0
        def get_shotgun_menu_items(self):
            """
            Returns the list of available menu items to populate the SG menu in Unreal.
            """
            menu_items = []

            engine = sgtk.platform.current_engine()
            menu_items = self.create_menu(engine)

            unreal.log_warning("get_shotgun_menu_items is deprecated, get_shotgrid_menu_items should be used instead.")
            unreal.log("get_shotgun_menu_items returned: {0}".format(menu_items.__str__()))

            return menu_items
コード例 #17
0
def regenerate_skeletal_mesh_lods(skeletal_mesh, number_of_lods=4):
    """
    Regenerate the LODs to a specific LOD level.

    .. NOTE: EditorScriptingUtilities plugin needs to be loaded.

    :param SkeletalMesh skeletal_mesh: SkeletalMesh object.
    :param int number_of_lods: Number of LODs to generate.
    :return:
    """
    did_update_lods = skeletal_mesh.regenerate_lod(number_of_lods)
    if not did_update_lods:
        unreal.log_warning("Unable to generate LODS for {}".format(
            skeletal_mesh.get_full_name()))
コード例 #18
0
def renderAllEnvironments(deltaTime):
    global envIndex
    global texture_cube_assets

    # check if game has been quit: no game world = no running game
    # (could not find a better solution in the API)
    if(unreal.EditorLevelLibrary.get_game_world() == None):
        envIndex += 1
        if(envIndex < len(texture_cube_assets) and envIndex >= 0):
            exchangeEnvironment(envIndex)
            startGame()
        else:
            unreal.unregister_slate_pre_tick_callback(tickhandle)
    else:
        unreal.log_warning("game still running.")
コード例 #19
0
def import_texture(filename, contentpath):
    task = unreal.AssetImportTask()
    task.set_editor_property('filename', filename)
    task.set_editor_property('destination_path', contentpath)
    task.automated = True

    asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
    asset_tools.import_asset_tasks([task])

    asset_paths = task.get_editor_property("imported_object_paths")
    if not asset_paths:
        unreal.log_warning("No assets were imported!")
        return None

    return unreal.load_asset(asset_paths[0])
コード例 #20
0
    def execute(self):
        search_path = "/Game/"
        try:
            search_path += sys.argv[1]
        except IndexError:
            pass

        if unreal.EditorAssetLibrary.does_directory_exist(search_path) != True:
            unreal.log_warning(
                'search directory is not found: {}'.format(search_path))
            return

        ProcessSlotTask.execute(
            'checking name of asset', lambda x: self.check_asset_name(x),
            unreal.AssetRegistryHelpers.get_asset_registry().
            get_assets_by_path(
                unreal.Paths.normalize_directory_name(search_path), True))
コード例 #21
0
def halve_tangent_weights(key_array):
    print('Halving the Tangent Weight for {0} keys...'.format(len(key_array)))

    for key in key_array:
        if key.get_interpolation_mode(
        ) != unreal.RichCurveInterpMode.RCIM_CUBIC or key.get_tangent_mode(
        ) != unreal.RichCurveTangentMode.RCTM_USER or key.get_tangent_weight_mode(
        ) != unreal.RichCurveTangentWeightMode.RCTWM_WEIGHTED_BOTH:
            unreal.log_warning(
                "Skipping setting tangent weight on key due to invalid Interp Mode, Tangent Mode or Weight Mode for this example!"
            )
            continue

        key.set_arrive_tangent_weight(key.get_arrive_tangent_weight() / 2)
        key.set_leave_tangent_weight(key.get_leave_tangent_weight() / 2)

    print('Finished!')
    return
    def execute(self):
        search_path = "/Game/"
        try:
            search_path += sys.argv[1]
        except IndexError:
            pass

        if unreal.EditorAssetLibrary.does_directory_exist(search_path) != True:
            unreal.log_warning(
                'search directory is not found: {}'.format(search_path))
            return

        all_directories = filter(
            lambda x: x.endswith('/'),
            unreal.EditorAssetLibrary.list_assets(search_path, True, True))

        ProcessSlotTask.execute('checking directories',
                                lambda x: self.check_directory(x),
                                all_directories)
コード例 #23
0
 def readMaterialInstanceCSV(self):
     try:
         with open(self.materialInstanceCSVPath, mode='r') as csv_file:
             csv_reader = csv.reader(csv_file, delimiter=',')
             line_count = 0
             parameterNames = []
             for row in csv_reader:
                 if line_count == 0:
                     unreal.log("Parameters To Import: " + " | ".join(row))
                     parameterNames = row
                     line_count += 1
                 else:
                     self.createMaterialInstance(NewMatName = row[1],parameterNames = parameterNames, parameters = row)
                     #unreal.log("row:" + str(line_count) + " :".join(row))
                     line_count += 1
             unreal.log('Processed ' + str(line_count-1) + ' materials')
         #TODO: search for textures before import
         unreal.EditorAssetLibrary.save_directory(self.UEMaterialDirectory)
     except Exception:
         unreal.log_warning("Issue reading material csv file")
コード例 #24
0
def export_mesh_to_usd(full_name,smc, directory):
    task = unreal.AssetExportTask()
    task.object = smc.static_mesh
    task.filename = get_usd_asset_filename(full_name, directory)
    task.selected = False
    task.replace_identical = True
    task.prompt = False
    task.automated = True
    unreal.Exporter.run_asset_export_task(task)

    #let's add the asset information
    unreal.log_warning("adding asset information for :" + full_name)
    stage = Usd.Stage.Open(task.filename)
    usd_prim = stage.GetDefaultPrim()
    model = Usd.ModelAPI(usd_prim)
    model.SetAssetIdentifier(task.filename)
    model.SetAssetName(full_name.rsplit('.')[1])
    stage.Save()

    return task.filename
コード例 #25
0
def create_unreal_asset(
    asset_name, package_path, factory, asset_class, force=False, save=True
):
    """

    INPUT:
        asset_name: str
            Exp: "MyAwesomeBPActorClass"
        package_path: str
            Exp: "/Game/MyContentFolder"
        package_path: unreal.Factory:
            Exp: unreal.BlueprintFactory()
        asset_class: unreal.Object
            Exp: unreal.Actor
        force: bool
            Force remove old and create new one
        save: bool
            Save asset after creation

    OUPUT:
        unreal.Object

    """

    asset_path = "{}/{}".format(package_path, asset_name)
    if AssetLibrary.does_asset_exist(asset_path):
        if force:
            unreal.log_warning("{} exists. Skip creating".format(asset_name))
            return
        else:
            unreal.log_warning("{} exists. Remove existing asset.".format(asset_name))
            AssetLibrary.delete_asset(asset_path)

    factory.set_editor_property("ParentClass", asset_class)

    new_asset = AssetTools.create_asset(asset_name, package_path, None, factory)

    if save:
        AssetLibrary.save_loaded_asset(new_asset)

    return new_asset
コード例 #26
0
    def execute(self):
        search_path = "/Game/"
        try:
            search_path += sys.argv[1]
        except IndexError:
            pass

        if unreal.EditorAssetLibrary.does_directory_exist(search_path) != True:
            unreal.log_warning(
                'search directory is not found: {}'.format(search_path))
            return

        with unreal.ScopedEditorTransaction("validating texture properties"):
            ProcessSlotTask.execute(
                'checking texture assets', lambda x: self.check_asset_data(x),
                AssetStatics.filter_by_class(
                    unreal.Texture2D,
                    unreal.AssetRegistryHelpers.get_asset_registry().
                    get_assets_by_path(
                        unreal.Paths.normalize_directory_name(search_path),
                        True), True, False))
コード例 #27
0
    def _check_wrapper(self, wrapper):
        """ Checks that wrapper matches self.asset_wrapper. Logs a warning if
        it does not.

        Args:
            wrapper (HoudiniPublicAPIAssetWrapper): the wrapper to check
            against self.asset_wrapper

        Returns:
            (bool): True if the wrappers match.

        """
        if wrapper != self._asset_wrapper:
            unreal.log_warning(
                '[UHoudiniPublicAPIProcessHDANode] Received delegate event '
                'from unexpected asset wrapper ({0} vs {1})!'.format(
                    self._asset_wrapper.get_name() if self._asset_wrapper else '',
                    wrapper.get_name() if wrapper else ''
                )
            )
            return False
        return True
def testRegistry(deltaTime):
    unreal.log_warning("ticking.")
    asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
    if asset_registry.is_loading_assets():
        unreal.log_warning("still loading...")
    else:
        unreal.log_warning("ready!")
        unreal.unregister_slate_pre_tick_callback(tickhandle)
コード例 #29
0
def getActor(actorName):
    """
    seach for an actor label
 
    arg:
    actorName =  str|label beaing searched for
 
    returns:
    list of actor(s)
    """
    level_actors = unreal.EditorLevelLibrary.get_all_level_actors()

    filtered_list = unreal.EditorFilterLibrary.by_actor_label(
        level_actors, actorName,
        unreal.EditorScriptingStringMatchType.EXACT_MATCH)

    if len(filtered_list) == 0:
        unreal.log_warning(
            'Did not find any actor with label: "{}"'.format(actorName))
    if len(filtered_list) > 1:
        unreal.log_warning(
            'More then one actor with label: "{}"'.format(actorName))
    return filtered_list
コード例 #30
0
def save_assets(assets, force_save=False):
    """
    Saves the given asset objects.

    :param list assets: List of asset objects to save.
    :param bool force_save: Will save regardless if the asset is dirty or not.
    :return: True if all assets were saved correctly, false if not; the failed
    assets are returned if necessary.
    :rtype: bool, list[unreal.Object]
    """
    failed_assets = []
    only_if_is_dirty = not force_save
    assets = assets if isinstance(assets, list) else [assets]

    for asset in assets:
        asset_path = asset.get_full_name()
        if unreal.EditorAssetLibrary.save_asset(asset_path, only_if_is_dirty):
            unreal.log("Saved newly created asset: {}".format(asset_path))
        else:
            unreal.log_warning(
                "FAILED TO SAVE newly created asset: {}".format(asset_path))
            failed_assets.append(asset)

    return len(failed_assets) == 0, failed_assets