Porting CDLOD Terrain to Android Vulkan

Contents

A bend in the road nearly disappeared into the sand when we switched the test terrain to Android Vulkan Mobile Preview. The terrain silhouette still lined up, and both ends of the road were visible. Enlarging the coverage mask did little. Displaying the source BaseColor brought the bend back. That narrowed the problem to the blend between the road mask and the source color.

The previous article built the heightfield, CDLOD mesh, terrain materials, and collision. This port uses the same terrain data. We checked rendering and collision cases in Windows Mobile Preview and ran the packaged build in an Android emulator. Custom Terrain in UE 5.8: From Height Data to Rendering and Collision

CDLOD already uses coarser meshes at a distance, reducing vertex work. The height and normal data still occupy an 8192 × 8192 atlas, and startup still has to load textures and build collision. The mobile material moves part of the BaseColor compositing into Runtime Virtual Texture (RVT) page rendering. That gives us three separate costs to track: texture residency, startup uploads, and GPU time in RVT page rendering and the Base Pass.

Porting the CDLOD Terrain Pipeline

The CPU selects quadtree nodes by viewpoint distance and packs their offsets, sampling scale, and quadrant visibility into instance parameters. The vertex shader uses those parameters to sample the height/normal atlas and position the mesh. In Windows Vulkan SM5 and Windows Android Vulkan Mobile Preview, all four sampled Base Pass and RVT draws used vkCmdDrawIndexed with 6,144 indices and 100 instances per call.

The terrain material uses material IDs and weights to look up layers in dynamic texture arrays. On mobile, the RVT producer composites BaseColor and the Base Pass samples the cached result. Normal and Roughness retain their existing material inputs. The faded bend originated in the producer: coarse page sampling reduced the road mask’s contribution. The fix estimates the source footprint from UV derivatives and increases the source BaseColor weight as that footprint grows. The local road texture still applies its own alpha on top.

The dynamic texture arrays use BGRA8. Uploads copy source and destination mips with matching dimensions. A 1024² source begins at mip 1 when the destination slice is 512². The Vulkan path transitions both resources into copy access, then restores shader-read access. The formats, dimensions, and mips in the Android cook determine the actual upload volume.

Rendering Changes from PC to Mobile

The vertex path uses the same CDLOD instance parameters and height data in both previews. The implementation changes concentrate on mobile material binding, RVT BaseColor production, and texture-copy access transitions.

Feature Mobile approach What we checked
Geometry and LOD Keep the CDLOD grid, quadtree, and height sampling. Assets that rely on Nanite would need conventional meshes and LODs on the default mobile path. The instance layout, height encoding, and 8192 × 8192 atlas carry over.
Materials and sampling Compile the material for the mobile shader platform. Check which sampling branches survive compilation before deciding which layers to keep, bake, or remove. Startup binds the mobile material. BaseColor comes from RVT. Normal and Roughness keep separate nodes.
Texture formats and copies Cook textures for Android and specify the runtime array format separately. Check formats, mip dimensions, and access states before copying. The Android cook targets ASTC. The runtime array uses BGRA8. The Vulkan copy path uses explicit CopySrc and CopyDest transitions.
RVT and roads Adjust the producer’s blend when a larger sampling footprint weakens narrow features. Profile production and sampling separately. Both previews regenerated RVT pages. The revised footprint blend restored the bend at the matched viewpoint.
Lighting and reflections For scenes using Lumen on PC, evaluate baked indirect lighting and reflection captures on the default mobile path. Platform option.
Shadows For scenes using Virtual Shadow Maps on PC, evaluate supported mobile alternatives such as Cascaded Shadow Maps for the main directional light. Tune coverage, cascades, and resolution per device tier. Platform option.
Anti-aliasing and output Select TAA or FXAA for the chosen mobile path. Evaluate MSAA where the mode supports it, and record both internal and output resolutions. The 1920 × 1080 emulator result is a screenshot dimension.
Mobile Forward and Deferred Select the mobile shading mode separately from Vulkan. Check GBuffer requirements, dynamic lights, and reflections against that mode. The Android ES3_1 shader platform was confirmed.

UE 5.8 mobile rendering features · UE mobile rendering and shading modes

From PC DirectX to Android Vulkan. The port keeps CDLOD node selection, instanced draws, and height sampling. The mobile shading path produces and samples RVT BaseColor and uploads terrain texture array slices.
Figure 1. From PC DirectX to Android Vulkan. The port keeps CDLOD node selection, instanced draws, and height sampling. The mobile shading path produces and samples RVT BaseColor and uploads terrain texture array slices.

Height, Normals, and Material Weights

PC and mobile read height, normal, and material weight data from the same terrain file. Both use quadtree selection, a regular grid, and Geomorph. The mobile terrain material samples its BaseColor from RVT.

PC and mobile share CDLOD terrain data and bind their own terrain materials. Collision is built independently.
Figure 2. PC and mobile share CDLOD terrain data and bind their own terrain materials. Collision is built independently.

The silhouette and surface color come from different calculations. The vertex shader gets the terrain shape from the height atlas. The material combines IDs, weights, and textures into a color. When the silhouettes line up and a road fades, follow the material blend and RVT output to find where the color changes.

Stage PC implementation Mobile port
Height and weights Atlas, material IDs, and blend weights Shared inputs, checked by independent parsing
Geometry selection Quadtree, distance thresholds, quadrant coverage Same SceneProxy and instance layout
Vertex processing Height decoding, Geomorph, triangle visibility Same Vertex Factory and height rules
Terrain shading Texture arrays, slot indirection, layer blending Mobile material for ES3_1, with RVT BaseColor
Uploads Copy from source textures into array slices Explicit copy-access transitions

The file contains 64 × 64 blocks of 128 × 128 samples, assembled into an 8192 × 8192 height/normal atlas. The 4,096 file blocks organize height data. The quadtree selects draw nodes by distance, and collision builds its own patches according to visibility and physics requirements. This run registered 3,364 collision patches.

An independent check compared all 67,108,864 weight texels and found matching material IDs and weights. Texture filtering, shading, virtual texture pages, and lighting can still change the output. Using the same terrain makes it possible to trace those differences without changing the input height or weights.

Matched close views of the road network and surrounding terrain in PC Vulkan SM5 and Mobile Preview.
Figure 3. Matched close views of the road network and surrounding terrain in PC Vulkan SM5 and Mobile Preview.
Mid-distance PC Vulkan SM5 and Mobile Preview views. The bend and nearby roads are visible below the slope.
Figure 4. Mid-distance PC Vulkan SM5 and Mobile Preview views. The bend and nearby roads are visible below the slope.

CDLOD Node Selection and Draw Submission

CDLOD represents the same heightfield using regular grids at several scales. The CPU selects nodes, and the shader morphs vertices toward their parent-grid positions in the transition band before sampling height.

FCDLODSceneProxy::TraverseNode() uses the nearest XY distance from the viewpoint to the node’s bounding box. The contribution along an axis is zero inside its bounds and otherwise comes from the nearest edge. In the pseudocode, c is the box center, e its half extent, and v the local viewpoint in XY.

// Per axis, measure the distance to the node's bounds.
dx = max(abs(v.x - c.x) - e.x, 0)
dy = max(abs(v.y - c.y) - e.y, 0)
distanceSquared = dx*dx + dy*dy

A viewpoint inside the projected bounds gives zero distance even if it is far from the node center. The code rejects the node when distanceSquared is greater than or equal to the squared threshold for that LOD. The next finer threshold determines whether to draw the node as a whole or recurse. A four-bit mask lets the parent skip quadrants covered by finer nodes.

The left panel shows the nearest XY distance to the node. On the right, a child covers one quadrant and the parent draws the rest.
Figure 5. The left panel shows the nearest XY distance to the node. On the right, a child covers one quadrant and the parent draws the rest.

Instance Data Sent to the Vertex Shader

Each instance supplies two float4 values. The first contains local node offset and height-atlas offset. The second contains packed grid stride, LOD, and quadrant flags along with sampling parameters and the triangle-visibility offset. The two rows contain 32 bytes of logical data before buffer layout and allocation overhead.

// Each instance provides two float4 values to the Vertex Shader.
struct FCDLODInstanceInfoRows
{
    FVector4f Row0; // xy: local node offset. zw: height atlas offset.
    FVector4f Row1; // Packed flags, reciprocal stride, texel scale, and visibility bit offset.
};

The shader adds the batch’s BaseInstance to the input instance ID and reads two consecutive rows. asuint interprets the stored bits directly. Precision conversion on the packed field can corrupt the stride or visibility flags.

// Read the two consecutive float4 rows for this instance.
uint instanceIndex = Input.InstanceId + CDLODDynamic.BaseInstance;
float4 row0 = CDLODInstances.CDLODInstanceInfoArray[instanceIndex * 2];
float4 row1 = CDLODInstances.CDLODInstanceInfoArray[instanceIndex * 2 + 1];
uint flags = asuint(row1.x);

The CPU groups ordinary and per-triangle visibility instances separately and splits batches at the instance-array limit. FMeshBatchElement::NumInstances is the batch instance count. NumPrimitives describes the shared mesh per instance. A PatchSize of 32 represents 32 quads per edge, with 33 vertices per edge and 32 × 32 × 2 = 2,048 triangles in the full patch. Quadrant masking, triangle visibility, and pass participation all affect how that geometry contributes to the frame.

The GPU draws are recorded per pass. Depth, shadows, Base Pass, and RVT may each use the same mesh batch, so the RHI counts or a capture give the actual draw totals.

Geomorph Before the Height Lookup

The shader uses horizontal world-space distance to calculate the morph factor. start and end are the LOD transition limits.

// Horizontal world-space distance.
// Start and end distances of the current LOD transition.
k = clamp((d - start) / (end - start), 0, 1)

The Uniform Buffer stores constants so the shader can evaluate the factor with a multiply-add. It then applies the horizontal adjustment -2*k*frac(gridPosition*0.5) and samples height at the corrected position.

Even grid coordinates stay fixed. Odd coordinates move toward the preceding even coordinates. Vertex 3, for example, moves through 3, 2.5, and 2 at k = 0, 0.5, 1. At the far end of the transition, those vertices align with the parent grid.

Vertex 3 moves toward vertex 2. The height lookup uses the vertex’s final horizontal position and the current LOD stride.
Figure 6. Vertex 3 moves toward vertex 2. The height lookup uses the vertex’s final horizontal position and the current LOD stride.

The road comparison held the geometry settings fixed. A continuous camera traversal is a separate test for visual continuity across LOD transitions and hole boundaries.

Decoding Terrain Vertex Height

The height/normal atlas stores the high and low height bytes in RG and the normal’s XY components in BA.

// Decode height from RG. R stores the high byte and G the low byte.
float CDLODDecodePackedHeight(float2 PackedHeight)
{
    return PackedHeight.x * 510.0
         + PackedHeight.y * 1.9921875f - 256.0f;
}

For bytes hi and lo, the normalized channels are hi/255 and lo/255. The formula reduces to 2*hi + lo/128 - 256, or the combined integer divided by 128 and offset by 256. The shader’s operation order and precision remain platform-dependent.

The decoded value is scaled using the terrain file header and then transformed to world space. Check the file scale and component transform together. A meter-to-centimeter conversion contributes a factor of 100, which should be applied only once.

The shader samples four neighboring heights in the full-resolution atlas at the current LOD stride. It interpolates using the fractional grid position after Geomorph. Reducing surface texture resolution does not change these vertex-stage reads. Any change to the sampling scheme needs a check of coarse-grid heights and LOD continuity.

After decoding normal XY into [-1,1], the shader reconstructs Z with sqrt(max(1-dot(xy,xy),0)). The clamp handles small negative values from quantization or interpolation. Material detail normals use their own samples and space transforms.

Binding the Android Terrain Material

ATerrainShadingActor owns references to the terrain component, Clipmap, materials, and RVT setup. At startup it checks the world Feature Level. If an ES3_1 mobile material is configured, the actor binds it to the terrain component. The shared initialization then creates the Material Instance Dynamic (MID) and sets the texture parameters.

// Bind the ES3_1 terrain material and configure RVT.
if (MobileShadingMaterial &&
    GetWorld()->GetFeatureLevel() == ERHIFeatureLevel::ES3_1)
{
    if (bUseRVTWithMobileShading &&
        (!IsValid(RVTAsset) || !IsValid(RVTVolumeRef)))
    {
        return; // Stop if the RVT asset or Volume is invalid.
    }

    ShadingMaterial = MobileShadingMaterial.Get();
    CDLODRef->Material = ShadingMaterial;

    if (!bUseRVTWithMobileShading)
    {
        CDLODRef->RuntimeVirtualTextures.Reset();
        RVTAsset = nullptr;
        RVTVolumeRef = nullptr;
    }
}

The mobile material can shade directly or use RVT. When RVT is enabled, the actor checks both the RVT asset and its Volume. When RVT is disabled, it clears the component’s virtual texture output references and the actor’s RVT references. The startup log records the selected material.

The configuration script derives the mobile RVT material from an existing mobile material and modifies the road Custom node. The saved asset export shows the node wiring. The cooked SPIR-V and a capture are the evidence for instruction count, active sampling branches, and runtime shading cost. Desktop references can still affect what gets cooked when a level is shared.

Copying Terrain Textures into a Texture Array

The destination slice dimensions and mip count determine the bytes per slice. The number of slices prepared at startup determines how much data the initialization uploads. For each terrain layer the shader resolves a material ID to an array slot. The upload also needs a point at which the new slot mapping can be published and a point at which the destination is readable.

Vulkan must see the source texture as a copy source and the destination array as a copy destination, regardless of their previous shader-read use. After the explicit transitions were added, the layout warning associated with the source terrain texture did not recur. The historical validation logs contain other warnings.

FTexture2DArrayResource::InitRHI() creates the array with Create2DArray and ShaderResource usage. The descriptor leaves InitialState unspecified. The upload uses SRVMask before and after the copy; the engine’s default logical access state for the descriptor explains the assumption. The actual first-upload layout sequence was not captured.

// SrcRHI is the source Texture2D. DstTex is the runtime texture array.
// Transition from shader-read access to copy access.
RHICmdList.Transition({
    FRHITransitionInfo(SrcRHI, ERHIAccess::SRVMask, ERHIAccess::CopySrc),
    FRHITransitionInfo(DstTex, ERHIAccess::SRVMask, ERHIAccess::CopyDest),
});

for (int32 Mip = 0; Mip < Mips; ++Mip)
{
    FRHICopyTextureInfo CopyInfo;
    CopyInfo.SourceMipIndex = Mip + MipBias;
    CopyInfo.DestMipIndex = Mip;
    CopyInfo.SourceSliceIndex = 0;
    CopyInfo.DestSliceIndex = SlotId;
    CopyInfo.NumSlices = 1;
    CopyInfo.NumMips = 1;
    CopyInfo.Size = FIntVector(
        FMath::Max(Size >> Mip, 1),
        FMath::Max(Size >> Mip, 1), 1);
    RHICmdList.CopyTexture(SrcRHI, DstTex, CopyInfo);
}

// Restore shader-read access after the copies.
RHICmdList.Transition({
    FRHITransitionInfo(SrcRHI, ERHIAccess::CopySrc, ERHIAccess::SRVMask),
    FRHITransitionInfo(DstTex, ERHIAccess::CopyDest, ERHIAccess::SRVMask),
});

On Vulkan, the path is CopyTexture → FVulkanCommandListContext::RHICopyTexture → vkCmdCopyImage. Each call copies one mip to one destination slice. Destination mip m comes from source mip m + MipBias, and SlotId selects the target slice. The backend builds the required barriers for the device’s synchronization path.

The render command captures source and destination resource pointers. Both resources must stay valid until the render command consumes them. The caller waits for render commands with FlushRenderingCommands() before updating the CPU slot mapping. GPU completion depends on queue submission and synchronization. An asynchronous version would also need to track pending slots, cancellation, old resource lifetimes, and when mappings become visible to the material.

Matching Source Mips to the Destination Slice

The current BGRA8 array requires compatible formats and matching copy dimensions. For square source and destination dimensions S and T, the current path requires S/T to be a power of two of at least 1.

// Compute MipBias from the source-to-destination size ratio.
MipBias = log2(S / T)
SourceMip = DestinationMip + MipBias
SourceMipCount >= MipBias + DestinationMipCount
Source mip 1 and destination mip 0 both measure 512 × 512.
Figure 7. Source mip 1 and destination mip 0 both measure 512 × 512.

A 1024 × 1024 source feeding a 512 × 512 slice uses MipBias=1. Destination mip 0 copies source mip 1. A full ten-level destination chain from 512 to 1 requires source mips 1 through 10, so the source needs at least eleven levels. This is a copy example; check the cooked textures for actual dimensions and mip counts.

The implementation rejects insufficient dimensions or mips. Some format mismatches log a warning and continue, so the cooked source and BGRA8 destination still have to meet the copy API’s constraints. An Android ASTC cook target does not set the format of the runtime array.

A 512 × 512 texture at four bytes per texel contains 1 MiB at mip 0 and roughly 1.33 MiB across the complete chain, excluding row alignment and allocation overhead. At that example size, two 23-slice arrays for color and normals would contain about 23 × 2 × 4/3 ≈ 61.3 MiB of texel data. Actual residency also depends on the real formats, cache, buffering, and driver allocations. The logs record 32 material IDs and 23 resident slots. These count material identities and slot occupancy, respectively.

Terrain Weights, Texture Slices, and Cached BaseColor

The Weight Clipmap provides weights at multiple scales around the viewpoint. The DTA supplies terrain layer textures. The RVT producer blends those inputs into BaseColor, and the Base Pass reads the resulting tile. Each cache tracks its own residency. Uploading an array slice does not refresh an RVT tile that already contains the previous blend.

Resource Contents What to inspect
Height/Normal Atlas Encoded height and normal inputs for vertex processing File decode, size, Vertex Factory bindings
Weight Clipmap Weight windows and tiles by mip Viewpoint updates and weight consistency
DTA Texture array slices for color, normals, and other layer data Slot mapping, mip copies, access states
RVT Physical Tile Output of the RVT producer Tile production, sampling, invalidation
Texture Streaming Pool UE’s texture residency budget and use Runtime warnings and streaming counters
Both paths use the same height, normals, material IDs, and weights. The mobile path writes and reads BaseColor through RVT. Color swatches are schematic.
Figure 8. Both paths use the same height, normals, material IDs, and weights. The mobile path writes and reads BaseColor through RVT. Color swatches are schematic.
Terrain weights and texture slices feed the RVT producer. The Base Pass samples the cached BaseColor.
Figure 9. Terrain weights and texture slices feed the RVT producer. The Base Pass samples the cached BaseColor.

The Clipmap can follow the player camera or take a manually assigned viewpoint. Its Tick updates weights from the selected driver. In the capture below we moved the driver while keeping the orthographic capture camera and scale fixed.

The driver moved 254 m along +Y in Windows Android Vulkan Mobile Preview. Mip 0 moved two cells and uploaded 32 blocks. Mip 1 moved one cell and uploaded 25 blocks. Mip 2 stayed in place, while its outer retention ring uploaded 32 blocks again. The terrain image uses the regular surface material, which uses a flat weight texture in this capture. The overlay comes from the independent Weight Clipmap runtime trace.

Weight Clipmap before movement. The white marker is the driver. Solid outlines show the request windows for Mip 0, Mip 1, and Mip 2.
Figure 10. Weight Clipmap before movement. The white marker is the driver. Solid outlines show the request windows for Mip 0, Mip 1, and Mip 2.
Weight Clipmap after a 254 m move along +Y. Dashed outlines mark the previous windows, solid outlines show current requests, and fills show the source blocks uploaded in this update.
Figure 11. Weight Clipmap after a 254 m move along +Y. Dashed outlines mark the previous windows, solid outlines show current requests, and fills show the source blocks uploaded in this update.

DTA initialization registers the full map’s material IDs and repeatedly advances uploads and resizing through UploadAllNecessaryIds(). MaxRequestPerFrame=1 limits one scheduler invocation, and initialization can call the scheduler repeatedly. Testing sustained streaming on a phone still requires recording requests, uploads, evictions, misses, and memory along a fixed route.

Compositing BaseColor in RVT

The producer blends roads and terrain color into RVT. Once a tile is cached, the Base Pass can reuse it. Moving into an uncached region or invalidating an existing tile requests new production. Verify that the mesh participates in RVT rendering, the producer writes the right attribute, the Base Pass samples the same RVT, and stale regions can be regenerated.

The SceneProxy sets bRenderToVirtualTexture and RuntimeVirtualTextureMaterialType on the Mesh Batch. These fields tell the renderer which batches participate and how to render them. Collector.AddMesh() submits the batch for collection.

The configuration connects existing material inputs to the available Runtime Virtual Texture Output pins. It creates a Sample for the same RVT and connects the Sample’s BaseColor back to the main material.

# RVT Output and RVT Sample use the same RVT asset.
# Connect the existing material attributes to RVT Output.
sample = edit.create_material_expression(
    material, unreal.MaterialExpressionRuntimeVirtualTextureSample)
sample.set_editor_property("virtual_texture", rvt)

assert edit.connect_material_property(
    sample, "BaseColor", unreal.MaterialProperty.MP_BASE_COLOR)

The saved graph confirms that the road Custom node supplies BaseColor to the RVT Output.

Attribute RVT Output input Main material input
BaseColor Road Custom BaseColor from RVT Sample
Normal ComponentMask Same ComponentMask
Roughness RuntimeVirtualTextureReplace Same RuntimeVirtualTextureReplace

The RVT asset format determines which attributes a Physical Tile stores. This run verified the BaseColor write and read path. The Normal and Roughness entries describe the graph connections.

A change to an MID parameter can leave existing pages with their previous output. When required terrain textures become ready, the actor requests invalidation of the affected world bounds so the producer can blend those pages again.

Selecting CDLOD Nodes for an RVT View

The RVT view defines the world region covered by the page. For View->bIsVirtualTexture, the shared SceneProxy uses the cached main-view XY to calculate CDLOD distance and Geomorph. Other non-perspective views have related handling. This lets the page render its own region while preserving the main camera’s distance reference.

Mesh Batch UserData references Uniform Buffer parameters that the renderer consumes later. Clearing per-batch storage inside the view loop can free data still used by an earlier view. The implementation clears that storage at a guarded per-frame point, including when the terrain participates in RVT and shadow views.

Vulkan Draws in the Base Pass and RVT

Windows Vulkan SM5 and Windows Android Vulkan Mobile Preview used the same map, mobile material, and camera. After flushing RVT, we captured one frame in each configuration and selected one draw from the Base Pass and one from the RVT pass.

Configuration Pass Capture ID Vulkan call Indices Instances
Windows Vulkan SM5 BasePass 4024 vkCmdDrawIndexed 6,144 100
Windows Vulkan SM5 RVT page rendering 614 vkCmdDrawIndexed 6,144 100
Android Vulkan Mobile Preview on Windows MobileBasePass 3763 vkCmdDrawIndexed 6,144 100
Android Vulkan Mobile Preview on Windows RVT page rendering 530 vkCmdDrawIndexed 6,144 100

The shared 32 × 32 grid has 2,048 triangles and 6,144 indices per instance. All four calls passed indexCount=6144 and instanceCount=100 directly. Vulkan Synchronization2 was disabled for replay in both captures.

RVT Tile Layout and BaseColor Sampling

The RVT stores one Base Color layer. Its Tile Size is 256 × 256 texels, with a Tile Border of 4 texels on each side. The Physical Tile Size is therefore 264 × 264. Windows Vulkan SM5 and Windows Mobile Preview both reported DXT1 (BC1) with the same mobile material. The emulator confirmed the material binding. The PC SM6 log confirmed the shader platform at startup.

The nominal virtual dimension is 2¹⁴ × 256 = 4,194,304 texels. Per-axis dimensions also depend on the Volume aspect ratio and runtime TileCountBias. The physical pool allocation depends on format, layer count, and Physical Tile Size. Source code checks DXT1 support for the Base Color layer, then ETC2 RGB if needed. The APK’s ASTC cook target describes packaged textures. RVT chooses a format at runtime.

Page work starts with RequestPageData and ProducePageData. The renderer collects terrain meshes using the page view and submits VirtualTextureDraw. On the Vulkan indexed draw path, RHIDrawIndexedPrimitive reaches vkCmdDrawIndexed. The compression pass can dispatch vkCmdDispatch. If UAV format aliasing and direct compression are available and enabled, the pass can write to the physical target. The intermediate-texture path uses AddCopyTexturePass, then RHICopyTexture and vkCmdCopyImage. The captures confirm the selected draw calls. The compression and copy paths are traced in source.

In the Base Pass, the material supplies the Page Table, physical texture, and sampler. TextureLoadVirtualPageTableAdaptive looks up the Physical Tile. Tile Offset and Tile Border determine Physical UV for TextureVirtualSample, which uses SampleGrad or SampleLevel according to the shader permutation. The terrain material samples BaseColor from RVT and evaluates Normal and Roughness through their existing nodes.

RVT page rendering and Base Pass sampling. Captures confirm the selected indexed draws. The compression, copy, and sampling branches are shown from source.
Figure 12. RVT page rendering and Base Pass sampling. Captures confirm the selected indexed draws. The compression, copy, and sampling branches are shown from source.

Why the Road Bend Faded

Early PC and Mobile Preview comparison. The matched views below isolate the road blend change.
Figure 13. Early PC and Mobile Preview comparison. The matched views below isolate the road blend change.

Enlarging the road mask left one part of the loop nearly the color of the sand. The source BaseColor still showed the road. The source Streaming Virtual Texture (SVT) held the terrain texture data; the RVT held the result rendered at runtime. The change belonged in the RVT producer’s blend.

Source BaseColor diagnostic in Mobile Preview. The road remains visible in the southeast before it is blended with the terrain.
Figure 14. Source BaseColor diagnostic in Mobile Preview. The road remains visible in the southeast before it is blended with the terrain.
Custom input Purpose
Ground BaseColor from the preceding terrain blend
WP XYZ from the World Position node
Road Local road texture supplied by RoadColorPatch
Baked Map-wide source BaseColor
Mask Map-wide road coverage, sampled from red

Blending the Terrain and Applying the Road Overlay

The first blend combines Ground and Baked. The second applies the local road texture using its alpha. The two textures cover different areas and use different UVs.

// Map world XY to the local road texture. World units are centimeters.
float2 uv = (WP.xy - float2(334000, 321400)) / 25200.0;
float4 color = Road.SampleGrad(RoadSampler, saturate(uv), ddx(uv), ddy(uv));
float coverage = all(uv >= 0) && all(uv < 1) ? saturate(color.a) : 0;

// The map-wide mask and source BaseColor share UVs and derivatives.
float2 fullUV = (WP.xy - float2(44200, 44200)) / 730800.0;
float2 dx = ddx(fullUV);
float2 dy = ddy(fullUV);
float mask = Mask.SampleGrad(MaskSampler, saturate(fullUV), dx, dy).r;
float3 baked = Baked.SampleGrad(BakedSampler, saturate(fullUV), dx, dy).rgb;
float inside = all(fullUV >= 0) && all(fullUV < 1) ? 1.0 : 0.0;

SampleGrad takes explicit UV derivatives. The texture lookup clamps UVs to [0, 1], while the blend tests the original coordinates to keep the border color inside its intended coverage.

The old first-layer weight was saturate(mask) * inside. A page pixel with a large footprint can average a narrow road down to a faint mask value. That moves the blend toward Ground even when the source BaseColor still contains the road. Outside the local texture’s coverage, the overlay contributes nothing.

Preserving Road Color at Larger Footprints

The fix changes the first blend’s weight. The local alpha overlay remains the last operation.

// Estimate the source-texel footprint from the map-wide UV derivatives.
float footprint = max(length(dx), length(dy)) * 16384.0;
float coarseWeight = smoothstep(0.5, 2.0, footprint);

// Inside the coverage region, blend from the mask toward full source BaseColor.
float sourceWeight = lerp(saturate(mask), 1.0, coarseWeight) * inside;
float3 globalColor = lerp(Ground.rgb, baked, sourceWeight);
return lerp(globalColor, color.rgb, coverage);

Up to a footprint of 0.5, the blend uses the original mask. At 2.0 and above, it uses the full source color inside the coverage area. For a mask of 0.2 and a footprint of 1.25 inside the region, smoothstep returns 0.5 and the effective source weight becomes 0.6.

Baked and Mask use the same fullUV and derivatives. The material uses 16,384 as a reference width for estimating the footprint in source texels. The asset export confirms the inputs and UVs; the cooked texture dimensions should be checked when replacing either source texture. The derivatives come from RVT shading. Camera movement governs page requests, while the shader’s footprint depends on the current page pixel.

The grid shows the footprint of an RVT page pixel in the source texture. For inside = 1, the curve shows sourceWeight going from the sampled mask toward 1.
Figure 15. The grid shows the footprint of an RVT page pixel in the source texture. For inside = 1, the curve shows sourceWeight going from the sampled mask toward 1.

Matched Views Before and After the Fix

Both Lit screenshots were captured in Windows Android Vulkan Mobile Preview at (500000, 319000, 42000) cm, pitch −46°, yaw 135°, and 90° FOV. Primary and secondary screen percentages were 100, with dynamic resolution disabled. After positioning the camera, we flushed RVT, waited about 25 seconds, recorded residency, and exported 1920 × 1080 images. The old formula was restored in memory. The second run used the saved material.

Old blend at the matched viewpoint. The road remains dark at both ends, but the middle of the bend fades into the sand.
Figure 16. Old blend at the matched viewpoint. The road remains dark at both ends, but the middle of the bend fades into the sand.
Revised blend at the same viewpoint. The road color is continuous through the bend.
Figure 17. Revised blend at the same viewpoint. The road color is continuous through the bend.

The bend is continuous at this viewpoint with the revised blend. Increasing the contribution of source color can also change other colors inside the coverage region. The editor reported an access violation when exiting PIE after writing the final screenshot. The old-formula run exited normally, and the saved material’s SHA-256 matched its pre-capture value.

Source-color diagnostic from the southeast viewpoint after the fix, showing the bend in the surrounding road network.
Figure 18. Source-color diagnostic from the southeast viewpoint after the fix, showing the bend in the surrounding road network.

Regenerating RVT Tiles After a Cache Flush

The screenshot dimensions belong to their respective experiments. RVT virtual dimensions, Physical Tile Size, and screenshot dimensions describe different things.

Specification Windows Vulkan SM5 Android Vulkan Mobile Preview on Windows
Graphics API and RHI Vulkan on Windows Windows Vulkan RHI with Android shader platform
UE shader platform VULKAN_SM5 VULKAN_ES3_1_ANDROID Android_Preview_Vulkan
Captured output 3196 × 1808 in the separate D3D11/Windows Vulkan BaseColor comparison 1920 × 1080 in the road comparison, both screen percentages at 100, dynamic resolution off
Height/Normal Atlas 8192 × 8192 Same 8192 × 8192 atlas and sampling rules
RVT format and tile layout Base Color only; 256 × 256 Tile Size, 4 texels per side; DXT1 and 264 × 264 with the same mobile material Same layout; DXT1 and 264 × 264 in Windows Mobile Preview
Base Pass material Dynamic updates verified RVT supplies BaseColor; Normal and Roughness use separate nodes

Both runs moved from a close view to an overhead view and back, observed 300 frames, then flushed RVT and measured regeneration.

Observation Windows Vulkan SM5 Android Vulkan Mobile Preview on Windows
Tile renders in the 300 frames before flush 0 0
Tile renders after flush, through follow-up 276 200
Resident entries in the follow-up pool dump 265 194
Peak residency mip bias 0 0

Tile renders are counted over an interval. The pool dump reports entries at one instant. Tiles can be rendered, reused, or replaced between those observations. Page demand, cache state, viewport coverage, and producer cost can differ between the runs, so the counts do not give a GPU time ratio.

The 200 tile renders were counted over an interval. The pool dump listed 194 resident entries at a single point in time.
Figure 19. The 200 tile renders were counted over an interval. The pool dump listed 194 resident entries at a single point in time.

The earlier residency run used a separate camera sequence and configuration. For the road fix, the paired captures show the change in BaseColor after invalidation, while the cache statistics confirm that the producer rendered new pages and the pool contained resident entries.

Loading Terrain from the Android Package

On startup, UE’s platform file layer opens packaged Unreal File System (UFS) data from a mounted container. The older build opened the level but failed to read the terrain file because both the shading Actor and the terrain component prepended the project directory. The Actor now passes the project-relative path. The terrain component converts it once before opening the file. BeginPlay() checks that the configured path is nonempty and project-relative.

// Pass the project-relative path from the shading Actor.
CDLODRef->PayloadFilePath = ProjectRelativePayload;
CDLODRef->ReloadPayload();

// Resolve the path once in the terrain component.
FString Path = PayloadFilePath;
if (FPaths::IsRelative(Path))
{
    Path = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir(), Path);
}
Payload = TerrainFileLoader::LoadFromFile(Path);

Reading Material Weights from Terrain Data in Memory

The terrain component passes the loaded data to InitFromLoadedPayload(). Clipmap checks the object, dimensions, and initialization state, then builds its weight cache from the shared data. Its subsequent viewpoint updates supply the material IDs and blend weights to the shading path.

// Share the loaded terrain data with Clipmap.
const auto Payload = CDLODRef->GetPayload();
if (!Payload.IsValid() || !Payload->IsValid())
{
    return; // Stop if the terrain data is invalid.
}

if (!ClipmapActorRef->InitFromLoadedPayload(Payload))
{
    return; // Stop if weight-cache initialization fails.
}

Building Collision After Terrain Load

PostRegisterAllComponents() can run before the shading Actor sets the terrain path in BeginPlay(). In that case the earlier automatic collision attempt can be skipped. After the file loads, startup calls InitTerrainCollision() if automatic initialization is enabled and there are no collision patches yet.

// Build collision after loading if there are no patches yet.
if (ACDLODTerrainActor* Terrain =
        Cast<ACDLODTerrainActor>(CDLODRef->GetOwner());
    Terrain && Terrain->bInitializeCollisionOnRegister &&
    Terrain->GetCollisionPatchCount() == 0)
{
    if (!Terrain->InitTerrainCollision())
    {
        return; // Stop shading initialization if collision creation fails.
    }
}

When terrain data changes at runtime, the collision component requires the existing collision to be destroyed before switching its source. The Android startup log records material selection, collision readiness, and shading readiness. The ray and character tests ran in Windows Mobile Preview.

Keeping Collision Height Stable Across LOD Changes

Collision uses independent terrain data so the character’s support surface remains stable as the render mesh morphs. For CX cells per axis, the collision mesh needs CX+1 samples along the edge. It takes the neighboring block’s first row or column to complete that shared edge. The render atlas instead packs the continuous source samples for texture lookup.

Startup registered 3,364 collision patches, including 23 triangle meshes. It skipped 732 invisible blocks, accounting for all 4,096 input blocks. Triangle visibility controls hole handling. A fully hidden cell has no collision surface, while a half-visible cell must preserve its visible triangle.

The run covered 6,880 probes, 40 walk/run routes, 8 negative character tests, and steep slopes. Ray probes check whether a surface exists at a point. Character capsules can still find support on adjacent geometry at narrow openings, so the test suite checks both.

Android Emulator Startup

The Android Development package includes an APK and an OBB, totaling about 3.76 GB. The emulator started the test level with VULKAN_ES3_1_ANDROID, loaded the terrain data, registered collision patches, and bound the mobile RVT material.

The two emulator runs recorded LoadMap at approximately 77.7 s and 75.035 s. The total includes terrain reads, atlas generation, uploads, and collision registration.

Close view in the Android Vulkan emulator. The 1920 × 1080 screenshot retains the Texture Streaming Pool warning in the upper left.
Figure 20. Close view in the Android Vulkan emulator. The 1920 × 1080 screenshot retains the Texture Streaming Pool warning in the upper left.

The emulator log records a startup system resolution of 1280 × 720. The screenshot is 1920 × 1080, and the steady-state internal 3D resolution was not confirmed. The on-screen warning shows the Texture Streaming Pool approximately 26.6 MiB over its budget. It does not measure total device memory or the DTA’s allocation. Development package size also depends on the cook scope and shared desktop asset references.

Measuring Startup, Traversal, and Steady State

The editor PIE CSVs provide draw, frame, and page statistics for those runs. On-device profiling should hold route, camera, output resolution, materials, initial cache state, and measurement window fixed. Record initial loading and uploads, moving-camera page production, and steady-state rendering separately. One average frame rate hides which phase changed.

Profiling the Base Pass and RVT Separately

Identical geometry and height samples do not imply identical shader permutations, texture requests, or GPU timings. Check instance parameters, cooked shaders, and resource bindings in the Base Pass capture. For RVT, pair page production counters with GPU timing during the same camera movement.

In the matched PC backend comparison, D3D11 and Windows Vulkan SM5 had identical nonblack pixel coverage. Mean absolute BaseColor error over the common region was 0.273/255 in the close view and 0.340/255 in the overhead view.

The matched Lit view shows slightly softer near-ground detail in Mobile Preview. Source mips, anisotropic filtering, Physical Tile Size, and internal render resolution can all affect that image. A controlled comparison should vary one factor at a time. Changes to geometry sampling should also preserve silhouettes, transitions, and contact before their performance results are compared.

Results from Mobile Preview and the Android Package

Area Verified
Terrain inputs Shared height, material IDs, and weights
Geometry Mobile Preview uses the shared custom Vertex Factory and instance layout
RVT BaseColor write, sampling, and regeneration after invalidation in Windows preview
Roads The bend remains visible in the matched Windows Mobile Preview capture
Collision Probes, walk/run routes, negative character cases, and slopes in Windows Mobile Preview
Android startup Installed emulator build loads terrain data, registers collision, and renders the close view

A repeatable setup needs the source changes, the material graph and terrain data, the cook settings, and the capture conditions. The Git baseline alone identifies the starting point.

Terrain Memory and GPU Time on Physical Devices

Loading the Height Atlas in Blocks

The 8192 × 8192 atlas has a 256 MiB base mip at four bytes per texel. Startup may hold the file buffer, decoded heights, upload data, and the GPU atlas at the same time. Record allocation and release times as well as steady-state residency. Keep these measurements separate from the Texture Streaming Pool warning.

If atlas residency is the dominant cost, split the atlas into independently resident blocks. Keep drawing an available coarse node until the finer node’s samples and border data are ready. Traverse and backtrack over the same route to check reloads, evictions, and silhouette continuity.

Batching Texture Array Uploads

A 512² BGRA8 slice with a complete mip chain is about 1.33 MiB. A color slice and a normal slice total about 2.67 MiB at that example size. Track bytes, mips, and slices per batch. The emulator’s roughly 75 s LoadMap includes terrain reads, atlas construction, and collision registration alongside uploads.

If uploads dominate startup, prepare the beginning of the route first and upload subsequent layers with a byte budget. Publish the material ID to slot mapping when the slice is readable and invalidate regions that still cache the old color. Check first-frame time, hitches during traversal, and missing layers.

Timing RVT Production and Sampling

On the same device, measure the Base Pass after pages stabilize, then record tile production and GPU time along a fixed route. If traversal spends more time producing pages, inspect page coverage, update frequency, and the producer shader. Tune cooked texture samples and detail normals with exposure, resolution, and viewpoints held fixed. Include the separate Normal and Roughness paths in the Base Pass timing.

Loading Collision Ahead of the Character

Collision residency should follow the character’s path. Test boundary crossings, backtracking, slopes, and holes. Record when upcoming patches become ready and when old ones can be reclaimed. A coarse visual fallback still needs a stable collision surface.

Conclusion

The port keeps CDLOD’s quadtree selection, instance layout, and height atlas. The mobile material composites BaseColor into RVT, the Base Pass samples it, and texture-array uploads declare the correct Vulkan copy access. A footprint-aware blend keeps the road bend visible in the matched preview capture.

We used test terrain for this port. We will use other terrain assets to validate Android shading, resource costs, and stability on physical devices. The device runs will track startup peak memory, atlas residency, array uploads, RVT production during traversal, and steady-state Base Pass time.

AI-Assisted Review

AI assistance organized the supplied source and runtime records and traced the links between material selection, height sampling, DTA uploads, RVT, and startup. The review checked the saved road Custom node against the matched images and distinguished render-thread command processing from GPU completion. The runtime results describe the supplied captures and logs.

Source and Evidence Index

Source or record What it covers
CDLODSceneProxy.cpp Distance selection, instance packing, batches, RVT view reference, and parameter lifetime
CDLODVertexFactory.h/.cpp, CDLODVertexFactory.ush Parameters, bindings, Geomorph, height and normal sampling
TerrainShadingActor.cpp Mobile material selection, terrain loading, DTA initialization, and RVT invalidation
DTAResource.cpp Mip uploads, array slices, and access transitions
ClipmapActor.cpp Shared data, weight initialization, camera and manual viewpoints
CDLODComponent.cpp, TerrainCollisionComponent.cpp Path resolution, collision startup, shared edges, and physics state
Config/Android/AndroidEngine.ini Android build options
Mobile RVT configuration script and material exports RVT wiring, road Custom inputs, and footprint-aware blend
Matched capture notes and Weight Clipmap trace Viewpoint settings, exit behavior, window movement, and upload counts
Mobile PIE collision records Probes, walk/run routes, negative character cases, and slopes
PC and Mobile Preview profiling CSVs Page production and residency observations
Android startup and path error logs Packaged terrain load and collision initialization

The source and runtime records were collected in November 2026. The baseline, subsequent changes, cooked assets, and packaged build are separate inputs to reproduction. Platform and capture conditions are recorded alongside each result.

Leave a Comment