Analysis of UE5 Asynchronous Asset Loading Flow

Words: 1611

Overview

This document provides a detailed analysis of the asynchronous asset loading flow of FStreamableManager in UE5, covering the complete process from RequestAsyncLoad to callback execution. By examining the source code in depth, we will understand the interaction mechanism between the main thread and the loading thread, as well as how asset dependencies are handled.

Core Concepts

Key Classes and Structures

  • FStreamableManager: The core class in UE5 responsible for managing asynchronous asset loading
  • FStreamableHandle: Tracks the status and callbacks of a single asynchronous load request
  • FStreamable: Used internally to track the loading status of a single asset
  • FSoftObjectPath: A soft reference path used to point to assets that have not yet been loaded

Main Flow Components

  • Request initiation: Initiate an asynchronous load request via RequestAsyncLoad or related methods
  • Request processing: StartHandleRequests processes load requests
  • Asset loading: StreamInternal performs the actual asset loading logic
  • Callback handling: Notify the main thread via callback after loading completes
  • Dependency handling: Automatically handles dependencies between assets

Complete Flow Analysis

Request Initiation Stage

Starting with the RequestAsyncLoadInternal function:

cpp
1
2
3
4
5
6
7
TSharedPtr<FStreamableHandle> FStreamableManager::RequestAsyncLoadInternal(
    TArray<FSoftObjectPath>&& TargetsToStream, 
    FStreamableDelegate&& DelegateToCall, 
    TAsyncLoadPriority Priority, 
    bool bManageActiveHandle, 
    bool bStartStalled, 
    FString&& DebugName)

Main steps:

  1. Create a load handle: Create an FStreamableHandle object to track the load request
  2. Set the callback: Store the user-provided callback function in the handle
  3. Validate asset paths: Check and clean up invalid asset paths
  4. Manage the handle: Add the handle to the active handle list if needed
  5. Start loading: Call StartHandleRequests to begin processing the load request

Load Processing Stage

The StartHandleRequests function processes the actual load requests:

cpp
1
void FStreamableManager::StartHandleRequests(TSharedRef<FStreamableHandle> Handle)

Main steps:

  1. Iterate over assets: Call StreamInternal for each requested asset
  2. Track existing streams: Add the returned FStreamable objects to the list
  3. Check already-loaded assets: For assets already in memory, mark them as complete directly

Asset Loading Core

StreamInternal is the core implementation of asset loading:

cpp
1
2
3
4
FStreamable* FStreamableManager::StreamInternal(
    const FSoftObjectPath& InTargetName, 
    TAsyncLoadPriority Priority, 
    TSharedRef<FStreamableHandle> Handle)

Main steps:

  1. Check whether it exists in memory: If the asset is already in memory, return directly
  2. Create a stream object: If it is a new asset, create an FStreamable object
  3. Synchronous load check: Perform synchronous loading in certain cases (such as initialization loading or inside constructors)
  4. Asynchronous loading: Call LoadPackageAsync to initiate an asynchronous load request
  5. Set the callback: Configure the callback function for when loading completes

Callback Handling Stage

After loading completes, the AsyncLoadCallback function is called:

cpp
1
void FStreamableManager::AsyncLoadCallback(FSoftObjectPath TargetName, UPackage* Package)

Main steps:

  1. Get the stream object: Find the corresponding FStreamable object based on the asset path
  2. Mark loading complete: Set bAsyncLoadRequestOutstanding = false
  3. Find the asset in memory: Call FindInMemory to find the loaded asset
  4. Check completed requests: Call CheckCompletedRequests to check whether all requests have completed

Completion Check and Callback Execution

The CheckCompletedRequests function checks whether load requests are complete and executes the corresponding callbacks:

Main steps:

  1. Iterate over related handles: Check all FStreamableHandle objects that reference the asset
  2. Mark completion status: For completed assets, update the handle’s completion status
  3. Execute callbacks: When all assets have finished loading, execute the user-provided callback function

Interaction Between the Main Thread and the Loading Thread

Thread Responsibility Division

Thread TypeResponsibilityKey Operations
Main threadInitiate load requests and handle callbacksCreate load requests and execute completion callbacks
Loading threadPerform the actual asset loadingRead from disk, parse package files, and load assets

Interaction Mechanism

  1. Request initiation: The main thread calls LoadPackageAsync to initiate a load request
  2. Task scheduling: LoadPackageAsync submits the load task to the asynchronous loading system
  3. Background loading: The loading thread performs the actual loading operations in the background
  4. Completion notification: After loading completes, notify the main thread via the FLoadPackageAsyncDelegate callback
  5. Callback execution: The main thread handles the loaded assets in AsyncLoadCallback

Synchronization Points

Although the loading process is asynchronous, synchronization is forced in certain cases:

  • Initialization stage: During game initialization, certain assets need to be loaded synchronously
  • Inside constructors: Load requests initiated inside object constructors are executed synchronously
  • Forced synchronization: When the bForceSynchronousLoads flag is set

Asset Dependency Handling

Dependency Loading Mechanism

UE5’s package loading system automatically handles asset dependencies:

  1. Package dependency analysis: When loading an asset, the system analyzes the other assets it depends on
  2. Recursive loading: Automatically load all dependent assets
  3. Dependency graph management: Build and manage the dependency graph between assets

Specific Flow

  1. Main asset loading: Initiate a load request for the main asset
  2. Dependency analysis: The loading system analyzes the dependencies of the main asset
  3. Dependency loading: Automatically create load requests for all dependencies
  4. Loading order: Determine the loading order based on dependency relationships
  5. Completion notification: The main asset is notified as loaded only after all dependencies have finished loading

Dependency Handling Example

Scenario: Loading a static mesh that contains a material and a texture

  1. Initiate loading: Request to load the static mesh asset StaticMesh'/Game/Meshes/Sphere.Sphere'
  2. Dependency analysis: The loading system discovers that the mesh uses the material Material'/Game/Materials/Metal.Metal'
  3. Material loading: Automatically load the material asset
  4. Texture loading: Discover that the material depends on the texture Texture2D'/Game/Textures/Metal_Albedo.Metal_Albedo', and automatically load the texture
  5. Completion order: Texture → Material → Static Mesh
  6. Callback execution: When all assets have finished loading, execute the user-provided callback

Code Flow Details

Core Flowchart

  flowchart TD
    A[RequestAsyncLoadInternal] --> B[创建FStreamableHandle]
    B --> C[StartHandleRequests]
    C --> D[StreamInternal]
    D --> E{资源是否在内存中?}
    E -->|是| F[直接返回]
    E -->|否| G{是否需要同步加载?}
    G -->|是| H[StaticLoadObject]
    G -->|否| I[LoadPackageAsync]
    I --> J[加载线程执行]
    J --> K[AsyncLoadCallback]
    H --> L[CheckCompletedRequests]
    K --> L
    L --> M{所有资源加载完成?}
    M -->|是| N[执行用户回调]
    M -->|否| O[继续等待]

Key Code Analysis

Request Creation and Initialization

cpp
1
2
3
4
5
6
// 创建新的加载句柄
TSharedRef<FStreamableHandle> NewRequest = MakeShareable(new FStreamableHandle());
NewRequest->CompleteDelegate = MoveTemp(DelegateToCall);
NewRequest->OwningManager = this;
NewRequest->RequestedAssets = MoveTemp(TargetsToStream);
NewRequest->DebugName = MoveTemp(DebugName);

This code creates a new FStreamableHandle object and sets the callback function, asset paths, and other information.

Asset Loading Core

cpp
1
2
3
4
5
6
7
// 异步加载资源
Existing->RequestId = LoadPackageAsync(PackagePath,
    NAME_None /* PackageNameToCreate */,
    FLoadPackageAsyncDelegate::CreateSP(Handle, &FStreamableHandle::AsyncLoadCallbackWrapper, TargetName),
    PKG_None /* InPackageFlags */,
    INDEX_NONE /* InPIEInstanceID */,
    Priority /* InPackagePriority */);

This code calls LoadPackageAsync to initiate an asynchronous load request and sets the callback function.

Callback Handling

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
void FStreamableManager::AsyncLoadCallback(FSoftObjectPath TargetName, UPackage* Package)
{
    check(IsInGameThread());

    FStreamable* Existing = FindStreamable(TargetName);

    UE_LOG(LogStreamableManager, Verbose, TEXT("Stream Complete callback %s"), *TargetName.ToString());
    if (Existing)
    {
        if (Existing->bAsyncLoadRequestOutstanding)
        {
            Existing->bAsyncLoadRequestOutstanding = false;
            if (!Existing->Target)
            {
                FindInMemory(TargetName, Existing, Package);
            }

            CheckCompletedRequests(TargetName, Existing);
        }
        // ...
    }
}

This code handles the load completion callback, marks the loading status, and checks whether all requests have completed.

Practical Application Examples

Basic Asynchronous Loading

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// 基本异步加载示例
TArray<FSoftObjectPath> AssetsToLoad;
AssetsToLoad.Add(FSoftObjectPath("StaticMesh'/Game/Meshes/Sphere.Sphere'"));
AssetsToLoad.Add(FSoftObjectPath("Material'/Game/Materials/Metal.Metal'"));

UStreamableManager* StreamableManager = UStreamableManager::Get();
StreamableManager->RequestAsyncLoad(
    AssetsToLoad,
    FStreamableDelegate::CreateLambda([]() {
        UE_LOG(LogTemp, Log, TEXT("所有资源加载完成!"));
        // 在这里使用加载完成的资源
    }),
    FStreamableManager::AsyncLoadHighPriority,
    false,
    TEXT("ExampleLoad"));

Asynchronous Loading with a Handle

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// 带句柄的异步加载示例
UStreamableManager* StreamableManager = UStreamableManager::Get();
TSharedPtr<FStreamableHandle> LoadHandle = StreamableManager->RequestAsyncLoad(
    FSoftObjectPath("StaticMesh'/Game/Meshes/Sphere.Sphere'"),
    FStreamableDelegate::CreateLambda([]() {
        UE_LOG(LogTemp, Log, TEXT("资源加载完成!"));
    }),
    TEXT("SphereLoad"));

// 可以使用句柄检查加载状态
if (LoadHandle.IsValid())
{
    if (LoadHandle->HasLoadCompleted())
    {
        UE_LOG(LogTemp, Log, TEXT("加载已完成!"));
    }
    else if (LoadHandle->HasLoadFailed())
    {
        UE_LOG(LogTemp, Error, TEXT("加载失败!"));
    }
}

Dependency Loading Example

cpp
1
2
3
4
5
6
7
8
9
// 依赖加载示例 - 加载一个包含多个依赖的资源
UStreamableManager* StreamableManager = UStreamableManager::Get();
StreamableManager->RequestAsyncLoad(
    FSoftObjectPath("Blueprint'/Game/Blueprints/Character.Character'"),
    FStreamableDelegate::CreateLambda([]() {
        UE_LOG(LogTemp, Log, TEXT("角色蓝图及其所有依赖加载完成!"));
        // 这里可以安全地使用角色蓝图及其所有依赖资源
    }),
    TEXT("CharacterLoad"));

Performance Optimization Suggestions

Loading Strategy Optimization

  1. Batch loading: Merge multiple related assets into a single load request to reduce loading overhead
  2. Priority setting: Set appropriate load priorities based on the importance of the assets
  3. Preloading: Preload assets that will be used soon at appropriate times
  4. Asynchronous loading: Use asynchronous loading whenever possible to avoid blocking the main thread

Memory Management

  1. Release promptly: Promptly release assets that are no longer used via ReleaseHandle
  2. Dependency analysis: Analyze and optimize asset dependency relationships to reduce unnecessary loading

Error Handling

  1. Load failure handling: Add callback handling for load failures
  2. Timeout handling: For critical assets, add load timeout detection
  3. Error logs: Add detailed error logs to facilitate troubleshooting loading issues

Common Issues and Solutions

Load Failure

Problem: Asset loading fails

Solution:

  • Check whether the asset path is correct
  • Ensure the asset file exists at the specified location
  • Check whether asset dependencies are complete
  • Check the logs for detailed error information

Slow Loading

Problem: Asset loading is too slow

Solution:

  • Optimize asset size and complexity
  • Use appropriate compression formats
  • Implement asset preloading

High Memory Usage

Problem: Loading too many assets causes high memory usage

Solution:

  • Release assets that are no longer used promptly
  • Implement asset pool management
  • Consider using dynamic asset loading strategies
  • Monitor memory usage and adjust loading strategies promptly

Summary

UE5’s FStreamableManager provides a powerful and flexible asynchronous asset loading system, enabling efficient asset management through the following mechanisms:

  1. Separation of main thread and loading thread: The main thread initiates requests, the loading thread performs the actual loading, and completion is notified through a callback mechanism
  2. Automatic dependency handling: The loading system automatically handles dependencies between assets, ensuring all dependencies are loaded correctly
  3. Flexible loading strategies: Supports synchronous and asynchronous loading, allowing the appropriate loading method to be chosen for different scenarios
  4. Detailed status tracking: Provides detailed loading status information through FStreamableHandle

By using FStreamableManager appropriately, developers can achieve efficient asset management and improve the game’s loading speed and runtime performance.

References


This document is based on analysis of the UE5.5 source code; minor differences may exist between versions.

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...