Keywords: UE4, Console, Command

Editor命令

ShowFlag

如果想在 Editor 中查看 Actor 蓝图的 Bounds(默认只能在 Static Mesh 编辑窗口中查看),可以使用 ShowFlag 命令(在编辑器窗口中按下波浪键打开输入窗口)。

开启:

ShowFlag.Bounds 1

关闭:

ShowFlag.Bounds 0

凡是 Show 命令能查看的参数,ShowFlag也能查看,包括Collision等。

如果想在游戏运行时查看指定物体的Bounds,那么可以先执行 ShowFlag.Bounds 1,然后再以 Simulate 模式运行游戏,然后再在场景中单击要查看的物体,就可以只显示该物体的Bounds信息。

运行时命令

Camera

修改Camera Mode(切换摄像机视角): Camera [modename] 其中modename的值为:

static const FName NAME_Fixed = FName(TEXT("Fixed"));
static const FName NAME_ThirdPerson = FName(TEXT("ThirdPerson"));
static const FName NAME_FreeCam = FName(TEXT("FreeCam"));
static const FName NAME_FreeCam_Default = FName(TEXT("FreeCam_Default"));
static const FName NAME_FirstPerson = FName(TEXT("FirstPerson"));

启用debug camera:

ToggleDebugCamera
Rendering

渲染优化分析视图模式:

//Lit view mode shows the final result of your scene once all of the Materials and lighting have been applied.
//Hotkey: Alt + 4
viewmode lit

//Unlit view mode removes all lighting from the scene, showing you Base Color only.
//Hotkey: Alt + 3
viewmode unlit

//Wireframe shows all of the polygon edges in the scene. In the case of Brushes, you will see the resultant geometry. 
//Hotkey: Alt + 2
viewmode wireframe

//Detail Lighting activates a neutral Material across the entire scene, using the normal maps of the original materials. This is useful for isolating whether your BaseColor is obscuring lighting by being too dark or noisy. 
//Hotkey: Alt + 5
viewmode lit_detaillighting

//Lighting Only shows a neutral Material that is only affected by lighting. It differs from Detail Lighting mode in that you will not see normal maps. 
//Hotkey: Alt + 6
viewmode lightingonly

//Light Complexity shows the number of non-static lights affecting your geometry. This is useful for tracking lighting cost - the more lights affecting a surface, the more expensive it will be to shade. 
//Hotkey: Alt + 7
viewmode lightcomplexity

//Shader Complexity Mode is used to visualize the number of shader instructions being used to calculate each pixel of your scene. It is generally a good indication of how performance-friendly your scene will be. In general, it is used to test overall performance for your base scene, as well as to optimize particle effects, which tend to cause performance spikes with a large amount of overdraw for a short period of time. 
//Hotkey: Alt + 8
viewmode shadercomplexity

//view quad overdraw
viewmode quadoverdraw

参考:View Modes
https://docs.unrealengine.com/4.26/en-US/BuildingWorlds/LevelEditor/Viewports/ViewModes/

显示 Buffer Visualization
先执行(若要退出Buffer Visualization,执行:ViewMode Lit):

//打开所有Buffer Visualization参数的矩阵视图
ViewMode VisualizeBuffer

再切换到单个参数视图,比如,想查看AO(若要退出当前视图,执行:r.BufferVisualizationTarget ""):

r.BufferVisualizationTarget AmbientOcclusion

其中,r.BufferVisualizationTarget的可选参数包括:BaseColor, CustomDepth, CustomStencil, FinalImage, ShadingModel, MaterialAO, Metallic, Opacity, Roughness, Anisotropy, SceneColor, SceneDepth, SeparateTranslucencyRGB, SeparateTranslucencyA Specular SubsurfaceColor WorldNormal AmbientOcclusion CustomDepthWorldUnits SceneDepthWorldUnits, PreTonemapHDRColor, PostTonemapHDRColor等。

ViewModer.BufferVisualizationTarget的参数,也就是Viewport左上角View ModeBuffer Visualization Mode下的菜单名:

参考:Console commands for Buffer Visualization
https://answers.unrealengine.com/questions/139442/console-commands-for-buffer-visualization.html

显示刚体

Show Collision

显示帧率

stat fps

限制最大帧率(需要提前关闭VSync)

t.MaxFPS 60

显示mesh drawcall

stat scenerendering

显示UMG Widget drawcall

stat slate

显示static mesh、skeletal mesh的三角面数量

stat Engine

显示硬件级(RHI)三角面总数和drawcall总数

stat rhi

其中:

  • Render target memory是buffer(比如g-buffer)或shadow map等render target的内存大小。buffer大小取决于分辨率,shadow map大小取决于阴影质量。
  • Triangles drawn是最终绘制的面数,即camera frustum和occlusion culling之后的面数。数量包含了shadowmap和tessellation,所以数值会显著高于stat Engine中的三角面数;
  • DrawPrimitive calls数量除了geometry,还包括decals、shadows、translucent lighting volumes、post processing等,其数值也会明显高于stat scenerendering中的draw call数。

显示单帧信息:总时长、Game耗时、Draw耗时、GPU耗时

stat Unit
stat UnitGraph  //附带各个参数的实时曲线图

显示当前帧的CPU时间信息(各种Tick, GC Mark,Update Overlaps等):

stat game

设置渲染分辨率为默认大小的50%(500就表示实际viewport大小的5倍尺寸来渲染,可以用来做压力测试,判断性能瓶颈是不是像素处理)

r.ScreenPercentage 50

r.SetRes也可以判断瓶颈是否和像素相关。和r.ScreenPercentage功能相同,但r.ScreenPercentage有额外开销。

r.SetRes 1920x1080f

如果是移动端,使用r.MobileContentScaleFactor来控制分辨率。MobileContentScaleFactor减小会导致UI变模糊,解决办法是对应增大ScreenPercentage

强制开启early Z pass:

r.EarlyZPass 2
r.EarlyZPassOnlyMaterialMasking 1

默认是r.EarlyZPass 3,表示根据硬件特性选择性开启(比如mask材质的物体可能不开启)。
EarlyZPass有没开启成功,可根据遮挡剔除有没生效来验证:

r.visualizeOccludedPrimitives 1

较高drawcall情况下,开启early Z后如果basepass的overdraw明显较少,说明early Z pass效果明显。修改值后需要重新运行游戏生效。更多细节参考:Mask material only in early Z-pass

设置贴图的尺寸级别(精度),前提是贴图已经生成了LOD(即mipmap)

r.mipmaplodbias 0

特效lodbias修改命令:

r.ParticleLODBias

强制以lod投射阴影:

r.ForceLODShadow

关闭遮挡剔除,默认开启:

r.AllowOcclusionQueries 0

运动模糊:

//0表示禁用,1-4表示模糊级别
r.MotionBlurQuality 0

若动作模糊默认开启,最好提供禁用开关,因为开启会增加晕3D玩家(motion sickness)的不适感。
另外过度锐化(sharpness)也会让晕3D玩家不适。

关闭或开启屏幕上打印信息(AddOnScreenDebugMessage)

DisableAllScreenMessages

EnableAllScreenMessages

Viewport高清截图(UI会被自动剔除)

//以当前viewport分辨率的两倍进行截图
HighResShot 2

//指定分辨率截图
HighResShot 3840x2160

图片存储位置:\Saved\Screenshots\

Taking Screenshots
https://docs.unrealengine.com/en-US/Engine/Basics/Screenshots/index.html

Dump Console Commands

Q:console的命令非常多,如何将所有命令全部dump出一个列表?
A:使用命令dumpconsolecommands,执行后,所有可用的命令会存储在\Saved\Logs\下的log文件中。

参考自:Where can I find all the console commands?
https://answers.unrealengine.com/questions/255772/where-can-i-find-all-the-console-commands.html

或者直接查看引擎源码:
Engine\Source\Runtime\Engine\Private\UnrealEngine.cpp

bool UEngine::Exec( UWorld* InWorld, const TCHAR* Cmd, FOutputDevice& Ar )
性能统计图工具 Session Frontend

用于记录某段时间内的性能分析数据。

在需要开始统计的时刻执行:

stat startfile

在统计完成的时刻执行:

stat stopfile

此时会在路径 Saved/Profiling/UnrealStats 下生成数据文件。
然后点击:Windows -》 Developer Tools -》 Session Frontend -》点击 Profiler 选项卡 -》 点击 Load 按钮,载入前面生成的数据文件。

性能统计自身也会消耗一定性能,有没办法将性能统计的自身消耗,从性能统计的计算结果中排除掉?答案是:No!至少目前版本不支持。

Profiling & Debugging

CPU

CPU性能问题(耗时高、卡顿等)大多出现在GameThread、RenderThread上。

记录卡顿时间(通过t.HitchFrameTimeThreshold(单位ms,默认60。旧版本叫t.HitchThreshold)定义卡顿时长阀值)

stat Hitches    //或者stat DumpHitches 记录log文件

程序运行时一旦某帧耗时超过t.HitchFrameTimeThreshold指定的时长,则函数堆栈就会被打印出来。
例如,以下 hitchdump 显示LoadObject耗时较长(Self表示函数堆栈中上一级函数,即LoadObject,所占用耗时),则表示是加载资源导致顿卡

   477.514ms (   4)  -  Thread_4118_0 - GameThread - STATGROUP_Threads - STATCAT_Advanced
     477.510ms (   2)  -  FrameTime - STAT_FrameTime - STATGROUP_Engine - STATCAT_Advanced
       470.844ms (   1)  -  FrameTime - STAT_FrameTime - STATGROUP_Engine - STATCAT_Advanced
         470.840ms (   1)  -  World Tick Time - STAT_WorldTickTime - STATGROUP_Game - STATCAT_Advanced
           470.758ms (   5)  -  Tick Time - STAT_TickTime - STATGROUP_Game - STATCAT_Advanced
             470.590ms (   2)  -  TG_PrePhysics - STAT_TG_PrePhysics - STATGROUP_TickGroups - STATCAT_Advanced
               470.585ms (   2)  -  ReleaseTickGroup Block - STAT_ReleaseTickGroup_Block - STATGROUP_TickGroups - STATCAT_Advanced
                 470.579ms (   1)  -  Game TaskGraph Tasks - STAT_TaskGraph_GameTasks - STATGROUP_Threading - STATCAT_Advanced
                   470.512ms (  20)  -  FTickFunctionTask - STATGROUP_TaskGraphTasks - STATCAT_Advanced
                     470.309ms (   1)  -  BaseGameMode/Game/Map/PVP/UEDPIE_0_PVP.PVP.PersistentLevel.BaseGameMode - STATGROUP_UObjects - STATCAT_Advanced
                       469.638ms (   3)  -  LoadObject - STAT_LoadObject - STATGROUP_Object - STATCAT_Advanced
                         377.887ms (   3)  -  Self
                         26.688ms ( 533)  -  STAT_FArchiveAsync2_WaitRead - STATGROUP_Quick - STATCAT_Advanced

stat DumpHitches命令有可选参数,-start-stop,表示dump的开始和结束位置:

stat DumpHitches -start
stat DumpHitches -stop

默认只会打印GameThread、RenderThread上的卡顿,如果希望打印其他线程卡顿,比如AudioThread、TaskGraph等,执行命令:t.DumpHitches.AllThreads 1

渲染相关的CPU性能问题还可以通过 stat scenerenderingstat game 等命令分析,如果某类型的 draw call 数量特别高,说明这是 CPU 的瓶颈所在。

CPU Profiling
https://docs.unrealengine.com/en-us/Engine/Performance/CPU

GPU

在编辑器中运行游戏时,按下 Ctrl + Shift + 逗号,或者命令行输入:profilegpu ,打开 GPUProfile 面板,显示当前帧的各类计算的耗时:PostProcess、Lighting 等。
注意:是当前一帧的耗时,不是平均每帧的耗时。

需要关闭VSync(默认是关闭),否则每帧的空闲等待时长会被算到计算耗时中。

另外一个类似命令:profilegpuhitches,表示每当GPU有卡顿时,自动弹出一个当时所在帧的 GPUProfile 面板。

GPUProfile面板上的可视化信息,在log文件(工程名\Saved\Logs\工程名.log)里面也会以文本形式打印出来。
在Development 打包模式下,由于无法打开GPUProfile 面板,所以分析数据只打印在log里,例如:

Profiling the next GPU frame
LogD3D11RHI: Warning: 
LogD3D11RHI: Warning: 
LogRHI: Perf marker hierarchy, total GPU time 4.33ms
LogRHI: Warning: Profiled range was continuous.
LogRHI: 100.0% 4.33ms   FRAME 635 draws 16087 prims 18018 verts
LogRHI: 97.1% 4.20ms   Scene 633 draws 15751 prims 17346 verts
LogRHI:     1.1% 0.05ms   PrePass DDM_AllOpaque (Forced by DBuffer) 141 draws 5744 prims 5634 verts
LogRHI:        0.3% 0.01ms   BeginRenderingPrePass 1 draws 0 prims 0 verts
LogRHI:     0.5% 0.02ms   ComputeLightGrid 5 draws 5 prims 0 verts
LogRHI:        0.3% 0.01ms   CullLights 30x17x32 NumLights 0 NumCaptures 1 4 draws 4 prims 0 verts
LogRHI:        0.2% 0.01ms   Compact 1 draws 1 prims 0 verts
LogRHI:     0.1% 0.00ms   BeginOcclusionTests 16 draws 192 prims 128 verts
LogRHI:        0.1% 0.00ms   ViewOcclusionTests 0 16 draws 192 prims 128 verts
LogRHI:           0.1% 0.00ms   IndividualQueries 16 draws 192 prims 128 verts

如果不需要gpu耗时存到文本,也不需要GUI面板,只是在屏幕上实时打印,使用命令:

stat gpu

如果是在编辑器模式,建议以“独立游戏”(Standalone Game)PIE模式运行,否则会把编辑器的消耗也算进去(即使是全屏模式)。

GPU Profiling
https://docs.unrealengine.com/en-us/Engine/Performance/GPU

Memory

查看low-level memory占用(启动游戏需追加参数:MyGame.exe -LLM):

stat LLMFull

查看Streaming内存占用详情(主要是texture内存占用):

stat Streaming
stat StreamingOverview

其中,texture pool大小等于Safety Pool + Temporary Pool + Streaming Pool + NonStreaming Mips
文档:Reporting Texture Streaming Metrics

内存相关的优化调试命令:memreport或者memreport -full

//这些命令定义在 Engine\Config\BaseEngine.ini 中
[MemReportCommands]
; These commands are run when memreport is executed, and output to a profile file
+Cmd="Mem FromReport"
+Cmd="LogCountedInstances"
+Cmd="obj list -alphasort"
+Cmd="rhi.DumpMemory"
+Cmd="LogOutStatLevels"
+Cmd="ListSpawnedActors"

[MemReportFullCommands]
; Additional commands to run with memreport -full
+Cmd="DumpParticleMem"
+Cmd="ConfigMem"
+Cmd="r.DumpRenderTargetPoolMemory"
+Cmd="ListTextures"
+Cmd="ListSounds -alphasort"
+Cmd="ListParticleSystems -alphasort"
+Cmd="obj list class=SoundWave -alphasort"
+Cmd="obj list class=SkeletalMesh -alphasort"
+Cmd="obj list class=StaticMesh -alphasort"
+Cmd="obj list class=Level -alphasort"
+Cmd="obj list class=StaticMeshComponent -alphasort"

使用obj list时,-alphasort表示按名字排序,其他可选项有:-countsort按数量排序,-resourcesizesort按内存占用大小排序。
ListTextures只支持名字排序,若要按内存占用排序,需要该引擎代码,代码位置:UEngine::HandleListTexturesCommand()(位于Engine\Source\Runtime\Engine\Private\UnrealEngine.cpp)。

处理obj list命令的代码位置:
Engine\Source\Runtime\Engine\Private\UnrealEngine.cpp

else if( FParse::Command(&Cmd,TEXT("LIST")) )

Low-Level Memory Tracker. Going over how to use the Low-Level Memory Tracker in your Unreal Engine projects.
https://docs.unrealengine.com/4.27/en-US/ProductionPipelines/DevelopmentSetup/Tools/LowLevelMemoryTracker/

Debugging and Optimizing Memory
https://www.unrealengine.com/en-US/blog/debugging-and-optimizing-memory

Crash Testing

Force game crash (not available in shipping):

debug threadcrash

Misc

工程设置相关

使用stat相关命令检测性能时,需要关闭Smooth Frame Rate来保证检测结果更精准:
Project Settings -> Engine -> General Settings -> Framerate -> Uncheck Smooth Frame Rate

运行时期间用C++执行console命名
UKismetSystemLibrary::ExecuteConsoleCommand(UObject* WorldContextObject, 
    const FString& Command, class APlayerController* SpecificPlayer = nullptr );
Scalability

Modify graphics quality at run-time:

r.PostProcessAAQuality 4
sg.PostProcessQuality 3
sg.ShadowQuality 3
sg.TextureQuality 3
sg.EffectsQuality 3
foliage.DensityScale 1.0
grass.DensityScale 1.0

For more detail see: Unreal Engine Scalability

如何在引擎或游戏启动时执行命令

方式1:修改 Engine/Config/ConsoleVariables.ini,例如,

[Startup]
r.FogDensity = 0.9
post.ImageGrain = 0.5

方式2:修改Engine.ini(BaseEngine.ini或者DefaultEngine.ini),在[SystemSettings]或[SystemSettingsEditor]分段下追加。

[SystemSettings]
r.DetectAndWarnOfBadDrivers = 0

[SystemSettingsEditor]
; System settings overrides for the editor.  Ideally the editor should use the same settings as the game.

; Do not vsync in the editor. Throws off gpu profiling.
r.VSync=0

[ConsoleVariables]分段也可添加,参考:UE5/Engine/Config/Android/AndroidEngine.ini

[ConsoleVariables]
Slate.CacheRenderData=0
r.VSync=1
r.ParallelShadows=0
; high priority thread tasks can be downgraded to normal priority if a task is created with EPowerSavingEligibility::Eligible.
TaskGraph.EnablePowerSavingThreadPriorityReduction=1
; prefer D24_S8 for depth/stencil
r.Vulkan.Depth24Bit=1
;GalaxyS6Edge=577
r.Shadow.ForceSerialSingleRenderPass=1
; Support Mali 64k texel buffer limitation, tuned for 1080p. If you target 2k-4k resolutions please also set the LightGridPixelSize to 128
r.Forward.LightGridSizeZ = 8
r.Forward.MaxCulledLightsPerCell = 8
r.HairStrands.Simulation=0
r.HairStrands.Strands=0
r.HairStrands.Binding=0
; R11G11B10 UAV is not supported on Android
r.TemporalAA.R11G11B10History=0
; Do not backtrace vulkan memory allocations
r.Vulkan.MemoryBacktrace=0
查询命令的参数值

C++ 或者 蓝图中使用查询函数

float UKismetSystemLibrary::GetConsoleVariableFloatValue(const FString& VariableName)

int32 UKismetSystemLibrary::GetConsoleVariableIntValue(const FString& VariableName)

例如:

先在命令行执行

r.ScreenPercentage 200

然后通过蓝图或者C++查询

//RetVal is 200.f
float RetVal = KismetSystemLibrary::GetConsoleVariableIntValue(TEXT("r.ScreenPercentage"));

文档

Commands

Stat Commands
https://docs-origin.unrealengine.com/latest/INT/Engine/Performance/StatCommands/

Unreal Engine 4 Console Variables and Commands
https://digilander.libero.it/ZioYuri78/

Measuring Performance
https://unrealartoptimization.github.io/book/process/measuring-performance/

Unreal Engine 4.19 Console Variables and Commands
https://pongrit.github.io/