This commit is contained in:
C
2023-02-06 17:17:44 +05:00
parent 9d03a8eb1b
commit e9f3169a6f
804 changed files with 2798 additions and 24737 deletions
-23
View File
@@ -1,23 +0,0 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "1.22",
"FriendlyName": "Character Creator & iClone Auto Setup",
"Description": "Automatic shader and skeletal assignment for CC Characters and iClone Assets, including Blueprint generation for material properties, texture settings and model configurations. ",
"Category": "Reallusion",
"CreatedBy": "Reallusion",
"CreatedByURL": "",
"DocsURL": "",
"MarketplaceURL": "",
"SupportURL": "",
"EngineVersion": "4.27.0",
"CanContainContent": false,
"Installed": true,
"Modules": [
{
"Name": "RLPlugin",
"Type": "Editor",
"LoadingPhase": "PreDefault"
}
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

@@ -1,29 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Factories/FbxFactory.h"
#include "Runtime/SlateCore/Public/Styling/SlateTypes.h"
//#include "SlateBasics.h"
#include "Factories/Factory.h"
#include "UObject/ObjectMacros.h"
#include "CCImportUI.h"
#include "CCFbxFactory.generated.h"
class UTextureFactory;
UCLASS(hidecategories = Object)
class UCCFbxFactory : public UFbxFactory
{
GENERATED_UCLASS_BODY()
public:
//~ UFactory Interface
virtual UObject* FactoryCreateFile( UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, const FString& InFilename, const TCHAR* Parms, FFeedbackContext* Warn, bool& bOutOperationCanceled );
virtual void PostInitProperties() override;
void ImportTextureFolder( FString& fbxRootPath, FString& rootGamePath, TArray< TCHAR* > kFileExtension, FString &fbxName, TArray<FString> &kTextureList );
TArray<FString> GetLODPaths( FString &targetFolderPath, FString &FbxName );
void SetShaderType( FString shaderType );
private:
FString m_ShaderType = "Standard";
};
@@ -1,33 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "CCImportUI.generated.h"
/**
* TODO:
*/
UCLASS( config = EditorPerProjectUserSettings, AutoExpandCategories = ( FTransform ), HideCategories = Object, MinimalAPI )
class UCCImportUI : public UObject
{
GENERATED_BODY()
public:
UCCImportUI( const FObjectInitializer& kObjectInitializer );
void WriteConfig();
private:
void ReadConfig();
public:
bool isCCAutoSetup;
bool isHQSkin;
bool isLWSkin;
bool isStandardSkin;
bool isCanceled;
bool isCanChangeAutoEnable;
bool hasCCShader;
bool isLiveLink;
};
@@ -1,405 +0,0 @@
#pragma once
#include "CoreMinimal.h"
TMap< FString, FString > g_kTeethMap =
{
{ "Gums Mask", "Teeth Mask Map" },
{ "Gradient AO", "Gradient AO Map" },
{ "MicroNormal", "MicroNormal Map" },
// MicroNormal
{ "Flip MicroNormal Y", "Flip Micro Normal Y" },
{ "Teeth MicroNormal Tiling", "Teeth MicroNormal Tiling" },
{ "Teeth MicroNormal Strength", "Teeth MicroNormal Strength" },
{ "Gums MicroNormal Tiling", "Flesh MicroNormal Tiling" },
{ "Gums MicroNormal Strength", "Flesh MicroNormal Strength" },
// TeethGum
{ "Teeth Edge Color", "Teeth Edge Color" },
{ "Is Upper Teeth", "Is Upper Teeth" },
{ "Teeth Brightness", "Teeth Diffuse Brightness" },
{ "Teeth Desaturation", "Teeth Desaturation" },
{ "Gums Brightness", "Flesh Brightness" },
{ "Gums Desaturation", "Flesh Desaturation" },
{ "Front Roughness", "TeethGum Front Roughness" },
{ "Front Specular", "TeethGum Front Specular" },
// TeethGum-Adv
{ "Front AO", "TeethGum Front AO" },
{ "Back AO", "TeethGum Back AO" },
{ "Back Roughness", "TeethGum Back Roughness" },
{ "Back Specular", "TeethGum Back Specular" },
// SSS
{ "Gums Scatter", "Flesh Scatter" },
{ "Teeth Scatter", "Teeth Scatter" }
};
TMap< FString, FString > g_kTongueMap =
{
{ "MicroNormal", "MicroNormal Map" },
{ "Gradient AO", "Gradient AO Map" },
// MicroNormal
{ "Flip MicroNormal Y", "Flip Micro Normal Y" },
{ "MicroNormal Tiling", "Flesh MicroNormal Tiling" },
{ "MicroNormal Strength", "Flesh MicroNormal Strength" },
// Tongue
{ "_Brightness", "Flesh Brightness" },
{ "_Desaturation", "Flesh Desaturation" },
{ "Front Roughness", "Tongue Front Roughness" },
{ "Front Specular", "Tongue Front Specular" },
// Tongue-Adv
{ "Back Roughness", "Tongue Back Roughness" },
{ "Back Specular", "Tongue Back Specular" },
{ "Front AO", "Tongue Front AO" },
{ "Back AO", "Tongue Back AO" },
// SSS
{ "_Scatter", "Flesh Scatter" }
};
TMap< FString, FString > g_kSkinMap =
{
{ "SSS Map", "SSS Map" },
{ "MicroNormalMask", "MicroNormal Mask Map" },
{ "MicroNormal", "MicroNormal Map" },
{ "RGBA Area Mask", "RGBA Area Mask Map" },
{ "_BaseColorMap Brightness", "BaseColorMap_Brightness" },
{ "_BaseColorMap Saturation", "BaseColorMap_Saturation" },
// MicroNormal
{ "Flip MicroNormal Y", "Flip Micro Normal Y" },
{ "MicroNormal Tiling", "MicroNormal Tiling Value" },
{ "MicroNormal Strength", "MicroNormal Strength" },
// Roughness
{ "Micro Roughness Scale", "Micro Roughness Scale" },
{ "R Channel Roughness Scale", "R Channel Roughness Scale" },
{ "G Channel Roughness Scale", "G Channel Roughness Scale" },
{ "B Channel Roughness Scale", "B Channel Roughness Scale" },
{ "A Channel Roughness Scale", "A Channel Roughness Scale" },
{ "Unmasked Roughness Scale", "Unmask Roughness Scale" },
{ "Edge Roughness Multiplier", "Edge Roughness Multiplier" },
// Specular Metallic
{ "_Specular", "Specular" },
{ "SSS Metallic Threshold", "Metallic SSS Threshold" },
// SSS
{ "G Channel Scatter Scale", "G Channel Scatter" },
{ "R Channel Scatter Scale", "R Channel Scatter" },
{ "B Channel Scatter Scale", "B Channel Scatter" },
{ "A Channel Scatter Scale", "A Channel Scatter" },
{ "Unmasked Scatter Scale", "SSS Unmasked Scale" }
};
TMap< FString, FString > g_kHeadMap =
{
{ "BaseColor Blend2", "Blend Map_2" },
{ "NormalMap Blend", "NormalMap_Blend" },
{ "SSS Map", "SSS Map" },
{ "MicroNormalMask", "MicroNormal Mask Map" },
{ "MicroNormal", "MicroNormal Map" },
{ "Specular Mask", "Specular Cavity Map" },
{ "Mouth Cavity Mask and AO", "Mouth Cavity And AO Map" },
{ "Nose Mouth UpperInnerLid Mask", "NLML Mask Map" },
{ "Cheek Fore UpperLip Chin Mask", "CFUC Mask Map" },
{ "Ear Neck Mask", "EN Mask Map" },
// Blend Map
{ "BaseColor Blend2 Strength", "BaseColor_Blend2_Strength" },
{ "NormalMap Blend Strength", "NormalMap_Blend_Strength" },
{ "_BaseColorMap Brightness", "BaseColorMap_Brightness" },
{ "_BaseColorMap Saturation", "BaseColorMap_Saturation" },
// MicroNormal
{ "Flip MicroNormal Y", "Flip Micro Normal Y" },
{ "MicroNormal Tiling", "MicroNormal Tiling Value" },
{ "MicroNormal Strength", "MicroNormal Strength" },
// Roughness
{ "Micro Roughness Scale", "Micro Roughness Scale" },
{ "Nose Roughness Scale", "Nose Roughness Scale" },
{ "Mouth Roughness Scale", "Mouth Roughness Scale" },
{ "UpperLid Roughness Scale", "UpperLid Roughness Scale" },
{ "InnerLid Roughness Scale", "InnerLid Roughness Scale" },
{ "Ear Roughness Scale", "Ear Roughness Scale" },
{ "Neck Roughness Scale", "Neck Roughness Scale" },
{ "Cheek Roughness Scale", "Cheek Roughness Scale" },
{ "Forehead Roughness Scale", "Forehead Roughness Scale" },
{ "UpperLip Roughness Scale", "UpperLips Roughness Scale" },
{ "Chin Roughness Scale", "Chin Roughness Scale" },
{ "Unmasked Roughness Scale", "Unmask Roughness Scale" },
{ "Edge Roughness Multiplier", "Edge Roughness Multiplier" },
// Specular Metallic
{ "_Specular", "Head Specular" },
{ "SSS Metallic Threshold", "Metallic SSS Threshold" },
{ "Inner Mouth AO", "Inner Mouth AO" },
{ "Nostril AO", "Nostril AO" },
{ "Lips Gap AO", "Lips_Gap_AO" },
// SSS
{ "Nose Scatter Scale", "Nose Scatter Scale" },
{ "Mouth Scatter Scale", "Mouth Scatter Scale" },
{ "UpperLid Scatter Scale", "UpperLid Scatter Scale" },
{ "InnerLid Scatter Scale", "InnerLid Scatter Scale" },
{ "Ear Scatter Scale", "Ear Scatter Scale" },
{ "Neck Scatter Scale", "Neck Scatter Scale" },
{ "Cheek Scatter Scale", "Cheek Scatter Scale" },
{ "Forehead Scatter Scale", "Forehead Scatter Scale" },
{ "UpperLip Scatter Scale", "UpperLips Scatter Scale" },
{ "Chin Scatter Scale", "Chin Scatter Scale" },
{ "Unmasked Scatter Scale", "SSS Unmasked Scale" }
};
TMap< FString, FString > g_kEyeMap =
{
{ "Iris Normal", "Iris Normal Map" },
{ "Sclera Normal", "Normal Map" },
{ "EyeBlendMap2", "EyeBlendMap2" },
{ "Inner Iris Mask", "Inner Iris Mask" },
{ "Sclera", "Sclera Map" },
// Eye
{ "BlendMap2 Strength", "BlendMap2_Strength" },
{ "Shadow Radius", "Shadow Radius" },
{ "Shadow Hardness", "Shadow Hardness" },
{ "Specular Scale", "Specular Multiplier" },
// Eye-Adv
{ "Is Left Eye", "Is Left Eye" },
{ "Eye Corner Darkness Color", "Eye Corner Darkness Color" },
// Iris
{ "Iris Depth Scale", "Iris Depth Scale" },
{ "_Iris Roughness", "Iris Roughness" },
{ "Iris Color Brightness", "Iris Color Brightness" },
{ "Pupil Scale", "Pupil Scale" },
// Iris-Adv
{ "_IoR", "Ior" },
{ "Iris Cloudy Color", "Iris Cloudy Color" },
{ "Iris Inner Color", "Iris Inner Color" },
{ "Iris Inner Scale", "Iris Inner Scale" },
{ "Iris UV Radius", "Iris UV Radius" },
{ "Iris Color", "Iris Color" },
// Limbus
{ "Limbus UV Width Color", "Limbus UV Width Color" },
{ "Limbus Dark Scale", "Limbus Dark Scale" },
// Sclera
{ "ScleraBrightness", "Sclera Brightness" },
{ "Sclera Roughness", "Sclera Roughness" },
// Sclera-Adv
{ "Sclera Flatten Normal", "Sclera Normal" },
{ "Sclera Normal UV Scale", "Sclera Normal UV Scale" },
{ "Sclera UV Radius", "Sclera UV Radius" },
};
#define FLIP_TANGENT_Y "Flip Tangent Y"
#define ACTIVATE_HAIR_COLOR "Activate Hair Color"
TMap< FString, FString > g_kHairMap =
{
{ "Hair Tangent Map" , "Tangent Map" },
{ "Hair Flow Map" , "Flow Map" },
{ "Hair Specular Mask Map", "Specular Map" },
{ "Hair Root Map" , "Root Map" },
{ "Hair ID Map" , "ID Map" },
{ "TangentMapFlipGreen", FLIP_TANGENT_Y },
{ "AO Map Occlude All Lighting", "AO Map Occlude All Lighting" },
{ "Diffuse Strength", "Scatter" },
{ "Hair Roughness Map Strength", "Roughness Multiplier" },
{ "Hair Specular Map Strength", "Specular Multiplier" },
{ "VertexGrayToColor" , "Vertex Color" },
{ "VertexColorStrength" , "Vertex Color Strength" },
{ "ActiveChangeHairColor" , ACTIVATE_HAIR_COLOR },
{ "BaseColorMapStrength" , "Base Color Map Strength" },
// Strand Color
{ "RootColor" , "Root Color" },
{ "TipColor" , "End Color" },
{ "RootTipBlendMode" , "Root End Blend Mode" },
{ "UseRootTipColor" , "Global Strength" },
{ "RootColorStrength" , "Root Color Strength" },
{ "TipColorStrength" , "End Color Strength" },
{ "InvertRootTip" , "Invert Root and End Color" },
// highlight A
{ "_1st Dye Color" , "Highlight A Color" },
{ "_1st Dye Strength" , "Highlight A Strength" },
{ "_1st Dye Distribution from Grayscale", "Highlight A Affected Range" },
{ "_1st BlendMode" , "Highlight A Blend Mode" },
{ "Mask 1st Dye by RootMap" , "Highlight A Overlap End Color" },
{ "Invert 1st Dye RootMap Mask" , "Highlight A Invert End to Root Color" },
{ "_1st Dye add Specular" , "Highlight A Specular Strength" },
// hightlight B
{ "_2nd Dye Color" , "Highlight B Color" },
{ "_2nd Dye Strength" , "Highlight B Strength" },
{ "_2nd Dye Distribution from Grayscale", "Highlight B Affected Range" },
{ "_2nd BlendMode" , "Highlight B Blend Mode" },
{ "Mask 2nd Dye by RootMap" , "Highlight B Overlap End Color" },
{ "Invert 2nd Dye RootMap Mask" , "Highlight B Invert End to Root Color" },
{ "_2nd Dye add Specular" , "Highlight B Specular Strength" },
//
{ "BlackColor Reflection Offset X", "Rotate Vertical by Black ID" },
{ "BlackColor Reflection Offset Y", "Rotate Horizontal by Black ID" },
{ "BlackColor Reflection Offset Z", "Shift by Black ID" },
{ "WhiteColor Reflection Offset X", "Rotate Vertical by White ID" },
{ "WhiteColor Reflection Offset Y", "Rotate Horizontal by White ID" },
{ "WhiteColor Reflection Offset Z", "Shift by White ID" },
};
TMap< FString, FString > g_kEyeOccusionMap =
{
{ "Display Blur Range", "Blur Color" },
{ "Blur Strength", "Blur Strength" },
{ "_Expand", "Expand" },
{ "Top Blur Range", "Top Blur Range" },
{ "Top Blur Contrast", "Top Blur Contrast" },
{ "Bottom Blur Range", "Bottom Blur Range" },
{ "Bottom Blur Contrast", "Bottom Blur Contrast" },
{ "Outer Corner Blur Range", "Outer Corner Blur Range" },
{ "Outer Corner Blur Contrast", "Outer Corner Blur Contrast" },
{ "Tear Duct Position", "Tear Duct Position" },
{ "Tear Duct Contrast", "Tear Duct Contrast" },
{ "Tear Duct Shadow Offset", "Tear Duct Shadow Offset" },
// 1st layer shadow
{ "Shadow Color", "Shadow 1 Color" },
{ "Shadow Strength", "Shadow 1 Strength" },
{ "Shadow Top", "Shadow 1 Top" },
{ "Shadow Top Range", "Shadow 1 Top Range" },
{ "Shadow Top Arc", "Shadow 1 Top Edge" },
{ "Shadow Bottom", "Shadow 1 Bottom" },
{ "Shadow Bottom Range", "Shadow 1 Bottom Range" },
{ "Shadow Bottom Arc", "Shadow 1 Bottom Edge" },
{ "Shadow Inner Corner", "Shadow 1 Inner Corner" },
{ "Shadow Inner Corner Range", "Shadow 1 Inner Corner Range" },
{ "Shadow Outer Corner", "Shadow 1 Outer Corner" },
{ "Shadow Outer Corner Range", "Shadow 1 Outer Corner Range" },
// 2nd_Layer_Shadow
{ "Shadow2 Color", "Shadow 2 Color" },
{ "Shadow2 Strength", "Shadow 2 Strength" },
{ "Shadow2 Top", "Shadow 2 Top" },
{ "Shadow2 Top Range", "Shadow 2 Top Range" },
// Vertex_Offset
{ "Depth Offset", "Depth Offset" },
{ "Fade Distance", "Fade Distance" }, // depth fade distance
{ "Top Offset", "Top Offset" },
{ "Bottom Offset", "Bottom Offset" },
{ "Inner Corner Offset", "Inner Corner Offset" },
{ "Outer Corner Offset", "Outer Corner Offset" },
};
TMap< FString, FString > g_kTearLineMap =
{
{ "Depth Offset", "DepthOffset" },
{ "Detail Amount", "DetailAmount" },
{ "Detail Scale U", "DetailScale_U" },
{ "Detail Scale V", "DetailScale_V" },
{ "Edge Fadeout", "Edge_fadeout" },
{ "_Roughness", "Roughness" }
};
#define AO_MAP_OCCLUDE_ALL_LIGHTS "Occlude All Lighting"
#define FLIP_MICRO_NORMAL_Y "Flip Micro Normal Y"
TMap< FString, FString > g_kGeneralMap =
{
{ "SSS Map", "SSS Map" },
{ "MicroNormalMask", "MicroNormal Mask Map" },
{ "MicroNormal", "MicroNormal Map" },
{ "RGBA Area Mask", "RGBA Area Mask Map" },
{ "_BaseColorMap Brightness", "BaseColorMap_Brightness" },
{ "_BaseColorMap Saturation", "BaseColorMap_Saturation" },
{ "AO Map Affect All Lights", AO_MAP_OCCLUDE_ALL_LIGHTS },
// Micro_Normal
{ "Flip MicroNormal Y", FLIP_MICRO_NORMAL_Y },
{ "MicroNormal Tiling", "MicroNormal Tiling Value" },
{ "MicroNormal Strength", "MicroNormal Strength" },
// _Specular_Roughness
{ "_Specular", "Specular" },
{ "Micro Roughness Scale", "Micro Roughness Scale" },
// _Specular_Roughness-Adv
{ "R Channel Roughness Scale", "R Channel Roughness Scale" },
{ "G Channel Roughness Scale", "G Channel Roughness Scale" },
{ "B Channel Roughness Scale", "B Channel Roughness Scale" },
{ "A Channel Roughness Scale", "A Channel Roughness Scale" },
{ "Unmasked Roughness Scale", "Unmask Roughness Scale" },
{ "Edge Roughness Multiplier", "Edge Roughness Multiplier" },
// SSS
{ "R Channel Scatter Scale", "R Channel Scatter" },
{ "G Channel Scatter Scale", "G Channel Scatter" },
{ "B Channel Scatter Scale", "B Channel Scatter" },
{ "A Channel Scatter Scale", "A Channel Scatter" },
{ "Unmasked Scatter Scale", "SSS Unmasked Scale" },
};
class RLShaderData
{
public:
RLShaderData() {}
~RLShaderData() {}
FString m_strShaderName;
TMap< FString, FString > m_kTexture;
TMap< FString, float > m_kParameter;
TMap< FString, TArray< float > > m_kColorParameter;
};
class RLScatter
{
public:
RLScatter() {}
~RLScatter() {}
RLScatter( FLinearColor sss,
FLinearColor falloff,
float radius,
float distribution,
float IOR,
float extinction,
float normalScale,
float roughness1,
float roughness2,
float lobeMix )
:m_kFalloff( falloff ),
m_fRadius(radius),
m_fDistribution(distribution),
m_fIOR(IOR),
m_kSubsurfaceColor( sss ),
m_fExtinctionScale(extinction),
m_fNormalScale(normalScale),
m_fRoughness0(roughness1),
m_fRoughness1(roughness2),
m_fLobeMix(lobeMix)
{
}
void SetDefaultParameter( FLinearColor kSubsurfaceColor,
float fDistribution,
float fIOR,
float fExtinctionScale,
float fNormalScale,
float fRoughness0,
float fRoughness1,
float fLobeMix )
{
m_kSubsurfaceColor = kSubsurfaceColor;
m_fDistribution = fDistribution;
m_fIOR = fIOR;
m_fExtinctionScale = fExtinctionScale;
m_fNormalScale = fNormalScale;
m_fRoughness0 = fRoughness0;
m_fRoughness1 = fRoughness1;
m_fLobeMix = fLobeMix;
}
FLinearColor m_kFalloff;
float m_fRadius = 0.0f;
float m_fDistribution = 0.0f;
float m_fIOR = 0.0f;
FLinearColor m_kSubsurfaceColor;
float m_fExtinctionScale = 0.0f;
float m_fNormalScale = 0.0f;
float m_fRoughness0 = 0.0f;
float m_fRoughness1 = 0.0f;
float m_fLobeMix = 0.0f;
};
@@ -1,4 +0,0 @@
#pragma once
#define Version_Error_Message "The current procedure has come to a stop because auto-setup is not support for this version of CC / iClone. Please update to the appropriate version."
#define Version_Not_Suitable "Auto-setup is not support for this version of CC / iClone and some issues may occur as a result. Please update to the appropriate version."
@@ -1,53 +0,0 @@
#pragma once
//#include "SlateBasics.h"
class UCCImportUI;
class SCCImportWindow : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SCCImportWindow)
: _ImportUI(NULL)
, _WidgetWindow()
//, _SourcePath()
//, _TargetPath()
{}
SLATE_ARGUMENT(UCCImportUI*, ImportUI)
SLATE_ARGUMENT(TSharedPtr<SWindow>, WidgetWindow)
// SLATE_ARGUMENT(FText, SourcePath)
//SLATE_ARGUMENT(FText, TargetPath)
SLATE_END_ARGS()
public:
void Construct(const FArguments& InArgs);
private:
UCCImportUI* ccImportUI;
TWeakPtr< SWindow > WidgetWindow;
TSharedPtr< SButton > ImportButton;
//FString TargetPath;
bool isCCAutoSetup;
bool isHQSkin;
bool isLWSkin;
bool isStandardSkin;
bool isliveLink;
//TSharedRef<SWidget> GetTestContent() const;
FString skinType = "Standard";
ECheckBoxState IsStandardActive() const;
ECheckBoxState IsHQActive() const;
ECheckBoxState IsLWActive() const;
void OnCCLiveLinkChanged(ECheckBoxState InCheckedState);
void OnCCAutoSetupChanged(ECheckBoxState InCheckedState);
void OnStandardChanged(ECheckBoxState InCheckedState);
void OnHQChanged(ECheckBoxState InCheckedState);
void OnLWChanged(ECheckBoxState InCheckedState);
TSharedPtr< SCheckBox > Standard_CheckBox;
TSharedPtr< SCheckBox > HQ_CheckBox;
TSharedPtr< SCheckBox > LW_CheckBox;
TSharedPtr< SCheckBox > CCAutoSetup_CheckBox;
FReply OnCancel();
FReply OnNext();
FReply OnMore();
};
@@ -1,43 +0,0 @@
#pragma once
#include "RLTextureData.h"
#include "RLPhysicClothData.h"
#include "RLShaderData.h"
enum class ENodeType
{
None,
Hair,
Accessory
};
class RLMaterialData
{
public:
RLMaterialData() {}
~RLMaterialData() {}
void SetShaderData( TSharedPtr< RLShaderData > spShaderData ) { m_spShaderData = spShaderData; }
const RLShaderData* GetShaderData() const { return m_spShaderData ? m_spShaderData.Get() : nullptr; }
RLShaderData* GetShaderData() { return m_spShaderData ? m_spShaderData.Get() : nullptr; }
void SetScatter( TSharedPtr< RLScatter > spScatter ) { m_spScatter = spScatter; }
RLScatter* GetScatter() { return m_spScatter ? m_spScatter.Get() : nullptr; }
bool m_bIsPbr = false;
ENodeType m_eNodeType = ENodeType::None;
bool m_bTwoSide = false;
int m_iUvChannelIndex = 0;
TArray< float > m_kDiffuseColor = { 255.f, 255.f, 255.f };
TArray< float > m_kAmbientColor = { 50.f, 50.f, 50.f };
TArray< float > m_kSpecularColor = { 229.f, 229.f, 229.f };
float m_fOpacity = 1.f;
float m_fSelfIllumination = 0.f;
float m_fSpecular = 0.f;
float m_fGlossiness = 0.f;
TMap< FString, RLTextureData > m_kTextureDatas;
TSharedPtr< RLPhysicClothData > m_spPhysicClothData = nullptr;
private:
TSharedPtr< RLShaderData > m_spShaderData;
TSharedPtr< RLScatter > m_spScatter;
};
@@ -1,28 +0,0 @@
#pragma once
#include "CoreMinimal.h"
class RLPhysicClothData
{
public:
RLPhysicClothData() {}
~RLPhysicClothData() {}
bool m_bActivate = false;
bool m_bUseGlobalGravity = false;
FString m_strWeightMapPath = "";
float m_fMass = 0.f;
float m_fFriction = 0.f;
float m_fDamping = 0.f;
float m_fDrag = 0.f;
float m_fSolverFrequency = 0.f;
float m_fTetherLimit = 0.f;
float m_fElasticity = 0.f;
float m_fStretch = 0.f;
float m_fBending = 0.f;
TArray< float > m_kInertia = { 6.0, 6.0, 6.0 };
bool m_bSoftVsRigidCollision = false;
float m_fSoftVsRigidCollisionMargin = 0.f;
bool m_bSelfCollision = false;
float m_fSelfCollisionMargin = 0.f;
float m_fStiffnessFrequency = 0.f;
};
@@ -1,27 +0,0 @@
#pragma once
#include "CoreMinimal.h"
class RLPhysicsCollisionShapeData
{
public:
RLPhysicsCollisionShapeData() {}
~RLPhysicsCollisionShapeData() {}
FString m_strName = "";
bool m_bBoneActivate = false;
bool m_bIsCCStdBoneAxis = false;
FString m_strBoundType = "";
FString m_strBoundAxis = "";
float m_fMargin = 0.f;
float m_fFriction = 0.f;
float m_fElasticity = 0.f;
TArray< float > m_kWorldTranslate = { 0.0, 0.0, 0.0 };
TArray< float > m_kWorldRotation = { 0.0, 0.0, 0.0, 0.0 };
TArray< float > m_kWorldScale = { 0.0, 0.0, 0.0 };
TArray< float > m_kShapeLocalPosition = { 0.0, 0.0, 0.0 };
TArray< float > m_kExtent = { 0.0, 0.0, 0.0 };
float m_fRadius = 0.f;
float m_fCapsuleLength = 0.f;
};
@@ -1,160 +0,0 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
#include "AssetRegistryModule.h"
#include "ObjectTools.h"
#include "PackageTools.h"
#include "CCImportUI.h"
#include "Editor/UnrealEd/Classes/Factories/FbxFactory.h"
#include "Editor/UnrealEd/Public/Editor.h"
#include "Runtime/Engine/Classes/Engine/Selection.h"
#include "Runtime/Engine/Classes/Materials/MaterialInstanceConstant.h"
#include "Runtime/Engine/Classes/Engine/SkeletalMesh.h"
#include "Runtime/JSon/Public/Dom/JsonObject.h"
#include "RLTextureData.h"
#include "RLMaterialData.h"
#include "RLPhysicCollisionShapeData.h"
#include "Runtime/Engine/Classes/Animation/Rig.h"
#include "Runtime/Launch/Resources/Version.h"
#include <functional>
class FToolBarBuilder;
class FMenuBuilder;
class UClothingAssetCommon;
class UClothLODDataBase;
class CMaterialType
{
public:
CMaterialType( FString strMaterialName, FString strBoneType = "" );
FString GetType() { return m_strMaterialType; }
float GetTilingValue() { return m_fTilingValue; }
private:
FString m_strMaterialType;
float m_fTilingValue = 0.0f;
};
enum class EShaderType
{
Teeth,
Scalp,
Eyelash,
Eye,
Tearline,
Occulsion,
Head,
Skin,
Hair,
GeneralSSS,
PBR,
TRA,
};
class FRLPluginModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
/** This function will be bound to Command. */
void PluginButtonClicked();
void AutoSetup( TArray<FAssetData>& kAssetDatas,
FString strShaderType,
TArray<FString>& kLODPathList,
bool bIsDragFbx );
bool CheckAutoSetupVersionPass( FString strJsonFilePath );
private:
void AddToolbarExtension( FToolBarBuilder& kBuilder );
void AddMenuExtension( FMenuBuilder& kBuilder );
void CheckWorldGridMaterial(FString &strFbxName, FString &rootGamePath, FString ccMaterialFolderGamePath, UStaticMesh *pMesh, bool isMaterialInstance);
bool CheckShaderTypeChange(FString &strfbxName, FString shaderType, USkeletalMesh *mesh, UMaterial* material, UMaterialInterface* MaterialInterface, RLMaterialData* pMaterialData, int slotID, FString &rootGamePath, bool isMaterialInstance, FString strBoneType );
void DeleteTextureFile( const FString& strDeleteFloderPath, const FString& strCheckFolderPath );
void ShowInfo( const FString& strMessage, const float& fExpireDuration );
FString GetBoneType( const FAssetData& kAssetData );
USkeleton* GetAssetSkeleton( const FAssetData& kAssetData );
bool CreateFolder( FString &path );
void CreateTexturesPathList( const FString &strRootGamePath, TArray <FString> &kTexturesPathList );
void RemoveInvalidTexture( TMap< FString, RLMaterialData >& kMaterialMap, const FString& strTexturePath, const FString& strFbmTexturePath, TArray< FString >& kTexturesPathList );
bool CheckTextureShouldImport( const FString& strFilePath, bool bPbr );
#if ENGINE_MAJOR_VERSION <= 4 && ENGINE_MINOR_VERSION == 24
bool RLPluginImportToLodInternal( USkeletalMesh* SourceMesh, int32 SourceLodIndex, int32 SourceSectionIndex, UClothingAssetCommon* DestAsset, UClothLODDataBase* DestLod, UClothLODDataBase* InParameterRemapSource );
#endif
FString GetMaterialPackagePath( const FString& strRootGamePath, const FString& strMaterialName, const FString& strFbxName, bool bIsMaterialInstance );
void ReplaceMaterial( UMaterialInterface* pMaterialInterface, const FString &strPackagePath, std::function< void( UMaterialInterface* ) > fnReplaceMaterial );
void DeleteUnrealMaterial( const FString &strSourceFolderPath, const FString &strTargetFolderPath, const FString &strFbxName, const FString &strRootGamePath, bool bIsMaterialInstance, std::function< void() > fnReplaceMeshMaterial );
void DeleteDefaultSkeletalMaterial( const FString &strSourceFolderPath, const FString &strTargetFolderPath, const FString &strFbxName, const FString &strRootGamePath, USkeletalMesh *pMesh, bool bIsMaterialInstance );
void DeleteDefaultStaticMaterial( const FString &strSourceFolderPath, const FString &strTargetFolderPath, const FString &strFbxName, const FString &strRootGamePath, UStaticMesh *pMesh, bool bIsMaterialInstance );
void MoveTextureFile( FString& strTargetFolderPath );
void findLODGroupMaterialJson(TMap< FString, RLMaterialData > &kMaterialMap, FString &strFbxName, FString &strRootGamePath, USkeletalMesh *kMesh, bool bIsMaterialInstance);
void findLODGroupMaterial(FString &rootGamePath, USkeletalMesh *mesh );
void SetOrmTextureSetting( UMaterialInstanceConstant* pMaterialInstance, const FString& strTexturePath, const bool bSkin = false );
void ProcessMaterialInstanceConstant( UMaterialInstanceConstant*& pMaterialInstance, UMaterial* pMaterial, UMaterialInterface* pMeshMaterialInterface, UMaterialInterface* pParentInterface, const FString& strCCMaterialFolderPath, std::function< void( UMaterialInstanceConstant* ) > fnMaterialSetting );
void AssignMaterialInstanceJson( UMaterialInstanceConstant*& pInstUMaterialInterface,
const FString& strMaterialName,
RLMaterialData* pMaterialData,
TArray <FString> & texturesPathList,
UMaterial* material,
UMaterialInterface* MaterialInterface,
FString texturesFilesGamePath,
FString texturesFilesGamePathFbm,
FString ccMaterialFolderGamePath,
const FString& strSubsurfaceProfilePath,
FString boneType,
FString shaderType );
void AssignGeneralSss( RLMaterialData* pMaterialData, TArray<FString> &kTexturesPathList, FString strTexturesFilesGamePathFbm, const FString& strMaterialName, FString texturesFilesGamePath, bool bIsHQSkin, const FString& strSubsurfaceProfilePath, FString strTexturePathToLoad, UMaterialInstanceConstant*& pInstUMaterialInterface, UMaterial* pMaterial, UMaterialInterface* pMaterialInterface, FString strCCMaterialFolderGamePath );
void PhysicIniPaser( FString iniPath );
FString GetTexturePath( RLMaterialData *pMaterialData, const FString& strKey, const FString& strTexturesFolderPath, const FString& strMaterialName );
void SetTextureParameter( RLMaterialData *pMaterialData, const FString& strKey, UMaterialInstanceConstant* pMaterialInstance );
void UpdateStaticParameter( UMaterialInstanceConstant* pMaterialInstance, const FString& strParameter, bool bEnable, bool bMarkChanged );
void SetMultiUvIndex( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance );
void SetBaseColor( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePathsFbm[2], FString strMaterialName );
void SetNormal( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePathsFbm[2], FString strMaterialName );
void SetSpecular( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePathsFbm[2], FString strMaterialName, bool bIsPBR );
void SetOpacity( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePathsFbm[2], FString strMaterialName );
void SetGlow( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePaths[2], FString strMaterialName );
void SetBlend( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString kTexturesFilesGamePaths[2], FString strMaterialName );
void SetBlendToHairDepthMap( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString kTexturesFilesGamePaths[2], FString strMaterialName );
void SetDisplacement( RLMaterialData* pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePaths[2], FString strMaterialName );
void SetAO( RLMaterialData *pMaterialData, UMaterialInstanceConstant* pMaterialInstance, TArray<FString> kTexturesPathList, FString strTexturesFilesGamePaths[2], FString strMaterialName );
void SetRoughness( RLMaterialData *kMaterialData, UMaterialInstanceConstant* kMaterialInstance, TArray<FString> texturesPathList, FString texturesFilesGamePaths[2], FString materialName, bool isPBR );
void SetMetallic( RLMaterialData *kMaterialData, UMaterialInstanceConstant* kMaterialInstance, TArray<FString> texturesPathList, FString texturesFilesGamePaths[2], FString materialName, bool isPBR );
void CreateCollisionShape(FName strBoneName, FVector kBoundMin, FVector kBoundMax, FVector kScale, FVector kOffset, UBodySetup* pBodySetup, int nShapeType, int nBoundAxis);
void CreateCollisionShapeFromData( RLPhysicsCollisionShapeData* pCollisionShapeData, UBodySetup* pBodySetup, const FTransform* kBoneParentWorldTransform );
void CreateConstraint(FName strBoneName, int nBoneID, USkeletalMesh* pMesh, UPhysicsAsset* pPhysicsAsset);
static bool SetShaderTextureSrgbCompression( UTexture* pTexture, FString strName );
void SetShaderData( RLShaderData* pShaderData, UMaterialInstanceConstant* pMaterialInstance, const FString& strFolder );
void SetScatter( const RLScatter* pScatter, UMaterialInstanceConstant* pMaterialInstance, const FString& strMaterialName, FString strSubsurfaceProfilePath, EShaderType eShaderType );
void GetShaderRenameMap( FString strMaterialName, EShaderType eType, RLShaderData* pShaderData, ENodeType eNodeType, TMap< FString, FString >& kRenameMap );
void ParseJson( const FString& strJsonFilePath, FString& strGeneration, FString& strBoneType, bool& bSupportShaderSelect, TMap< FString, RLMaterialData >& kMaterialMap, TMap< FString, TArray<RLPhysicsCollisionShapeData> >& kCollisionShapeMap );
void ParseJsonShaderData( TSharedPtr< RLMaterialData > spMaterialData, TSharedPtr< FJsonObject > spJsonObject, FString strMaterialName, FString strBoneType );
void ParseJsonScatterData( TSharedPtr< RLMaterialData > spMaterialData, TSharedPtr< FJsonObject > spJsonObject );
void ParseJsonPhysicsData( TSharedPtr<FJsonObject> spPhysicsRoot, TMap< FString, RLMaterialData >& kMaterialMap, TMap< FString, TArray<RLPhysicsCollisionShapeData> >& kCollisionShapeMap, bool bIsCCStdBoneAxis );
void ConvertEyeMaterialName( FString& strMaterialName );
UObject* RLCreatePhysicsAsset( FName InAssetName, UObject* InParent, USkeletalMesh* SkelMesh );
FString GetMaterialTypeByName( FString strName );
EShaderType GetShaderType( RLMaterialData* pMaterialData, FString strMaterialName, FString strBoneType );
EShaderType GetPbrShaderType( const RLShaderData* pShaderData, FString strMaterialName, FString strBoneType );
void UpdateWorld( int32 BoneIndex, FTransform ParentWorld, USkeleton* pSkeleton, const TArray<FTransform>& kBoneTransform, TArray<FTransform>& kBoneWorld );
void CreatePhysicCollisionShape( UPhysicsAsset* pPhysicsAsset, USkeletalMesh* pMesh, USkeleton* pSkeleton, const TMap< FString, TArray<RLPhysicsCollisionShapeData> >& kCollisionShapeMap );
void CreatePhysicSoftCloth( UPhysicsAsset* pPhysicsAsset, USkeletalMesh* pMesh, TMap< FString, RLMaterialData >& kMaterialMap );
TSharedPtr< class FUICommandList > m_kPluginCommands;
static URig* m_pEngineHumanoidRig;
bool m_bIsMaterialInstance = true;
//FString const MATERIAL_FLODER_NAME = "RL_Materials";
};
@@ -1,26 +0,0 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Framework/Commands/Commands.h"
#include "RLPluginStyle.h"
class FRLPluginCommands : public TCommands<FRLPluginCommands>
{
public:
FRLPluginCommands()
: TCommands<FRLPluginCommands>( TEXT( "RLPlugin" ),
NSLOCTEXT( "Contexts", "RLPlugin", "RLPlugin Plugin" ),
NAME_None,
FRLPluginStyle::GetStyleSetName() )
{
}
// TCommands<> interface
virtual void RegisterCommands() override;
public:
TSharedPtr< FUICommandInfo > PluginAction;
};
@@ -1,31 +0,0 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Styling/SlateStyle.h"
class FRLPluginStyle
{
public:
static void Initialize();
static void Shutdown();
/** reloads textures used by slate renderer */
static void ReloadTextures();
/** @return The Slate style set for the Shooter game */
static const ISlateStyle& Get();
static FName GetStyleSetName();
private:
static TSharedRef< class FSlateStyleSet > Create();
private:
static TSharedPtr< class FSlateStyleSet > StyleInstance;
};
@@ -1,20 +0,0 @@
#pragma once
#include "CoreMinimal.h"
class RLTextureData
{
public:
RLTextureData() {}
~RLTextureData() {}
FString m_strTexturePath = "";
bool m_bShareImage = false;
float m_fStrength = 100.f;
TArray< float > m_kOffset = { 0.f, 0.f };
TArray< float > m_kTiling = { 1.f, 1.f };
float m_fTessellationLevel = 0.f;
float m_fTessellationMulitiplier = 0.f;
float m_fGrayScaleBaseValue = 0.f;
FString m_strDisplacementMapType = "";
FString m_strBlendMode = "Multiply";
};
@@ -1,85 +0,0 @@
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class RLPlugin : ModuleRules
{
public RLPlugin(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
bUsePrecompiled = true;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"Projects",
"InputCore",
"UnrealEd",
"LevelEditor",
"CoreUObject",
"RenderCore",
"Engine",
"Slate",
"SlateCore",
"ContentBrowser",
"DesktopPlatform",
"MaterialEditor",
"ImageWrapper",
"EditorStyle",
"RawMesh",
"ClothingSystemEditorInterface",
"SkeletalMeshEditor",
"Json",
"JsonUtilities",
}
);
if( Target.Version.MajorVersion == 4 && Target.Version.MinorVersion <= 23 )
{
PrivateDependencyModuleNames.AddRange(
new string[]
{
"ClothingSystemRuntime"
} );
}
if( Target.Version.MajorVersion == 4 && Target.Version.MinorVersion >= 24 )
{
PrivateDependencyModuleNames.AddRange(
new string[]
{
"ClothingSystemEditor",
"ClothingSystemRuntimeCommon",
"SkeletalMeshUtilitiesCommon",
"ClothingSystemRuntimeInterface",
"ClothingSystemRuntimeNv"
} );
}
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
-3
View File
@@ -8,8 +8,5 @@
; /Binaries/ThirdParty/*.dll
/*.md
/*.pdf
/Config/...
/Images/...
Binary file not shown.
+12 -12
View File
@@ -1,8 +1,8 @@
{
"FileVersion": 3,
"Version": 10,
"VersionName": "2.3.3",
"FriendlyName": "NVIDIA DLSS",
"Version": 30,
"VersionName": "2.4.0b",
"FriendlyName": "NVIDIA DLSS/DLAA",
"Description": "NVIDIA Deep Learning Super Sampling",
"Category": "Rendering",
"CreatedBy": "NVIDIA",
@@ -10,7 +10,7 @@
"DocsURL": "",
"MarketplaceURL": "https://www.unrealengine.com/marketplace/en-US/product/nvidia-dlss",
"SupportURL": "mailto:DLSS-Support@nvidia.com",
"EngineVersion": "4.27.0",
"EngineVersion": "5.1.0",
"CanContainContent": true,
"Installed": true,
"Modules": [
@@ -18,7 +18,7 @@
"Name": "DLSSUtility",
"Type": "Runtime",
"LoadingPhase": "PostConfigInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -26,7 +26,7 @@
"Name": "DLSS",
"Type": "Runtime",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -39,7 +39,7 @@
"Name": "NGXRHI",
"Type": "Runtime",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -47,7 +47,7 @@
"Name": "NGXD3D11RHI",
"Type": "Runtime",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -55,7 +55,7 @@
"Name": "NGXD3D12RHI",
"Type": "Runtime",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -63,7 +63,7 @@
"Name": "NGXVulkanRHIPreInit",
"Type": "Runtime",
"LoadingPhase": "PostConfigInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -71,7 +71,7 @@
"Name": "NGXVulkanRHI",
"Type": "Runtime",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
},
@@ -79,7 +79,7 @@
"Name": "DLSSEditor",
"Type": "Editor",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [
"PlatformAllowList": [
"Win64"
]
}
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 762 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

-439
View File
@@ -1,439 +0,0 @@
![NVIDIA Logo](Images/nv-logo.png)
NVIDIA Unreal Engine DLSS/DLAA Plugin
=====================================
The NVIDIA *DLSS/DLAA* plugin is part of a wider suite of related NVIDIA performance and image quality improving technologies and corresponding NVIDIA Unreal Engine plugins:
- NVIDIA *Deep Learning Supersampling (DLSS)* is used to provide the highest possible frame rates at maximum graphics settings. *DLSS* requires an NVIDIA RTX graphics card.
- NVIDIA *Deep Learning Anti-Aliasing (DLAA)* is used to improve image quality. *DLAA* requires an NVIDIA RTX graphics card.
- NVIDIA *Image Scaling (NIS)* provides best-in class upscaling and sharpening for non-RTX GPUs, both NVIDIA or 3rd party. Please refer to the NVIDIA *Image Scaling* Unreal Engine plugin for further details.
# Quickstart
Please refer to the relevant section in this document for additional details.
1. Enable the *DLSS* plugin in the Editor, then restart the editor
2. DLSS in the Editor: enable the following settings in the Project Plugin settings
1. Enable DLSS to be turned on in Editor viewports (it should be set by default)
2. In the Viewport Options (downwards pointing arrow in the top left corner), use the DLSS Settings menu to toggle the different DLSS quality modes
3. DLSS/DLAA in [Blueprint](#dlss-blueprints):
The `SetDLSSMode` and `EnableDLAA` functions of the DLSS blueprint library provide convenient functions for setting those console variables and are recommended to be used when integrating support into a project's user interface and settings.
4. DLSS in Game: make sure that the following [console variables](#command-line-options-and-console-variables-and-commands) are set to enable DLSS:
1. r.NGX.Enable 1 (can be overriden on the command line with -ngxenable)
2. r.NGX.DLSS.Enable 1
3. r.NGX.DLSS.Quality -1
4. r.NGX.DLSS.Quality.Auto false
5. r.NGX.DLAA.Enable 0
5. DLAA in Game: make sure that the following [console variables](#command-line-options-and-console-variables-and-commands) are set to enable DLAA
1. r.NGX.Enable 1 (can be overriden on the command line with -ngxenable)
2. r.NGX.DLAA.Enable 1
6. Check the log for `LogDLSS: NVIDIA NGX DLSS supported 1`
7. (Optionally) Enable the DLSS on screen indicator in the bottom left of the screen via `\DLSS\Source\ThirdParty\NGX\Utils\ngx_driver_onscreenindicator.reg` to verify that DLSS is active
# Troubleshooting
## System requirements
- Windows 10, 64 bit
- at least version v1709, Windows 10 Fall 2017 Creators Update 64-bit.
- NVIDIA Geforce Driver
- Recommended: version 461.40 or higher
- Required: version 445.00 or higher
- NVIDIA RTX GPU (GeForce, Titan or Quadro) with [DLSS](https://www.nvidia.com/en-us/geforce/technologies/dlss/) support
- UE project using either
- Vulkan
- DX11
- DX12
## Diagnosing DLSS Issues in the Editor
The DLSS plugin shows various common reasons why DLSS might not be working at the top of the screen (in non-Shipping build configurations). This message can also be turned off in the DLSS plugin settings, as discussed in the "DLSS Plugin Settings" section in this document.
![DLSS Editor Developer messages](Images/DLSSDeveloperMessages.png)
Additionally, the DLSS plugin modules write various information into the following UE log categories:
* LogDLSS
* LogDLSSEditor
* LogDLSSBlueprint
* LogDLSSNGXRHI
* LogDLSSNGXD3D11RHI
* LogDLSSNGXD3D12RHI
* LogDLSSNGXVulkanRHIPreInit
* LogDLSSNGXVulkanRHI
* LogDLSSNGX
Those can be accessed in the Editor under `Window -> Developer Tools -> Message Log`
![DLSS Editor Output log menu](Images/DLSSOutputLogMenu.png)
The Message log then can be filtered to show only the DLSS related messages to get more information on why DLSS might not be functioning as expected, as shown in those examples.
![DLSS Editor Output log disabled](Images/DLSSOutputLogNotWorking.png)
![DLSS Editor Output log driver out of date](Images/DLSSOutputLogNotWorkingDriverOutOfDate.png)
## Incompatibilities with API Capture Tools such as RenderDoc
The Editor will show a warning at startup if DLSS incompatible API capture tools (such as RenderDoc) or plugins are used. To enable DLSS, please use an API capture tool such as [NVIDIA NSIGHT Graphics](https://developer.nvidia.com/nsight-graphics), which support the NGX APIs required by DLSS.
![DLSS Editor incompatible tools and plugins](Images/DLSSIncompatibleCaptureToolsPlugins.png)
## Incompatibilities with Screenpercentage override in Post Procssing Volumes
When DLSS is active, the DLSS quality mode determines the effective screen percentage. As such screen percentage overrides specified in postprocessing volumes are ignored. This can lead to unexpected performance behavior when DLSS is turned on, compared to when DLSS is turned off.
## Incompatibilities with Depth of Field
As DLSS workload occurs in the same spot as TAAU in the pipeline, visual differences in DoF are expected.
To minimize the differences, it is recommended to use DLSS in 'Quality' or 'Ultra Quality' modes.
It is possible to tweak the DoF settings in the camera actor to compensate for the differences.
Please keep in mind this is content dependent. Thus for some scenes the differences can be minimal and avoided while in other cases it might be more challenging.
## Verify Engine side plugin hooks
The following cvars should be set to those values by default:
- r.DefaultFeature.Antialiasing 2
- r.TemporalAA.Upscaler 1
- r.Reflections.Denoiser 2
## Enabling NGX DLSS Logging on End User machines
The DLSS plugin also pipes the NGX DLSS logs into the UE logging system into the `LogDLSSNGX` log category. It is enabled by default and can be tweaked with the `r.NGX.LogLevel` console variable, or set with the -NGXLogLevel=X command line option.
This requires an NVIDIA GeForce **driver version 461.36** or later.
## Enabling NGX DLSS Logging during Development
If r.NGX.EnableOtherLoggingSinks is set then additional NGX logging of the NVIDIA NGX software stack to files can be used as well, as discussed in the "NGX logging" chapter of the [DLSS Programming Guide](DLSS_Programming_Guide_Release.pdf) for details. The -NGXLogFileEnable and -NGXLogFileDisable command line options can also override the default setting.
The DLSS SDK provides registry keys which can be set with the following .reg files which can be found in the plugin folder under `\DLSS\Source\ThirdParty\NGX\Utils\`:
* `ngx_log_on.reg`
* `ngx_log_off.reg`
* `ngx_log_verbose.reg`
The DLSS plugin will write those into subfolder under `$(ProjectDir)\Saved\Logs\` with a `NGX_$(TimeStamp)_$(GUID)` pattern
* `nvngx.log`
* `nvngx_dlss_2_1_34.log`
* `nvsdk_ngx.log`
## DLSS On-Screen Indicator
The DLSS SDK provides registry keys which can be set with the following .reg files which can be found in the plugin folder under `\DLSS\Source\ThirdParty\NGX\Utils\`:
* `ngx_driver_onscreenindicator.reg`
* `ngx_driver_off_screenindicator.reg`
With the first registry key set, DLSS will display an indicator on-screen when it is enabled, enabling easier troubleshooting. The second registry key can be used to disable this indicator again.
Please see the [DLSS Programming Guide](DLSS_Programming_Guide_Release.pdf) for further details.
# Command Line Options And Console Variables and Commands
## Enabling DLSS (Engine Side)
The DLSS plugin uses various engine side hooks, which can be configured by the following cvars. Their default values
- r.DefaultFeature.Antialiasing (2, default)
- Enable Temporal Anti-Aliasing
- r.TemporalAA.Upscaler (1, default)
- Enable a custom TAAU upscaling plugin, such as the DLSS plugin
- r.Reflections.Denoiser (2, default)
- Enable a custom denoising plugin. The DLSS plugin makes use of this to improve image quality for raytraced reflections by adding additionial TAA passes
## Enabling Motion vectors for DLSS
DLSS requires correct motion vectors to function properly. The following console variable can be used to render motion vectors for all objects, and not just the ones with dynamic geometry. This can be useful if it's infeasible to e.g. change all meshes to stationary or dynamic.
- r.BasePassForceOutputsVelocity (0, default)
- Force the base pass to compute motion vector, regardless of FPrimitiveUniformShaderParameters.
- 0: Disabled
- 1: Enabled
## Enabling DLSS/DLAA (Plugin Side)
- r.NGX.Enable (1, default) can also be overriden on the command line with **-ngxenable** and **-ngxdisable**
- Whether the NGX library should be loaded. This allow to have the DLSS plugin enabled but avoiding potential incompatibilities by skipping the driver side NGX parts of DLSS.
- r.NGX.DLSS.Enable (1, default)
- Enable/Disable DLSS entirely.
- r.NGX.DLSS.Quality (-1, default)
- DLSS Performance/Quality setting. **Note:** Not all modes might be supported at runtime, in this case Balanced mode is used
- -2: Ultra Performance
- -1: Performance (default)
- 0: Balanced
- 1: Quality
- 2: Ultra Quality
- r.NGX.DLSS.Quality.Auto (false, default)
- Whether the DLSS quality mode should be chosen dynamically based on viewport size. Overrides r.NGX.DLSS.Quality
- r.NGX.DLAA.Enable (false, default)
- Enable/Disable DLAA. DLSS will be disabled while DLAA is enabled
**Blueprint** functions:
- `SetDLSSMode`, `GetDLSSMode`
- `IsDLSSSupported`, `QueryDLSSSupport`, `GetDLSSMinimumDriverVersion`, `GetDefaultDLSSMode`
- `IsDLSSModeSupported`, `GetSupportedDLSSModes`,`GetDLSSModeInformation`, `GetDLSSScreenPercentageRange`
- `EnableDLAA`, `IsDLAAEnabled`
## DLSS Runtime Image Quality Tweaks
- r.NGX.DLSS.DilateMotionVectors (1, default)
- 0: pass low resolution motion vectors into DLSS
- 1: pass dilated high resolution motion vectors into DLSS. This can help with improving image quality of thin details.
- r.NGX.DLSS.Reflections.TemporalAA (1, default)
- Apply a temporal AA pass on the denoised reflections
- r.NGX.DLSS.WaterReflections.TemporalAA (1, default)
- Apply a temporal AA pass on the denoised water reflections
- r.NGX.DLSS.Sharpness (0.0f off, default)
- -1.0 to 1.0: Softening/sharpening to apply to the DLSS pass. Negative values soften the image, positive values sharpen.
- r.NGX.DLSS.EnableAutoExposure
- 0: Use the engine-computed exposure value for input images to DLSS
- 1: Enable DLSS internal auto-exposure instead of the application provided one - enabling this can alleviate effects such as ghosting in darker scenes (default)
- r.NGX.DLSS.PreferNISSharpen (2,default)
- Prefer sharpening with an extra NIS plugin sharpening pass instead of DLSS sharpening if the NIS plugin is also enabled for the project.
- Requires UE4.27.1 and the NIS plugin to be enabled, DLSS sharpening will be used otherwise.
- 0: Softening/sharpening with the DLSS pass.
- 1: Sharpen with the NIS plugin. Softening is not supported. Requires the NIS plugin to be enabled.
- 2: Sharpen with the NIS plugin. Softening (i.e. negative sharpness) with the DLSS plugin . Requires the NIS plugin to be enabled.
**Note** This cvar is only evaluated when using the `SetDLSSSharpness` Blueprint function, from either C++ or a Blueprint event graph!
**Blueprint** functions:
- `SetDLSSSharpness`, `GetDLSSSharpness`
## DLSS Binaries
- r.NGX.BinarySearchOrder (0, default)
- 0: automatic
- use custom binaries from project and launch folder $(ProjectDir)/Binaries/ThirdParty/NVIDIA/NGX/$(Platform) if present
- fallback to generic binaries from plugin folder
- 1: force generic binaries from plugin folder, fail if not found
- 2: force custom binaries from project or launch folder, fail if not found
- 3: force generic development binaries from plugin folder, fail if not found. This is only supported in non-shipping build configurations
## DLSS memory usage
- `stat DLSS`
- shows how much GPU memory DLSS uses and how many DLSS features, i.e. instances of DLSS are allocated.
- In steady state there should be 1 DLSS feature allocated per view. This value can increase temporarily, typically after changing the DLSS quality mode or resizing the window. This can be configured with the `r.NGX.FramesUntilFeatureDestruction` console variable
## NGX Project ID
The DLSS plugin by default uses the project identifier to initialize NGX and DLSS. On rare occasion, NVIDIA might provide a special NVIDIA NGX application ID. The following console variable determines which one is used.
r.NGX.ProjectIdentifier (0, default)
- 0: automatic:
- use NVIDIA NGX Application ID if non-zero, otherwise use UE Project ID
- 1: force UE Project ID
- 2: force NVIDIA NGX Application ID (set via the Project Settings -> NVIDIA DLSS plugin)
Please refer to the "Distributing DLSS" section for further details.
## Multi GPU Support (Experimental)
The DLSS plugin supports multiple GPUs in certain circumstances, as shown in the following table.
There AFR stands for Alternate-Frame-Rendering, i.e. SLI or CrossFire, and SFR stands for Split-Frame-Rendering, which is what the nDisplay plugin uses.
| RHI | AFR | SFR|
| --- | --- | --- |
| D3D12RHI | no | conditionally|
| D3D11RHI| yes| no|
| VulkanRHI| no | no|
Notes:
- D3D12RHI
- AFR is not supported
- Primarily due to higher level renderer code not maintaining TAA (and thus DLSS) history across non-consecutive frames on the same GPU
- SFR is conditionally supported
- Support requires a custom nDisplay plugin to enable calling into the DLSS plugin
- Please refer to the [NvRTX](https://github.com/NvRTX/UnrealEngine) GitHub repository
- GPUs are expected to be in Linked Display Adapter (LDA) mode
- **This will not work with unmodified engine distributions, such as those from the Epic Games Launcher**
- D3D11RHI
- AFR is supported via driver based, automatic SLI support
- VulkanRHI
- The VulkanRHI (as of UE 4.27) does not implement explicit MGPU, and thus neither AFR nor SFR are available
The following console variables can be used to adjust how DLSS interacts with the GPU nodes
- r.NGX.DLSS.FeatureCreationNode (-1, default)
- Determines which GPU the DLSS feature is getting created on
- -1: Create on the GPU the command list is getting executed on
- 0: Create on GPU node 0
- 1: Create on GPU node 1
- r.NGX.DLSS.FeatureVisibilityMask (-1, default)
- Determines which GPU the DLSS feature is visible to
- -1: Visible to the GPU the command list is getting executed on
- 1: visible to GPU node 0
- 2: visible to GPU node 1
- 3: visible to GPU node 0 and GPU node 1
## Miscellaneous
- r.NGX.DLSS.AutomationTesting (0, default)
- Whether the NGX library should be loaded when GIsAutomationTesting is true.(default is false)
- Must be set to true before startup. This can be enabled for cases where running automation testing with DLSS is desired
- r.NGX.Automation.Enable (0, default)
- Enable automation for NGX DLSS image quality and performance evaluation.
- r.NGX.Automation.ViewIndex (0, default)
- Select which view to use with NGX DLSS image quality and performance automation.
- r.NGX.Automation.NonGameViews (0,default)
- Enable non-game views for NGX DLSS image quality and performance automation.
- r.NGX.FramesUntilFeatureDestruction (3, default)
- Number of frames until an unused NGX feature gets destroyed
- r.NGX.DLSS.MinimumWindowsBuildVersion (16299, default for v1709)
- Sets the minimum Windows 10 build version required to enable DLSS
- r.NGX.LogLevel (1, default)
- Determines the minimal amount of logging the NGX implementation. Please refer to the DLSS plugin documentation on other ways to change the logging level.
- 0: off
- 1: on
- 2: verbose
- r.NGX.EnableOtherLoggingSinks (0, default)
- Determines whether the NGX implementation will turn on additional log sinks LogDLSSNGXRHI
- 0: off
- 1: on
- r.NGX.RenameNGXLogSeverities (1, default)
- Renames 'error' and 'warning' in messages returned by the NGX log callback to 'e_rror' and 'w_arning' before passing them to the UE log system
- 0: off
- 1: on, for select messages during initalization
- 2: on, for all messages
- r.NGX.DLSS.ReleaseMemoryOnDelete (1, default)
- Enable/disable releasing DLSS related memory on the NGX side when DLSS features get released
# DLSS and the NIS NVIDIA Image Scaling plugin (UE 4.27.1+)
The *DLSS* plugin and NVIDIA Image Scaling (*NIS*) plugins can be enabled together for the same project. Please see the `RTX UI Developer Guidelines` document for suggested UI implementations.
When both the *DLSS* and *NIS* plugins are enabled for a project, NIS will be used instead of DLSS sharpening. See `r.NGX.DLSS.PreferNISSharpen` for details.
# DLSS in the Editor
## Enabling DLSS for a project
![DLSS Plugin](Images/DLSSPlugin.png)
## Enabling DLSS in Level Editor Viewports
With "Enable DLSS to be turned on in Editor viewports" set in the project plugin settings, (on by default), the DLSS mode can be turned on in level editor viewports like this. Each viewport can have a different DLSS mode.
![DLSS Viewport On](Images/DLSSViewportSettingsDLSSOn.png)
## DLSS Plugin Settings
Some of the "Level Editor - Viewport" settings are split across two config files and settings pages to tailor how DLSS is interacting with the editor user experience.
For example, a cross-platform game project might find it more practical by default to only have DLSS enabled in "Play In Editor Viewports" or in "game mode" in order to maintain a consistent content authoring experience across the range of supported platforms.
However projects (e.g. an architecture visualization project with notable raytracing workloads), might find it more useful to have DLSS enabled during the content authoring. Either way each user can override those settings locally:
- `Project Settings -> Plugins -> NVIDIA DLSS`
- stored in DefaultEngine.ini
- typically resides in source control.
- settings here are shared between users
- `Project Settings -> Plugins -> NVIDIA DLSS (Local)`
- stored UserEngine.ini
- not recommended to be checked into source control.
- allow a user to override project wide settings if desired. Defaults to "use project settings"
![DLSS plugin project settings](Images/DLSSPluginProjectSettings.png)
![DLSS plugin local project settings](Images/DLSSPluginProjectSettingsLocal.png)
## DLSS Blueprints
The UDLSSLibrary blueprint library provides functionality to query whether DLSS and which modes are supported. It also provides convenient functions to enable the underlying DLSS console variables. The tooltips of each function provide additional information.
Using the UDLSSLibrary via blueprint or C++ (by including the DLSSBlueprint module in a game project) is recommended over setting the console variables directly. This will make sure that any future updates will be picked up by simply updating the DLSS plugin, without having to update the game logic.
![DLSS Blueprint library](Images/DLSSBlueprintLibrary.png)
## DLSS Movie Render Queue Support (UE 4.27)
Starting with UE4.27 DLSS supports the DLSS when rendering movies with the Movie Render Queue plugin.
0. Enable the *Movie Render Queue* and *DLSS* plugins in the Editor
1. Enable the *Movie Render Queue DLSS Support* plugin in the Editor, then restart the editor
2. In the configuration, add the `Settings -> DLSS` page
3. In the DLSS settings page, change the desired DLSS quality mode
1. Note: Unsupported DLSS modes will show a warning at the bottom of the window
4. Optional: The `Settings -> Output -> File Name Format` page supports a `{dlss_quality}` format tag
**Note:** Only the *Deferred Rendering* render pass is supported with DLSS, all other passes use the built-in TAA
![DLSS Movie Scene Support Plugin](Images/DLSSMoviePipelineSupportPlugin.png)
![DLSS Movie Scene Support DLSS Setting](Images/DLSSMoviePipelineSupportDLSSetting.png)
![DLSS Movie Scene Support DLSS Setting Options](Images/DLSSMoviePipelineSupportDLSSOptions.png)
![DLSS Movie Scene Support DLSS Setting Options](Images/DLSSMoviePipelineSupportDLSSFormatFlags.png)
## DLSS nDisplay support (NVRTX only)
**Unmodified engine distributions, such as those from the Epic Games Launcher do not support DLSS with the nDisplay plugin.**
The [NvRTX](https://github.com/NvRTX/UnrealEngine) GitHub repository hosts a modified version of the nDisplay plugin that has those changes to the nDisplay plugin:
At the top of `\Engine\Plugins\Runtime\nDisplay\Source\DisplayCluster\Private\Game\EngineClasses\Basics\DisplayClusterViewportClient.cpp`, right after the existing header includes around line 50, add this block:
```
#include "CustomStaticScreenPercentage.h"
static TAutoConsoleVariable<int32> CVarAllowTemporalUpsampling(
TEXT("nDisplay.render.TemporalUpsampling"),
1,
TEXT("Allow custom upscaler plugins when rendering with nDisplay"),
ECVF_Default
);
```
And in `UDisplayClusterViewportClient::Draw`, around line 510, add this before the block that checks whether the view family has a screenpercentage interface set or not:
```
if (CVarAllowTemporalUpsampling.GetValueOnGameThread() && GCustomStaticScreenPercentage && ViewFamily.ViewMode == EViewModeIndex::VMI_Lit)
{
GCustomStaticScreenPercentage->SetupMainGameViewFamily(ViewFamily);
// Regular GameViewport set the primary screenpercentage mode elsewhere
if (ViewFamily.GetTemporalUpscalerInterface())
{
for (FSceneView* View : Views)
{
View->PrimaryScreenPercentageMethod = EPrimaryScreenPercentageMethod::TemporalUpscale;
}
}
}
```
The `nDisplay.render.TemporalUpsampling` console variable then can be used to enable/disable calling into the DLSS plugin.
The usual DLSS blueprint functionality can then be used to configure DLSS.
# Distributing DLSS
The DLSS plugin ships with a ready-to-use production DLSS binary (without watermarks) and uses the project identifier to initialize NGX and DLSS. This is the common case for distribution to end users and does not require further actions from either your or NVIDIA's side.
On rare occasion NVIDIA however might provide:
1. a custom project specific DLSS binary
2. an NVIDIA application ID
In that case those can be configured in the advanced plugin settings. Additionally please also ensure that the r.NGX.ProjectIdentifier console variable is set to either 0 (the default) or 2.
The project plugin settings can be used to configure those (please see above).
1. The custom, project specific DLSS binary `nvngx_dlss.dll` should be put into the project under `$(ProjectDir)/Binaries/ThirdParty/NVIDIA/NGX/$(Platform)`
2. Setting the NVIDIA NGX application ID for the project.
![DLSS Plugin Project Settings](Images/DLSSPluginProjectSettings.png)
Please refer to "Chapter 4 Distributing DLSS in a Game" in the the [DLSS Programming Guide](DLSS_Programming_Guide_Release.pdf) for details.
# DLSS API and UI Documentation
The [DLSS Programming Guide](DLSS_Programming_Guide_Release.pdf) provides details about the NVIDIA NGX APIs which are used by the plugin to implement DLSS.
The [RTX UI Developer Guidelines](RTX UI Developer Guidelines.pdf) ([Chinese](RTX UI Developer Guidelines Chinese Version.pdf)) provides details about recommended game settings and UI for DLSS.
The NVIDIA Developer Blog [Tips: Getting the Most out of the DLSS Unreal Engine 4 Plugin](https://developer.nvidia.com/blog/tips-getting-the-most-out-of-the-dlss-unreal-engine-4-plugin/) provides best practices along with other tips and tricks to use NVIDIA DLSS in Unreal Engine games and applications.
+4 -27
View File
@@ -10,6 +10,7 @@
*/
using UnrealBuildTool;
using System.IO;
public class DLSS : ModuleRules
{
@@ -38,9 +39,10 @@ public class DLSS : ModuleRules
);
// for ITemporalUpscaler in PostProcess/TemporalAA.h
PrivateIncludePaths.AddRange(
new string[] {
EngineDirectory + "/Source/Runtime/Renderer/Private",
Path.Combine(GetModuleDirectory("Renderer"), "Private"),
// ... add other private include paths required here ...
}
);
@@ -72,32 +74,7 @@ public class DLSS : ModuleRules
// ... add private dependencies that you statically link with here ...
}
);
if (ReadOnlyBuildVersion.Current.MajorVersion == 5)
{
PrivateDependencyModuleNames.Add("RHICore");
}
DynamicallyLoadedModuleNames.AddRange(SupportedDynamicallyLoadedNGXRHIModules(Target));
// We can't quite check whether we have CL 16848904 (in UE5-Main) so we do this in a round about way
bool bSupportsPostProcessingScreenPercentage = (Target.Version.MajorVersion == 4) ||
((Target.Version.MajorVersion == 5) && (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess"))
;
PrivateDefinitions.Add(string.Format("SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE={0}", bSupportsPostProcessingScreenPercentage ? "1" : "0"));
// this is a public definition so the DLSSMoviePipelineSupport modules (if compiled against that branch) see it
bool bSupportsCustomStaticScreenpercentageSetupViewFamily = ((Target.Version.MajorVersion == 4) && (Target.Version.MinorVersion >= 27)) || ((Target.Version.MajorVersion == 5) && (Target.Version.BranchName != "++UE5+Release-5.0-EarlyAccess"));
PublicDefinitions.Add(string.Format("DLSS_ENGINE_SUPPORTS_CSSPD={0}", bSupportsCustomStaticScreenpercentageSetupViewFamily ? "1" : "0"));
// We can't quite check whether we have CL 16758229 so we do this in a round about way
bool bEngineHasAAM_TSR = (Target.Version.MajorVersion == 5) && (Target.Version.BranchName != "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("DLSS_ENGINE_HAS_AAM_TSR={0}", bEngineHasAAM_TSR ? "1" : "0"));
// 4.x and early access 5.0 engines had GTemporalUpscaler interface
bool bEngineHasGTemporalUpscaler = (Target.Version.MajorVersion == 4) || (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("DLSS_ENGINE_HAS_GTEMPORALUPSCALER={0}", bEngineHasGTemporalUpscaler ? "1" : "0"));
// 4.x and early access 5.0 engines, ITemporalUpscaler::AddPasses returns values through pointers passed into the function
bool bEngineAddPassesReturnThroughParams = (Target.Version.MajorVersion == 4) || (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess");
PublicDefinitions.Add(string.Format("DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS={0}", bEngineAddPassesReturnThroughParams ? "1" : "0"));
}
}
+37 -90
View File
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
@@ -46,7 +46,7 @@ static TAutoConsoleVariable<int32> CVarNGXEnable(
TEXT("r.NGX.Enable"), 1,
TEXT("Whether the NGX library should be loaded. This allow to have the DLSS plugin enabled but avoiding potential ")
TEXT("incompatibilities by skipping the driver side NGX parts of DLSS. Can also be set on the command line via -ngxenable and -ngxdisable"),
ECVF_Default);
ECVF_ReadOnly);
static TAutoConsoleVariable<int32> CVarNGXDLSSMinimumWindowsBuildVersion(
TEXT("r.NGX.DLSS.MinimumWindowsBuildVersion"), 16299,
@@ -102,8 +102,8 @@ public:
virtual void SetupView(FSceneViewFamily& InViewFamily, FSceneView& InView) {}
virtual void SetupViewPoint(APlayerController* Player, FMinimalViewInfo& InViewInfo) {}
virtual void BeginRenderViewFamily(FSceneViewFamily& InViewFamily) {}
virtual void PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& InView) final {}
virtual void PreRenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneViewFamily& InViewFamily) final
virtual void PreRenderView_RenderThread(FRDGBuilder& GraphBuilder, FSceneView& InView) final {}
virtual void PreRenderViewFamily_RenderThread(FRDGBuilder& GraphBuilder, FSceneViewFamily& InViewFamily) final
{
int32 ViewIndex = CVarNGXAutomationViewIndex.GetValueOnRenderThread();
@@ -117,6 +117,7 @@ public:
View->ViewRotation.Pitch, View->ViewRotation.Roll, View->ViewRotation.Yaw);
static FColor ColorMarker = FColor::FromHex("0xA1A5E87");
FRHICommandListImmediate& RHICmdList = GraphBuilder.RHICmdList;
RHICmdList.PushEvent(*AiAgentMarker, ColorMarker);
RHICmdList.PopEvent();
}
@@ -124,42 +125,18 @@ public:
}
};
static bool IsCompatibleEngineVersion(FString& OutPluginVersion, FString& OutEngineVersion)
{
// Binary incompatibility between 4.26.0 and 4.26.1, so check for the engine patch version at runtime here
// Engine loading code already checks for compatibility for major/minor/changelist
// Written so that no code change will be needed for future engine versions if compatibility isn't broken again
FEngineVersion Version = FEngineVersion::Current();
OutEngineVersion = FString::Printf(TEXT("%u.%u.%u"), Version.GetMajor(), Version.GetMinor(), Version.GetPatch());
OutPluginVersion = FString::Printf(TEXT("%u.%u.%u"), ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION, ENGINE_PATCH_VERSION);
#if ENGINE_MAJOR_VERSION == 4
#if ENGINE_MINOR_VERSION == 26
#if ENGINE_PATCH_VERSION == 0
// 4.26.0
return Version.GetPatch() == 0;
#else
// 4.26.x, x > 0
return Version.GetPatch() >= 1;
#endif
#else
// 4.x._, x > 26
return true;
#endif
#elif ENGINE_MAJOR_VERSION == 5
return true;
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
}
void FDLSSModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
if (!GDynamicRHI)
{
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS requires an RHI"));
DLSSSupport = EDLSSSupport::NotSupported;
return;
}
// Get the base directory of this plugin
const FString PluginBaseDir = IPluginManager::Get().FindPlugin(TEXT("DLSS"))->GetBaseDir();
const FString NGXBinariesDir = FPaths::Combine(*PluginBaseDir, TEXT("Binaries/ThirdParty/Win64/"));
@@ -181,36 +158,7 @@ void FDLSSModule::StartupModule()
const int32 NGXDLSSMinimumWindowsBuildVersion = CVarNGXDLSSMinimumWindowsBuildVersion.GetValueOnAnyThread();
FString PluginVersion;
FString EngineVersion;
if (!IsCompatibleEngineVersion(PluginVersion, EngineVersion))
{
FEngineVersion Version = FEngineVersion::Current();
UE_LOG(LogDLSS, Error,
TEXT("This prebuilt binary distribution version %s of the NVIDIA DLSS plugin is not compatible with the current engine version %s"),
*PluginVersion, *EngineVersion);
UE_LOG(LogDLSS, Error, TEXT("Build the DLSS plugin from source (e.g. via the Editor -> Plugins -> NVIDIA DLSS -> Package)"));
DLSSSupport = EDLSSSupport::NotSupported;
// we don't want this ever show up in packaged builds
#if WITH_EDITOR
const bool IsUnattended = FApp::IsUnattended() || IsRunningCommandlet() || GIsRunningUnattendedScript;
if (!IsUnattended )
{
const FText DialogTitle(LOCTEXT("DLSSIncompatibleEngineVersionTitle", "Error - DLSS plugin incompatible with engine"));
const FTextFormat Format(LOCTEXT("DLSSIncompatibleEngineVersion",
"The binary version {0} of this DLSS Unreal Engine Plugin is not compatible with the binary version {1} of this Unreal Engine installation. \n\n"
"Please build the DLSS plugin from source (e.g. via the Editor -> Plugins -> NVIDIA DLSS -> Package)"));
const FText WarningMessage = FText::Format(Format, FText::FromString(PluginVersion), FText::FromString(EngineVersion));
FMessageDialog::Open(EAppMsgType::Ok,WarningMessage, &DialogTitle);
}
#endif //WITH_EDITOR
}
else if (!IsRHIDeviceNVIDIA())
if (!IsRHIDeviceNVIDIA())
{
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS requires an NVIDIA RTX series graphics card"));
DLSSSupport = EDLSSSupport::NotSupportedIncompatibleHardware;
@@ -234,9 +182,11 @@ void FDLSSModule::StartupModule()
}
else
{
const bool bIsDX12 = (RHIName == TEXT("D3D12")) && GetDefault<UDLSSSettings>()->bEnableDLSSD3D12;
const bool bIsDX11 = (RHIName == TEXT("D3D11")) && GetDefault<UDLSSSettings>()->bEnableDLSSD3D11;
const bool bIsVulkan = (RHIName == TEXT("Vulkan")) && GetDefault<UDLSSSettings>()->bEnableDLSSVulkan;
const ERHIInterfaceType RHIType = RHIGetInterfaceType();
const bool bIsDX12 = (RHIType == ERHIInterfaceType::D3D12) && GetDefault<UDLSSSettings>()->bEnableDLSSD3D12;
const bool bIsDX11 = (RHIType == ERHIInterfaceType::D3D11) && GetDefault<UDLSSSettings>()->bEnableDLSSD3D11;
const bool bIsVulkan = (RHIType == ERHIInterfaceType::Vulkan) && GetDefault<UDLSSSettings>()->bEnableDLSSVulkan;
const TCHAR* NGXRHIModuleName = nullptr;
DLSSSupport = (bIsDX11 || bIsDX12 || bIsVulkan) ? EDLSSSupport::Supported : EDLSSSupport::NotSupported;
@@ -253,7 +203,6 @@ void FDLSSModule::StartupModule()
}
else if (bIsVulkan)
{
// TODO Vulkan (which might need a second, pre RHI init module to route the required vulkan extensions to the VulkanRHI, similar to the HMD stuff
NGXRHIModuleName = TEXT("NGXVulkanRHI");
}
@@ -352,6 +301,8 @@ void FDLSSModule::StartupModule()
}
const FNGXDriverRequirements DriverRequirements = NGXRHIExtensions->GetDLSSDriverRequirements();
MinDriverVersionMajor = DriverRequirements.MinDriverVersionMajor;
MinDriverVersionMinor = DriverRequirements.MinDriverVersionMinor;
if (DriverRequirements.DriverUpdateRequired)
{
if (DLSSSupport == EDLSSSupport::Supported)
@@ -400,13 +351,6 @@ void FDLSSModule::StartupModule()
DLSSUpscaler.Reset();
NGXRHIExtensions.Reset();
}
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
else
{
checkf(GTemporalUpscaler == ITemporalUpscaler::GetDefaultTemporalUpscaler(), TEXT("GTemporalUpscaler is not set to the default upscaler. Please check that only one upscaling plugin is active."));
GTemporalUpscaler = DLSSUpscaler.Get();
}
#endif
}
}
@@ -416,6 +360,11 @@ void FDLSSModule::StartupModule()
if (DLSSSupport == EDLSSSupport::Supported)
{
// set up the view extension for setting up the FDLSSUpscaler on FSceneViewFamily
{
DLSSUpscalerViewExtension = FSceneViewExtensions::NewExtension<FDLSSUpscalerViewExtension>();
}
// set the denoiser
{
@@ -429,12 +378,6 @@ void FDLSSModule::StartupModule()
GScreenSpaceDenoiser = DLSSDenoiser.Get();
UE_LOG(LogDLSS, Log, TEXT("%s wrapping %s"), DLSSDenoiser->GetDebugName(), DLSSDenoiser->GetWrappedDenoiser()->GetDebugName());
}
// set the screen percentage driver for game views
{
checkf(GCustomStaticScreenPercentage == nullptr, TEXT("GCustomStaticScreenPercentage is already in use. Please check that only one upscaling plugin is active."));
GCustomStaticScreenPercentage = DLSSUpscaler.Get();
}
// set the resource pool
{
@@ -462,17 +405,19 @@ void FDLSSModule::ShutdownModule()
if (QueryDLSSSupport() == EDLSSSupport::Supported)
{
// reset the view extension
{
DLSSUpscalerViewExtension = nullptr;
}
// reset the resource pool
if (GCustomResourcePool == DLSSUpscaler.Get())
{
GCustomResourcePool = nullptr;
}
// reset the screen percentage driver for game views
{
GCustomStaticScreenPercentage = nullptr;
}
// reset the denoiser
if (GScreenSpaceDenoiser == DLSSDenoiser.Get())
{
UE_LOG(LogDLSS, Log, TEXT("%s unwrapping %s"), DLSSDenoiser->GetDebugName(), DLSSDenoiser->GetWrappedDenoiser()->GetDebugName());
GScreenSpaceDenoiser = DLSSDenoiser->GetWrappedDenoiser();
@@ -481,9 +426,6 @@ void FDLSSModule::ShutdownModule()
// reset the upscaler
{
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
GTemporalUpscaler = ITemporalUpscaler::GetDefaultTemporalUpscaler();
#endif
FDLSSUpscaler::ReleaseStaticResources();
DLSSUpscaler.Reset();
}
@@ -520,6 +462,11 @@ FDLSSUpscaler* FDLSSModule::GetDLSSUpscaler() const
return DLSSUpscaler.Get();
}
TSharedPtr< ISceneViewExtension, ESPMode::ThreadSafe> FDLSSModule::GetDLSSUpscalerViewExtension() const
{
return StaticCastSharedPtr<ISceneViewExtension>(DLSSUpscalerViewExtension);
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FDLSSModule, DLSS)
@@ -31,15 +31,6 @@ static TAutoConsoleVariable<int32> CVarNGXDLSSWaterReflectionsTemporalAA(
);
// defined in Buid.cs since it depends on the branch and engine version
#if !DLSS_ENGINE_HAS_AAM_TSR
/** Returns whether the anti-aliasing method use a temporal accumulation */
static inline bool IsTemporalAccumulationBasedMethod(EAntiAliasingMethod AntiAliasingMethod)
{
return AntiAliasingMethod == AAM_TemporalAA;
}
#endif
FDLSSDenoiser::FDLSSDenoiser(const IScreenSpaceDenoiser* InWrappedDenoiser, const FDLSSUpscaler* InUpscaler)
: WrappedDenoiser(InWrappedDenoiser)
, Upscaler(InUpscaler)
@@ -54,14 +45,7 @@ const TCHAR* FDLSSDenoiser::GetDebugName() const
{
// we don't have the View here to check whether we have a valid GetTemporalUpscalerInterface, which we'll do when we actually get called to denoise/add TAA
// and this is only for profilegpu anyways so OK if it's not 100% accurate
if (Upscaler->IsAutoQualityMode())
{
return TEXT("FDLSSDenoiserWrapper(Auto)");
}
else
{
return TEXT("FDLSSDenoiserWrapper(Active)");
}
return TEXT("FDLSSDenoiserWrapper(Active)");
}
else
{
@@ -87,7 +71,7 @@ IScreenSpaceDenoiser::FPolychromaticPenumbraOutputs FDLSSDenoiser::DenoisePolych
IScreenSpaceDenoiser::FReflectionsOutputs FDLSSDenoiser::DenoiseReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const
{
FReflectionsOutputs Outputs = WrappedDenoiser->DenoiseReflections(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
const bool bIsDLSSActive = Upscaler->IsDLSSActive() && View.Family && Upscaler->IsValidUpscalerInstance(View.Family->GetTemporalUpscalerInterface());
const bool bIsDLSSActive = View.Family && FDLSSSceneViewFamilyUpscaler::IsDLSSTemporalUpscaler(View.Family->GetTemporalUpscalerInterface());
const bool bApplyTemporalAA = bIsDLSSActive && CVarNGXDLSSReflectionsTemporalAA.GetValueOnRenderThread() && View.ViewState && IsTemporalAccumulationBasedMethod(View.AntiAliasingMethod);
if(bApplyTemporalAA)
{
@@ -116,7 +100,7 @@ IScreenSpaceDenoiser::FReflectionsOutputs FDLSSDenoiser::DenoiseReflections(FRDG
IScreenSpaceDenoiser::FReflectionsOutputs FDLSSDenoiser::DenoiseWaterReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const
{
FReflectionsOutputs Outputs = WrappedDenoiser->DenoiseWaterReflections(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
const bool bIsDLSSActive = Upscaler->IsDLSSActive() && View.Family && Upscaler->IsValidUpscalerInstance(View.Family->GetTemporalUpscalerInterface());
const bool bIsDLSSActive = View.Family && FDLSSSceneViewFamilyUpscaler::IsDLSSTemporalUpscaler(View.Family->GetTemporalUpscalerInterface());
const bool bApplyTemporalAA = bIsDLSSActive && Upscaler->IsDLSSActive() && CVarNGXDLSSWaterReflectionsTemporalAA.GetValueOnRenderThread() && View.ViewState && IsTemporalAccumulationBasedMethod(View.AntiAliasingMethod);
if (bApplyTemporalAA)
{
@@ -146,20 +130,6 @@ IScreenSpaceDenoiser::FAmbientOcclusionOutputs FDLSSDenoiser::DenoiseAmbientOccl
{
return WrappedDenoiser->DenoiseAmbientOcclusion(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
#if ENGINE_MAJOR_VERSION == 4
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseDiffuseIndirect(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseScreenSpaceDiffuseIndirect(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
IScreenSpaceDenoiser::FDiffuseIndirectHarmonic FDLSSDenoiser::DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseDiffuseIndirectHarmonic(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
#elif ENGINE_MAJOR_VERSION == 5
FSSDSignalTextures FDLSSDenoiser::DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
@@ -175,9 +145,6 @@ FSSDSignalTextures FDLSSDenoiser::DenoiseDiffuseIndirectHarmonic(FRDGBuilder& Gr
{
return WrappedDenoiser->DenoiseDiffuseIndirectHarmonic(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, CommonDiffuseParameters);
}
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
@@ -1,29 +1,18 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
#include "CoreMinimal.h"
#include "ScreenSpaceDenoise.h"
// for ENGINE_MAJOR_VERSION
#include "Launch/Resources/Version.h"
class FDLSSUpscaler;
// wrapper for the default denoiser to add TAA after some passes
@@ -41,17 +30,9 @@ public:
virtual FReflectionsOutputs DenoiseReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const final;
virtual FReflectionsOutputs DenoiseWaterReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const override;
virtual FAmbientOcclusionOutputs DenoiseAmbientOcclusion(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FAmbientOcclusionInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
#if ENGINE_MAJOR_VERSION == 4
virtual FDiffuseIndirectOutputs DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FDiffuseIndirectHarmonic DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FDiffuseIndirectOutputs DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
#elif ENGINE_MAJOR_VERSION == 5
virtual FSSDSignalTextures DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FSSDSignalTextures DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FSSDSignalTextures DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder,const FViewInfo& View,FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const HybridIndirectLighting::FCommonParameters& CommonDiffuseParameters) const final;
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
virtual FDiffuseIndirectOutputs DenoiseSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FDiffuseIndirectOutputs DenoiseReflectedSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
@@ -1,22 +0,0 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include "DLSSSettings.h"
#define LOCTEXT_NAMESPACE "FDLSSModule"
+210 -241
View File
@@ -12,6 +12,7 @@
#include "DLSSUpscaler.h"
#include "DLSS.h"
#include "DLSSUpscalerPrivate.h"
#include "DLSSUpscalerHistory.h"
#include "DLSSSettings.h"
@@ -22,6 +23,7 @@
#include "PostProcess/PostProcessing.h"
#include "SceneTextureParameters.h"
#include "ScreenPass.h"
#include "DynamicResolutionState.h"
#include "RayTracing/RaytracingOptions.h"
@@ -30,10 +32,6 @@
#define LOCTEXT_NAMESPACE "FDLSSModule"
#ifndef SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
#define SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE 1
#endif
static TAutoConsoleVariable<int32> CVarNGXDLSSEnable(
TEXT("r.NGX.DLSS.Enable"), 1,
TEXT("Enable/Disable DLSS entirely."),
@@ -69,7 +67,7 @@ static TAutoConsoleVariable<bool> CVarNGXDLSSAutoQualitySetting(
static TAutoConsoleVariable<float> CVarNGXDLSSSharpness(
TEXT("r.NGX.DLSS.Sharpness"),
0.0f,
TEXT("-1.0 to 1.0: Softening/sharpening to apply to the DLSS pass. Negative values soften the image, positive values sharpen. (default: 0.0f)"),
TEXT("[deprecated] -1.0 to 1.0: Softening/sharpening to apply to the DLSS pass. Negative values soften the image, positive values sharpen. (default: 0.0f)"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSDilateMotionVectors(
@@ -112,6 +110,8 @@ static TAutoConsoleVariable<int32> CVarNGXDLSSFeatureVisibilityMask(
DECLARE_GPU_STAT(DLSS)
static const float kDLSSResolutionFractionError = 0.01f;
BEGIN_SHADER_PARAMETER_STRUCT(FDLSSShaderParameters, )
// Input images
@@ -126,6 +126,13 @@ RDG_TEXTURE_ACCESS(SceneColorOutput, ERHIAccess::UAVCompute)
END_SHADER_PARAMETER_STRUCT()
static FDLSSUpscaler* GetGlobalDLSSUpscaler()
{
IDLSSModuleInterface* DLSSModule = &FModuleManager::LoadModuleChecked<IDLSSModuleInterface>("DLSS");
check(DLSSModule);
return DLSSModule->GetDLSSUpscaler();
}
FIntPoint FDLSSPassParameters::GetOutputExtent() const
{
@@ -148,12 +155,6 @@ bool FDLSSPassParameters::Validate() const
return true;
}
const TCHAR* FDLSSUpscaler::GetDebugName() const
{
return TEXT("FDLSSUpscaler");
}
static NVSDK_NGX_PerfQuality_Value ToNGXQuality(EDLSSQualityMode Quality)
{
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new EDLSSQualityMode enum values");
@@ -179,48 +180,119 @@ static NVSDK_NGX_PerfQuality_Value ToNGXQuality(EDLSSQualityMode Quality)
}
NGXRHI* FDLSSUpscaler::NGXRHIExtensions;
TStaticArray <TSharedPtr<FDLSSUpscaler>, uint32(EDLSSQualityMode::NumValues)> FDLSSUpscaler::DLSSUpscalerInstancesPerViewFamily;
float FDLSSUpscaler::MinResolutionFraction = TNumericLimits <float>::Max();
float FDLSSUpscaler::MaxResolutionFraction = TNumericLimits <float>::Min();
float FDLSSUpscaler::MinDynamicResolutionFraction = TNumericLimits <float>::Max();
float FDLSSUpscaler::MaxDynamicResolutionFraction = TNumericLimits <float>::Min();
uint32 FDLSSUpscaler::NumRuntimeQualityModes = 0;
TArray<FDLSSOptimalSettings> FDLSSUpscaler::ResolutionSettings;
FDLSSUpscaler* FDLSSUpscaler::GetUpscalerInstanceForViewFamily(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode)
bool FDLSSUpscalerViewExtension::IsActiveThisFrame_Internal(const FSceneViewExtensionContext& Context) const
{
uint32 ArrayIndex = (int32)ToNGXQuality(InQualityMode);
if (!DLSSUpscalerInstancesPerViewFamily[ArrayIndex])
{
DLSSUpscalerInstancesPerViewFamily[ArrayIndex] = MakeShared<FDLSSUpscaler>(InUpscaler, InQualityMode);
}
return DLSSUpscalerInstancesPerViewFamily[ArrayIndex].Get();
}
bool FDLSSUpscaler::IsValidUpscalerInstance(const ITemporalUpscaler* InUpscaler)
{
// DLSSUpscalerInstancesPerViewFamily gets lazily initialized, but we don't want to accidentally treat nullptr as a valid
// upscaler instance, when we want to check (e.g. in the denoiser) whether DLSS is actually active for the viewfamily
if (InUpscaler == nullptr)
// Verify this is for a viewport client
if (Context.Viewport == nullptr || !GEngine)
{
return false;
}
for (auto UpscalerInstance : DLSSUpscalerInstancesPerViewFamily)
// Do not setup temporal upscaler in automated tests.
const bool bDLSSActiveWithAutomation = !GIsAutomationTesting || (GIsAutomationTesting && (CVarNGXDLSSAutomationTesting.GetValueOnAnyThread() != 0));
if (!bDLSSActiveWithAutomation)
{
if (UpscalerInstance.Get() == InUpscaler)
return false;
}
// Do not setup if not available.
if (!GetGlobalDLSSUpscaler()->IsDLSSActive())
{
return false;
}
if (GIsEditor)
#if WITH_EDITOR
{
if (Context.Viewport->IsPlayInEditorViewport())
{
return true;
bool bEnableDLSSInPlayInEditorViewports = false;
if (GetDefault<UDLSSOverrideSettings>()->EnableDLSSInPlayInEditorViewportsOverride == EDLSSSettingOverride::UseProjectSettings)
{
bEnableDLSSInPlayInEditorViewports = GetDefault<UDLSSSettings>()->bEnableDLSSInPlayInEditorViewports;
}
else
{
bEnableDLSSInPlayInEditorViewports = GetDefault<UDLSSOverrideSettings>()->EnableDLSSInPlayInEditorViewportsOverride == EDLSSSettingOverride::Enabled;
}
#if !NO_LOGGING
static bool bLoggedPIEWarning = false;
if (!bLoggedPIEWarning && GIsPlayInEditorWorld && bEnableDLSSInPlayInEditorViewports)
{
if (FStaticResolutionFractionHeuristic::FUserSettings::EditorOverridePIESettings())
{
UE_LOG(LogDLSS, Warning, TEXT("r.ScreenPercentage for DLSS quality mode will be ignored because overridden by editor settings (r.Editor.Viewport.OverridePIEScreenPercentage). Change this behavior in Edit -> Editor Preferences -> Performance"));
bLoggedPIEWarning = true;
}
}
#endif
return GIsPlayInEditorWorld && bEnableDLSSInPlayInEditorViewports;
}
else
{
bool bEnableDLSSInEditorViewports = false;
if (GetDefault<UDLSSOverrideSettings>()->EnableDLSSInEditorViewportsOverride == EDLSSSettingOverride::UseProjectSettings)
{
bEnableDLSSInEditorViewports = GetDefault<UDLSSSettings>()->bEnableDLSSInEditorViewports;
}
else
{
bEnableDLSSInEditorViewports = GetDefault<UDLSSOverrideSettings>()->EnableDLSSInEditorViewportsOverride == EDLSSSettingOverride::Enabled;
}
return bEnableDLSSInEditorViewports;
}
}
return false;
#else
{
return false;
}
#endif
else
{
const bool bIsGameViewport = Context.Viewport->GetClient() == GEngine->GameViewport;
return bIsGameViewport;
}
}
bool FDLSSUpscaler::IsAutoQualityMode()
void FDLSSUpscalerViewExtension::BeginRenderViewFamily(FSceneViewFamily& ViewFamily)
{
return CVarNGXDLSSAutoQualitySetting.GetValueOnAnyThread();
if (ViewFamily.ViewMode != EViewModeIndex::VMI_Lit ||
ViewFamily.Scene == nullptr ||
ViewFamily.Scene->GetShadingPath() != EShadingPath::Deferred ||
!ViewFamily.bRealtimeUpdate)
{
return;
}
// Early returns if none of the view have a view state.
for (const FSceneView* View : ViewFamily.Views)
{
if (View->State == nullptr)
{
return;
}
}
// Early returns if AA is disabled.
if (!ViewFamily.EngineShowFlags.AntiAliasing)
{
return;
}
if (!ViewFamily.GetTemporalUpscalerInterface())
{
GetGlobalDLSSUpscaler()->SetupViewFamily(ViewFamily);
}
else
{
UE_LOG(LogDLSS, Error, TEXT("Another plugin already set FSceneViewFamily::SetTemporalUpscalerInterface()"));
return;
}
}
bool FDLSSUpscaler::IsDLAAMode()
@@ -228,25 +300,9 @@ bool FDLSSUpscaler::IsDLAAMode()
return CVarNGXDLAAEnable.GetValueOnAnyThread();
}
void FDLSSUpscaler::SetAutoQualityMode(bool bAutoQualityMode)
FDLSSUpscaler::FDLSSUpscaler(NGXRHI* InNGXRHIExtensions): PreviousResolutionFraction(-1.0f)
{
check(IsInGameThread());
CVarNGXDLSSAutoQualitySetting->Set(bAutoQualityMode, ECVF_SetByCommandline);
}
// make copy & assign quality mode
FDLSSUpscaler::FDLSSUpscaler(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode)
: FDLSSUpscaler(*InUpscaler)
{
DLSSQualityMode = InQualityMode;
check(NGXRHIExtensions);
}
FDLSSUpscaler::FDLSSUpscaler(NGXRHI* InNGXRHIExtensions)
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSS, VeryVerbose, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
checkf(!NGXRHIExtensions, TEXT("static member NGXRHIExtensions should only be assigned once by this ctor when called during module startup") );
@@ -267,9 +323,8 @@ FDLSSUpscaler::FDLSSUpscaler(NGXRHI* InNGXRHIExtensions)
// we only consider non-fixed resolutions for the overall min / max resolution fraction
if (OptimalSettings.bIsSupported && !OptimalSettings.IsFixedResolution())
{
// We use OptimalSettings.OptimalResolutionFraction to avoid getting to "floating point close" to OptimalSettings.{MinMax}ResolutionFraction)
MinResolutionFraction = FMath::Min(MinResolutionFraction, OptimalSettings.OptimalResolutionFraction);
MaxResolutionFraction = FMath::Max(MaxResolutionFraction, OptimalSettings.OptimalResolutionFraction);
MinDynamicResolutionFraction = FMath::Min(MinDynamicResolutionFraction, OptimalSettings.MinResolutionFraction);
MaxDynamicResolutionFraction = FMath::Max(MaxDynamicResolutionFraction, OptimalSettings.MaxResolutionFraction);
++NumRuntimeQualityModes;
}
@@ -278,7 +333,7 @@ FDLSSUpscaler::FDLSSUpscaler(NGXRHI* InNGXRHIExtensions)
}
// the DLSS module will report DLSS as not supported if there are no supported quality modes at runtime
UE_LOG(LogDLSS, Log, TEXT("NumRuntimeQualityModes=%u, MinResolutionFraction=%.4f, MaxResolutionFraction=%.4f"), NumRuntimeQualityModes, MinResolutionFraction, MaxResolutionFraction);
UE_LOG(LogDLSS, Log, TEXT("NumRuntimeQualityModes=%u, MinDynamicResolutionFraction=%.4f, MaxDynamicResolutionFraction=%.4f"), NumRuntimeQualityModes, MinDynamicResolutionFraction, MaxDynamicResolutionFraction);
// Higher levels of the code (e.g. UI) should check whether each mode is actually supported
// But for now verify early that the DLSS 2.0 modes are supported. Those checks could be removed in the future
@@ -287,54 +342,53 @@ FDLSSUpscaler::FDLSSUpscaler(NGXRHI* InNGXRHIExtensions)
check(IsQualityModeSupported(EDLSSQualityMode::Quality));
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
FDLSSUpscaler::~FDLSSUpscaler()
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSS, VeryVerbose, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
// this gets explicitly called during module shutdown
void FDLSSUpscaler::ReleaseStaticResources()
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSS, VeryVerbose, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
ResolutionSettings.Empty();
for (auto& UpscalerInstance : DLSSUpscalerInstancesPerViewFamily)
{
UpscalerInstance.Reset();
}
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSS, VeryVerbose, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
void FDLSSUpscaler::AddPasses(
#else
ITemporalUpscaler::FOutputs FDLSSUpscaler::AddPasses(
#endif
static const TCHAR* const GDLSSSceneViewFamilyUpscalerDebugName = TEXT("FDLSSSceneViewFamilyUpscaler");
const TCHAR* FDLSSSceneViewFamilyUpscaler::GetDebugName() const
{
return GDLSSSceneViewFamilyUpscalerDebugName;
}
// static
bool FDLSSSceneViewFamilyUpscaler::IsDLSSTemporalUpscaler(const ITemporalUpscaler* TemporalUpscaler)
{
return TemporalUpscaler != nullptr && TemporalUpscaler->GetDebugName() == GDLSSSceneViewFamilyUpscalerDebugName;
}
float FDLSSSceneViewFamilyUpscaler::GetMinUpsampleResolutionFraction() const
{
return Upscaler->GetMinResolutionFractionForQuality(DLSSQualityMode);
}
float FDLSSSceneViewFamilyUpscaler::GetMaxUpsampleResolutionFraction() const
{
return Upscaler->GetMaxResolutionFractionForQuality(DLSSQualityMode);
}
ITemporalUpscaler* FDLSSSceneViewFamilyUpscaler::Fork_GameThread(const class FSceneViewFamily& ViewFamily) const
{
return new FDLSSSceneViewFamilyUpscaler(Upscaler, DLSSQualityMode);
}
ITemporalUpscaler::FOutputs FDLSSSceneViewFamilyUpscaler::AddPasses(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FPassInputs& PassInputs
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
, FRDGTextureRef* OutSceneColorTexture
, FIntRect* OutSceneColorViewRect
, FRDGTextureRef* OutSceneColorHalfResTexture
, FIntRect* OutSceneColorHalfResViewRect
#endif
) const
{
#if ENGINE_MAJOR_VERSION < 5
// For TAAU, this can happen with screen percentages larger than 100%, so not something that DLSS viewports are setup with
checkf(!PassInputs.bAllowDownsampleSceneColor,TEXT("The DLSS plugin does not support downsampling the scenecolor. Please set r.TemporalAA.AllowDownsampling=0"));
#endif
checkf(View.PrimaryScreenPercentageMethod == EPrimaryScreenPercentageMethod::TemporalUpscale, TEXT("DLSS requires TemporalUpscale. If you hit this assert, please set r.TemporalAA.Upscale=1"));
const FTemporalAAHistory& InputHistory = View.PrevViewInfo.TemporalAAHistory;
const TRefCountPtr<ICustomTemporalAAHistory> InputCustomHistory = View.PrevViewInfo.CustomTemporalAAHistory;
@@ -344,9 +398,7 @@ ITemporalUpscaler::FOutputs FDLSSUpscaler::AddPasses(
FDLSSPassParameters DLSSParameters(View);
const FIntRect SecondaryViewRect = DLSSParameters.OutputViewRect;
#if !DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
ITemporalUpscaler::FOutputs Outputs;
#endif
{
RDG_GPU_STAT_SCOPE(GraphBuilder, DLSS);
RDG_EVENT_SCOPE(GraphBuilder, "DLSS");
@@ -369,25 +421,13 @@ ITemporalUpscaler::FOutputs FDLSSUpscaler::AddPasses(
OutputCustomHistory
);
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
FRDGTextureRef SceneColorTexture = DLSSOutputs.SceneColor;
*OutSceneColorTexture = SceneColorTexture;
*OutSceneColorViewRect = SecondaryViewRect;
*OutSceneColorHalfResTexture = nullptr;
*OutSceneColorHalfResViewRect = FIntRect(FIntPoint::ZeroValue, FIntPoint::ZeroValue);
#else
Outputs.FullRes.Texture = DLSSOutputs.SceneColor;
Outputs.FullRes.ViewRect = SecondaryViewRect;
#endif
}
#if !DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
return Outputs;
#endif
}
FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
FDLSSOutputs FDLSSSceneViewFamilyUpscaler::AddDLSSPass(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FDLSSPassParameters& Inputs,
@@ -397,8 +437,8 @@ FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
TRefCountPtr<ICustomTemporalAAHistory>* OutputCustomHistoryInterface
) const
{
check(IsValidUpscalerInstance(this));
check(IsDLSSActive());
check(IsInRenderingThread());
check(Upscaler->IsDLSSActive());
const FDLSSUpscalerHistory* InputCustomHistory = static_cast<const FDLSSUpscalerHistory*>(InputCustomHistoryInterface.GetReference());
const bool bCameraCut = !InputHistory.IsValid() || View.bCameraCut || !OutputHistory;
@@ -414,13 +454,16 @@ FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
// set DLSSQualityMode by setting an FDLSSUpscaler on the ViewFamily (from the pool in DLSSUpscalerInstancesPerViewFamily)
checkf(DLSSQualityMode != EDLSSQualityMode::NumValues, TEXT("Invalid Quality mode, not initialized"));
checkf(IsQualityModeSupported(DLSSQualityMode), TEXT("%u is not a valid Quality mode"), DLSSQualityMode);
checkf(Upscaler->IsQualityModeSupported(DLSSQualityMode), TEXT("%u is not a valid Quality mode"), DLSSQualityMode);
// This assert can accidentally hit with small viewrect dimensions (e.g. when resizing an editor view) due to floating point rounding & quantization issues
// e.g. with 33% screen percentage at 1000 DestRect dimension we get 333/1000 = 0.33 but at 10 DestRect dimension we get 3/10 0.3, thus the assert hits
checkf(DestRect.Width() < 100 || GetMinResolutionFractionForQuality(DLSSQualityMode) - 0.01f <= ScaleX && ScaleX <= GetMaxResolutionFractionForQuality(DLSSQualityMode) + 0.01f, TEXT("The current resolution fraction %f is out of the supported DLSS range [%f ... %f] for quality mode %d."), ScaleX, GetMinResolutionFractionForQuality(DLSSQualityMode), GetMaxResolutionFractionForQuality(DLSSQualityMode), DLSSQualityMode);
checkf(DestRect.Height() < 100 || GetMinResolutionFractionForQuality(DLSSQualityMode) - 0.01f <= ScaleY && ScaleY <= GetMaxResolutionFractionForQuality(DLSSQualityMode) + 0.01f, TEXT("The current resolution fraction %f is out of the supported DLSS range [%f ... %f] for quality mode %d."), ScaleY, GetMinResolutionFractionForQuality(DLSSQualityMode), GetMaxResolutionFractionForQuality(DLSSQualityMode), DLSSQualityMode);
checkf(DestRect.Width() < 100 || GetMinUpsampleResolutionFraction() - kDLSSResolutionFractionError <= ScaleX && ScaleX <= GetMaxUpsampleResolutionFraction() + kDLSSResolutionFractionError,
TEXT("The current resolution fraction %f is out of the supported DLSS range [%f ... %f] for quality mode %d."),
ScaleX, GetMinUpsampleResolutionFraction(), GetMaxUpsampleResolutionFraction(), DLSSQualityMode);
checkf(DestRect.Height() < 100 || GetMinUpsampleResolutionFraction() - kDLSSResolutionFractionError <= ScaleY && ScaleY <= GetMaxUpsampleResolutionFraction() + kDLSSResolutionFractionError,
TEXT("The current resolution fraction %f is out of the supported DLSS range [%f ... %f] for quality mode %d."),
ScaleY, GetMinUpsampleResolutionFraction(), GetMaxUpsampleResolutionFraction(), DLSSQualityMode);
const TCHAR* PassName = TEXT("MainUpsampling");
@@ -463,19 +506,22 @@ FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
}
const FVector2D JitterOffset = View.TemporalJitterPixels;
#if ENGINE_MAJOR_VERSION < 5
const float DeltaWorldTime = View.Family->DeltaWorldTime;
#else
const float DeltaWorldTime = View.Family->Time.GetDeltaWorldTimeSeconds();
#endif
const float PreExposure = View.PreExposure;
const bool bUseAutoExposure = CVarNGXDLSSAutoExposure.GetValueOnRenderThread() != 0;
const bool bReleaseMemoryOnDelete = CVarNGXDLSSReleaseMemoryOnDelete.GetValueOnRenderThread() != 0;
const float Sharpness = FMath::Clamp(CVarNGXDLSSSharpness.GetValueOnRenderThread(), -1.0f, 1.0f);
NGXRHI* LocalNGXRHIExtensions = this->NGXRHIExtensions;
#if !NO_LOGGING
static bool bLoggedSharpnessWarning = false;
if (Sharpness != 0.0f && !bLoggedSharpnessWarning)
{
UE_LOG(LogDLSS, Warning, TEXT("DLSS sharpening is deprecated, recommend using the NIS plugin for sharpening instead"));
bLoggedSharpnessWarning = true;
}
#endif
NGXRHI* LocalNGXRHIExtensions = Upscaler->NGXRHIExtensions;
const int32 NGXPerfQuality = ToNGXQuality(DLSSQualityMode);
GraphBuilder.AddPass(
RDG_EVENT_NAME("DLSS %s%s %dx%d -> %dx%d",
@@ -485,6 +531,7 @@ FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
DestRect.Width(), DestRect.Height()),
PassParameters,
ERDGPassFlags::Compute | ERDGPassFlags::Raster | ERDGPassFlags::SkipRenderPass,
// FRHICommandListImmediate forces it to run on render thread, FRHICommandList doesn't
[LocalNGXRHIExtensions, PassParameters, Inputs, bCameraCut, JitterOffset, DeltaWorldTime, PreExposure, Sharpness, NGXPerfQuality, DLSSState, bUseAutoExposure, bReleaseMemoryOnDelete](FRHICommandListImmediate& RHICmdList)
{
FRHIDLSSArguments DLSSArguments;
@@ -497,16 +544,9 @@ FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
DLSSArguments.Sharpness = Sharpness;
DLSSArguments.bReset = bCameraCut;
#if ENGINE_MAJOR_VERSION < 5
DLSSArguments.JitterOffset = JitterOffset;
DLSSArguments.MotionVectorScale = FVector2D(1.0f, 1.0f);
#else
DLSSArguments.JitterOffset = FVector2f(JitterOffset); // LWC_TODO: Precision loss
DLSSArguments.MotionVectorScale = FVector2f::UnitVector;
#endif ENGINE_MAJOR_VERSION
DLSSArguments.bHighResolutionMotionVectors = Inputs.bHighResolutionMotionVectors;
DLSSArguments.DeltaTime = DeltaWorldTime;
DLSSArguments.bReleaseMemoryOnDelete = bReleaseMemoryOnDelete;
@@ -537,7 +577,7 @@ FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
PassParameters->SceneColorOutput->MarkResourceAsUsed();
DLSSArguments.OutputColor = PassParameters->SceneColorOutput->GetRHI();
RHICmdList.TransitionResource(ERHIAccess::UAVMask, DLSSArguments.OutputColor);
RHICmdList.Transition(FRHITransitionInfo(DLSSArguments.OutputColor, ERHIAccess::Unknown, ERHIAccess::UAVMask));
RHICmdList.EnqueueLambda(
[LocalNGXRHIExtensions, DLSSArguments, DLSSState](FRHICommandListImmediate& Cmd) mutable
{
@@ -593,127 +633,66 @@ bool FDLSSUpscaler::IsQualityModeSupported(EDLSSQualityMode InQualityMode) const
bool FDLSSUpscaler::IsDLSSActive() const
{
static const auto CVarTemporalAAUpscaler = IConsoleManager::Get().FindConsoleVariable(TEXT("r.TemporalAA.Upscaler"));
static const IDLSSModuleInterface* DLSSModule = &FModuleManager::LoadModuleChecked<IDLSSModuleInterface>(TEXT("DLSS"));
check(DLSSModule);
check(CVarTemporalAAUpscaler);
const bool bDLSSActive =
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
((GTemporalUpscaler == this) || IsValidUpscalerInstance(this)) &&
#else
((GCustomStaticScreenPercentage == this) || IsValidUpscalerInstance(this)) &&
#endif
DLSSModule->QueryDLSSSupport() == EDLSSSupport::Supported &&
CVarTemporalAAUpscaler && (CVarTemporalAAUpscaler->GetInt() != 0) &&
((CVarNGXDLSSEnable.GetValueOnAnyThread() != 0) || CVarNGXDLAAEnable.GetValueOnAnyThread());
return bDLSSActive;
}
void FDLSSUpscaler::SetupMainGameViewFamily(FSceneViewFamily& ViewFamily)
void FDLSSUpscaler::SetupViewFamily(FSceneViewFamily& ViewFamily)
{
const bool bDLSSActiveWithAutomation = !GIsAutomationTesting || (GIsAutomationTesting && (CVarNGXDLSSAutomationTesting.GetValueOnAnyThread() != 0));
if (IsDLSSActive() && bDLSSActiveWithAutomation)
const ISceneViewFamilyScreenPercentage* ScreenPercentageInterface = ViewFamily.GetScreenPercentageInterface();
float DesiredResolutionFraction = ScreenPercentageInterface->GetResolutionFractionsUpperBound()[GDynamicPrimaryResolutionFraction];
TOptional<EDLSSQualityMode> SelectedDLSSQualityMode;
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new EDLSSQualityMode enum values");
for (EDLSSQualityMode DLSSQualityMode : { EDLSSQualityMode::UltraPerformance, EDLSSQualityMode::Performance , EDLSSQualityMode::Balanced, EDLSSQualityMode::Quality, EDLSSQualityMode::UltraQuality })
{
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
checkf(GTemporalUpscaler == this, TEXT("GTemporalUpscaler is not set to a DLSS upscaler . Please check that only one upscaling plugin is active."));
#endif
checkf(GCustomStaticScreenPercentage == this, TEXT("GCustomStaticScreenPercentage is not set to a DLSS upscaler. Please check that only one upscaling plugin is active."));
if (!GIsEditor || (GIsEditor && GIsPlayInEditorWorld && EnableDLSSInPlayInEditorViewports()))
bool bIsSupported = FDLSSUpscaler::IsQualityModeSupported(DLSSQualityMode);
if (!bIsSupported)
{
bool bIsDLAAMode = IsDLAAMode();
EDLSSQualityMode DLSSQuality;
if (bIsDLAAMode)
{
DLSSQuality = EDLSSQualityMode::Quality;
}
else if (IsAutoQualityMode())
{
TOptional<EDLSSQualityMode> MaybeDLSSQuality = GetAutoQualityModeFromViewFamily(ViewFamily);
if (!MaybeDLSSQuality.IsSet())
{
return;
}
else
{
DLSSQuality = MaybeDLSSQuality.GetValue();
}
}
else
{
DLSSQuality = GetSupportedQualityModeFromCVarValue(CVarNGXDLSSPerfQualitySetting.GetValueOnGameThread());
}
continue;
}
ViewFamily.SetTemporalUpscalerInterface(GetUpscalerInstanceForViewFamily(this, DLSSQuality));
float MinResolutionFraction = FDLSSUpscaler::GetMinResolutionFractionForQuality(DLSSQualityMode);
float MaxResolutionFraction = FDLSSUpscaler::GetMaxResolutionFractionForQuality(DLSSQualityMode);
float TargetResolutionFraction = FDLSSUpscaler::GetOptimalResolutionFractionForQuality(DLSSQualityMode);
if (ViewFamily.EngineShowFlags.ScreenPercentage && !ViewFamily.GetScreenPercentageInterface())
{
// DLSS uses recommended resolution fraction, DLAA forces a 1.0 scale
float ResolutionFraction = 1.0f;
if (!bIsDLAAMode)
{
ResolutionFraction = GetOptimalResolutionFractionForQuality(DLSSQuality);
}
ViewFamily.SetScreenPercentageInterface(new FLegacyScreenPercentageDriver(
ViewFamily, ResolutionFraction
#if SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
/* AllowPostProcessSettingsScreenPercentage = */ , false
#endif
));
}
bool bIsCompatible = DesiredResolutionFraction <= 1.0 &&
DesiredResolutionFraction >= (MinResolutionFraction - kDLSSResolutionFractionError) &&
DesiredResolutionFraction <= (MaxResolutionFraction + kDLSSResolutionFractionError);
bool bIsClosestYet = false;
if (SelectedDLSSQualityMode.IsSet())
{
float SelectedTargetResolutionFraction = FDLSSUpscaler::GetOptimalResolutionFractionForQuality(SelectedDLSSQualityMode.GetValue());
bIsClosestYet = FMath::Abs(TargetResolutionFraction - DesiredResolutionFraction) < FMath::Abs(SelectedTargetResolutionFraction - DesiredResolutionFraction);
}
else if (bIsCompatible)
{
bIsClosestYet = true;
}
if (bIsCompatible && bIsClosestYet)
{
SelectedDLSSQualityMode = DLSSQualityMode;
}
}
}
#if DLSS_ENGINE_SUPPORTS_CSSPD
void FDLSSUpscaler::SetupViewFamily(FSceneViewFamily& ViewFamily, TSharedPtr<ICustomStaticScreenPercentageData> InScreenPercentageDataInterface)
{
check(InScreenPercentageDataInterface.IsValid());
TSharedPtr<FDLSSViewportQualitySetting> ScreenPercentageData = StaticCastSharedPtr<FDLSSViewportQualitySetting>(InScreenPercentageDataInterface);
EDLSSQualityMode Quality = static_cast<EDLSSQualityMode>(ScreenPercentageData->QualitySetting);
const bool bIsDLAAMode = ScreenPercentageData->bDLAAEnabled;
if (bIsDLAAMode)
if (SelectedDLSSQualityMode.IsSet())
{
Quality = EDLSSQualityMode::Quality;
ViewFamily.SetTemporalUpscalerInterface(new FDLSSSceneViewFamilyUpscaler(this, SelectedDLSSQualityMode.GetValue()));
}
if (!IsQualityModeSupported(Quality))
else if (DesiredResolutionFraction != PreviousResolutionFraction)
{
UE_LOG(LogDLSS, Warning, TEXT("DLSS Quality mode is not supported %d"), Quality);
return;
UE_LOG(LogDLSS, Warning, TEXT("Could not setup DLSS upscaler for screen percentage = %f"), DesiredResolutionFraction * 100.0f);
}
const bool bDLSSActiveWithAutomation = !GIsAutomationTesting || (GIsAutomationTesting && (CVarNGXDLSSAutomationTesting.GetValueOnAnyThread() != 0));
if (IsDLSSActive() && bDLSSActiveWithAutomation)
{
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
checkf(GTemporalUpscaler == this, TEXT("GTemporalUpscaler is not set to a DLSS upscaler . Please check that only one upscaling plugin is active."));
#endif
checkf(GCustomStaticScreenPercentage == this, TEXT("GCustomStaticScreenPercentage is not set to a DLSS upscaler. Please check that only one upscaling plugin is active."));
ViewFamily.SetTemporalUpscalerInterface(GetUpscalerInstanceForViewFamily(this, Quality));
if (ViewFamily.EngineShowFlags.ScreenPercentage && !ViewFamily.GetScreenPercentageInterface())
{
const float ResolutionFraction = bIsDLAAMode ? 1.0f : GetOptimalResolutionFractionForQuality(Quality);
ViewFamily.SetScreenPercentageInterface(new FLegacyScreenPercentageDriver(
ViewFamily, ResolutionFraction
#if SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
/* AllowPostProcessSettingsScreenPercentage = */ , false
#endif
));
}
}
}
#endif
TOptional<EDLSSQualityMode> FDLSSUpscaler::GetAutoQualityModeFromViewFamily(const FSceneViewFamily& ViewFamily) const
{
if (ensure(ViewFamily.RenderTarget != nullptr))
{
FIntPoint ViewSize = ViewFamily.RenderTarget->GetSizeXY();
int32 Pixels = ViewSize.X * ViewSize.Y;
return GetAutoQualityModeFromPixels(Pixels);
}
return TOptional<EDLSSQualityMode> {};
PreviousResolutionFraction = DesiredResolutionFraction;
}
TOptional<EDLSSQualityMode> FDLSSUpscaler::GetAutoQualityModeFromPixels(int PixelCount) const
@@ -735,7 +714,7 @@ TOptional<EDLSSQualityMode> FDLSSUpscaler::GetAutoQualityModeFromPixels(int Pixe
}
bool FDLSSUpscaler::EnableDLSSInPlayInEditorViewports() const
bool FDLSSUpscaler::EnableDLSSInPlayInEditorViewports() const
{
if (GetDefault<UDLSSOverrideSettings>()->EnableDLSSInPlayInEditorViewportsOverride == EDLSSSettingOverride::UseProjectSettings)
{
@@ -747,16 +726,6 @@ bool FDLSSUpscaler::EnableDLSSInPlayInEditorViewports() const
}
}
float FDLSSUpscaler::GetMinUpsampleResolutionFraction() const
{
return MinResolutionFraction;
}
float FDLSSUpscaler::GetMaxUpsampleResolutionFraction() const
{
return MaxResolutionFraction;
}
float FDLSSUpscaler::GetOptimalResolutionFractionForQuality(EDLSSQualityMode Quality) const
{
checkf(IsQualityModeSupported(Quality),TEXT("%u is not a valid Quality mode"), Quality);
+69 -72
View File
@@ -12,13 +12,12 @@
#pragma once
#include "CoreMinimal.h"
#include "SceneViewExtension.h"
#include "RendererInterface.h"
#include "PostProcess/TemporalAA.h"
#include "ScreenPass.h"
#include "NGXRHI.h"
#include "DLSSSettings.h"
#include "CustomStaticScreenPercentage.h"
#include "CustomResourcePool.h"
class FSceneTextureParameters;
@@ -28,6 +27,8 @@ struct FTemporalAAHistory;
class FRHITexture;
class NGXRHI;
struct FDLSSOptimalSettings;
class FDLSSUpscaler;
struct FDLSSPassParameters
{
FIntRect InputViewRect;
@@ -68,44 +69,61 @@ enum class EDLSSQualityMode
NumValues = 5
};
class DLSS_API FDLSSUpscaler final : public ITemporalUpscaler, public ICustomStaticScreenPercentage, public ICustomResourcePool
class DLSS_API FDLSSUpscalerViewExtension final : public FSceneViewExtensionBase
{
public:
FDLSSUpscalerViewExtension(const FAutoRegister& AutoRegister) : FSceneViewExtensionBase(AutoRegister)
{ }
virtual void SetupViewFamily(FSceneViewFamily& InViewFamily) override {}
virtual void SetupView(FSceneViewFamily& InViewFamily, FSceneView& InView) override {}
virtual void BeginRenderViewFamily(FSceneViewFamily& InViewFamily) override;
virtual void PreRenderView_RenderThread(FRDGBuilder& GraphBuilder, FSceneView& InView) final override {}
virtual void PreRenderViewFamily_RenderThread(FRDGBuilder& GraphBuilder, FSceneViewFamily& InViewFamily) final override {}
virtual bool IsActiveThisFrame_Internal(const FSceneViewExtensionContext& Context) const override;
};
class DLSS_API FDLSSSceneViewFamilyUpscaler final : public ITemporalUpscaler
{
public:
FDLSSSceneViewFamilyUpscaler(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InDLSSQualityMode)
: Upscaler(InUpscaler)
, DLSSQualityMode(InDLSSQualityMode)
{ }
virtual const TCHAR* GetDebugName() const final override;
virtual float GetMinUpsampleResolutionFraction() const final override;
virtual float GetMaxUpsampleResolutionFraction() const final override;
virtual ITemporalUpscaler* Fork_GameThread(const class FSceneViewFamily& ViewFamily) const final override;
virtual ITemporalUpscaler::FOutputs AddPasses(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FPassInputs& PassInputs) const final override;
static bool IsDLSSTemporalUpscaler(const ITemporalUpscaler* TemporalUpscaler);
private:
const FDLSSUpscaler* Upscaler;
const EDLSSQualityMode DLSSQualityMode;
FDLSSOutputs AddDLSSPass(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FDLSSPassParameters& Inputs,
const FTemporalAAHistory& InputHistory,
FTemporalAAHistory* OutputHistory,
const TRefCountPtr<ICustomTemporalAAHistory> InputCustomHistoryInterface,
TRefCountPtr<ICustomTemporalAAHistory>* OutputCustomHistoryInterface
) const;
};
class DLSS_API FDLSSUpscaler final : public ICustomResourcePool
{
friend class FDLSSModule;
public:
FDLSSUpscaler(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode);
virtual ~FDLSSUpscaler();
// Inherited via ITemporalUpscaler
virtual const TCHAR* GetDebugName() const final;
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
virtual void AddPasses(
#else
virtual ITemporalUpscaler::FOutputs AddPasses(
#endif
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FPassInputs& PassInputs
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
, FRDGTextureRef* OutSceneColorTexture
, FIntRect* OutSceneColorViewRect
, FRDGTextureRef* OutSceneColorHalfResTexture
, FIntRect* OutSceneColorHalfResViewRect
#endif
) const final;
// Inherited via ICustomStaticScreenPercentage
virtual void SetupMainGameViewFamily(FSceneViewFamily& ViewFamily) final;
#if DLSS_ENGINE_SUPPORTS_CSSPD
/** Allows to setup View Family directly. To be used by modules that are aware of DLSS Plugin. */
virtual void SetupViewFamily(FSceneViewFamily& ViewFamily, TSharedPtr<ICustomStaticScreenPercentageData> InScreenPercentageDataInterface) final;
#endif
virtual float GetMinUpsampleResolutionFraction() const final;
virtual float GetMaxUpsampleResolutionFraction() const final;
void SetupViewFamily(FSceneViewFamily& ViewFamily);
float GetOptimalResolutionFractionForQuality(EDLSSQualityMode Quality) const;
float GetOptimalSharpnessForQuality(EDLSSQualityMode Quality) const;
@@ -129,61 +147,40 @@ public:
bool IsDLSSActive() const;
static FDLSSUpscaler* GetUpscalerInstanceForViewFamily(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode);
static bool IsValidUpscalerInstance(const ITemporalUpscaler* InUpscaler);
static bool IsDLAAMode();
static bool IsAutoQualityMode();
static void SetAutoQualityMode(bool bAutoQualityMode);
// Give the suggested EDLSSQualityMode if one is appropriate for the given pixel count, or nothing if DLSS should be disabled
TOptional<EDLSSQualityMode> GetAutoQualityModeFromPixels(int PixelCount) const;
static void ReleaseStaticResources();
static float GetMinUpsampleResolutionFraction()
{
return MinDynamicResolutionFraction;
}
static float GetMaxUpsampleResolutionFraction()
{
return MaxDynamicResolutionFraction;
}
private:
FDLSSUpscaler(NGXRHI* InNGXRHIExtensions);
FDLSSUpscaler(const FDLSSUpscaler&) = default;
EDLSSQualityMode GetSupportedQualityModeFromCVarValue(int32 InCVarValue) const
{
checkf(NumRuntimeQualityModes, TEXT("This should only be called from the higher level code when DLSS is supported") );
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new EDLSSQualityMode enum values");
for (auto QualityMode : { EDLSSQualityMode::UltraPerformance, EDLSSQualityMode::Performance , EDLSSQualityMode::Balanced, EDLSSQualityMode::Quality, EDLSSQualityMode::UltraQuality })
{
if (InCVarValue == static_cast<int32>(QualityMode) && IsQualityModeSupported(QualityMode))
{
return QualityMode;
}
}
return EDLSSQualityMode::Balanced;
}
TOptional<EDLSSQualityMode> GetAutoQualityModeFromViewFamily(const FSceneViewFamily& ViewFamily) const;
bool EnableDLSSInPlayInEditorViewports() const;
FDLSSOutputs AddDLSSPass(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FDLSSPassParameters& Inputs,
const FTemporalAAHistory& InputHistory,
FTemporalAAHistory* OutputHistory,
const TRefCountPtr<ICustomTemporalAAHistory> InputCustomHistoryInterface,
TRefCountPtr<ICustomTemporalAAHistory>* OutputCustomHistoryInterface
) const;
EDLSSQualityMode DLSSQualityMode = EDLSSQualityMode::NumValues;
// The FDLSSUpscaler(NGXRHI*) will update those once
static NGXRHI* NGXRHIExtensions;
static float MinResolutionFraction;
static float MaxResolutionFraction;
static float MinDynamicResolutionFraction;
static float MaxDynamicResolutionFraction;
static uint32 NumRuntimeQualityModes;
static TArray<FDLSSOptimalSettings> ResolutionSettings;
float PreviousResolutionFraction;
static TStaticArray <TSharedPtr<FDLSSUpscaler>, uint32(EDLSSQualityMode::NumValues)> DLSSUpscalerInstancesPerViewFamily;
friend class FDLSSUpscalerViewExtension;
friend class FDLSSSceneViewFamilyUpscaler;
};
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
@@ -26,7 +17,7 @@
class DLSS_API FDLSSUpscalerHistory final : public ICustomTemporalAAHistory, public FRefCountBase
{
friend class FDLSSUpscaler;
friend class FDLSSSceneViewFamilyUpscaler;
FDLSSStateRef DLSSState;
+14 -17
View File
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
@@ -24,6 +15,8 @@
class FDLSSUpscaler;
class FDLSSDenoiser;
class ISceneViewExtension;
class FDLSSUpscalerViewExtension;
class FNGXAutomationViewExtension;
class NGXRHI;
@@ -46,6 +39,7 @@ class IDLSSModuleInterface : public IModuleInterface
virtual void GetDLSSMinDriverVersion(int32& MajorVersion, int32& MinorVersion) const = 0;
virtual float GetResolutionFractionForQuality(int32 Quality) const = 0;
virtual FDLSSUpscaler* GetDLSSUpscaler() const = 0;
virtual TSharedPtr< ISceneViewExtension, ESPMode::ThreadSafe> GetDLSSUpscalerViewExtension() const = 0;
};
class FDLSSModule final: public IDLSSModuleInterface
@@ -60,13 +54,16 @@ public:
virtual EDLSSSupport QueryDLSSSupport() const;
virtual void GetDLSSMinDriverVersion(int32& MajorVersion, int32& MinorVersion) const;
virtual float GetResolutionFractionForQuality(int32 Quality) const;
virtual FDLSSUpscaler* GetDLSSUpscaler() const ;
virtual FDLSSUpscaler* GetDLSSUpscaler() const;
virtual TSharedPtr< ISceneViewExtension, ESPMode::ThreadSafe> GetDLSSUpscalerViewExtension() const;
private:
TUniquePtr<FDLSSUpscaler> DLSSUpscaler;
TUniquePtr<FDLSSDenoiser> DLSSDenoiser;
TUniquePtr<NGXRHI> NGXRHIExtensions;
TSharedPtr< FDLSSUpscalerViewExtension, ESPMode::ThreadSafe> DLSSUpscalerViewExtension;
TSharedPtr< FNGXAutomationViewExtension, ESPMode::ThreadSafe> NGXAutomationViewExtension;
EDLSSSupport DLSSSupport = EDLSSSupport::NotSupported;
int32 MinDriverVersionMinor;
+22 -40
View File
@@ -13,8 +13,7 @@
#include "UObject/ObjectMacros.h"
#include "UObject/Object.h"
#include "Engine/DeveloperSettings.h"
#include "CustomStaticScreenPercentage.h"
#include "Runtime/Launch/Resources/Version.h"
#include "SceneView.h"
#include "DLSSSettings.generated.h"
@@ -33,24 +32,20 @@ public:
GENERATED_BODY()
/** This enables DLSS in editor viewports. Saved to local user config only.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable DLSS to be turned on in Editor viewports")
/** This enables DLSS/DLAA in editor viewports. Saved to local user config only.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable DLSS/DLAA to be turned on in Editor viewports")
EDLSSSettingOverride EnableDLSSInEditorViewportsOverride = EDLSSSettingOverride::UseProjectSettings;
/** This setting enables adjusting the screenpercentage directly in the editor, outside of the optimized DLSS quality modes. Saved to local user config only.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable Screenpercentage Manipulation in DLSS Editor Viewports")
EDLSSSettingOverride EnableScreenpercentageManipulationInDLSSEditorViewportsOverride = EDLSSSettingOverride::UseProjectSettings;
/** This enables DLSS in play in editor viewports. Saved to local user config only. */
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable DLSS in Play In Editor viewports")
/** This enables DLSS/DLAA in play in editor viewports. Saved to local user config only. */
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable DLSS/DLAA in Play In Editor viewports")
EDLSSSettingOverride EnableDLSSInPlayInEditorViewportsOverride = EDLSSSettingOverride::UseProjectSettings;
/** This enables warnings about plugins & tools that are incompatible with DLSS in the editor. Saved to local user config only. */
/** This enables warnings about plugins & tools that are incompatible with DLSS/DLAA in the editor. Saved to local user config only. */
UPROPERTY(Config, EditAnywhere, Category = "Editor (Local)", DisplayName = "Warn about incompatible plugins and tools")
bool bShowDLSSIncompatiblePluginsToolsWarnings = true;
/** This enables on screen warnings and errors about DLSS */
UPROPERTY(Config, EditAnywhere, Category = "Editor (Local)", DisplayName = "Show various DLSS on screen debug messages")
/** This enables on screen warnings and errors about DLSS/DLAA */
UPROPERTY(Config, EditAnywhere, Category = "Editor (Local)", DisplayName = "Show various DLSS/DLAA on screen debug messages")
EDLSSSettingOverride ShowDLSSSDebugOnScreenMessages = EDLSSSettingOverride::UseProjectSettings;
};
@@ -64,32 +59,28 @@ private:
public:
/** Enable DLSS for D3D12, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS for the D3D12RHI")
/** Enable DLSS/DLAA for D3D12, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS/DLAA for the D3D12RHI")
bool bEnableDLSSD3D12 = PLATFORM_WINDOWS;
/** Enable DLSS for D3D11, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS for the D3D11RHI")
/** Enable DLSS/DLAA for D3D11, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS/DLAA for the D3D11RHI")
bool bEnableDLSSD3D11 = PLATFORM_WINDOWS;
/** Enable DLSS for Vulkan, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS for the VulkanRHI")
/** Enable DLSS/DLAA for Vulkan, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS/DLAA for the VulkanRHI")
bool bEnableDLSSVulkan = PLATFORM_WINDOWS;
/** This enables DLSS in editor viewports. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable DLSS to be turned on in Editor viewports")
bool bEnableDLSSInEditorViewports = true;
/** This enables DLSS/DLAA in editor viewports. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable DLSS/DLAA to be turned on in Editor viewports")
bool bEnableDLSSInEditorViewports = false;
/** This setting enables adjusting the screenpercentage directly in the editor, outside of the optimized DLSS quality modes. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config = Editor, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable Screenpercentage Manipulation in DLSS Editor Viewports")
bool bEnableScreenpercentageManipulationInDLSSEditorViewports = false;
/** This enables DLSS in play in editor viewports. This project wide setting can be locally overridden in in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable DLSS in Play In Editor viewports")
/** This enables DLSS/DLAA in play in editor viewports. This project wide setting can be locally overridden in in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable DLSS/DLAA in Play In Editor viewports")
bool bEnableDLSSInPlayInEditorViewports = true;
/** This enables on screen warnings and errors about DLSS. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings. */
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Show various DLSS on screen debug messages")
/** This enables on screen warnings and errors about DLSS/DLAA. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings. */
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Show various DLSS/DLAA on screen debug messages")
bool bShowDLSSSDebugOnScreenMessages = true;
/** This is part of the DLSS plugin and used by most projects*/
@@ -99,7 +90,7 @@ public:
UPROPERTY(VisibleAnywhere, Config, Category = "General Settings", DisplayName = "Exists")
bool bGenericDLSSBinaryExists;
/** By default the DLSS plugin uses the UE Project ID to initalize DLSS. In some cases NVIDIA might provide a separate NVIDIA Application ID, which should be put here. Please refer to https://developer.nvidia.com/dlss for details*/
/** By default the DLSS plugin uses the UE Project ID to initialize DLSS. In some cases NVIDIA might provide a separate NVIDIA Application ID, which should be put here. Please refer to https://developer.nvidia.com/dlss for details*/
UPROPERTY(Config, EditAnywhere, Category = "General Settings", DisplayName = "NVIDIA NGX Application ID", AdvancedDisplay)
uint32 NVIDIANGXApplicationId;
@@ -110,12 +101,3 @@ public:
bool bCustomDLSSBinaryExists;
};
// This is publically defined in the .Build.cs so it can key off branch names, which is not feasible to do with the preprocessor
#if DLSS_ENGINE_SUPPORTS_CSSPD
class FDLSSViewportQualitySetting final : public ICustomStaticScreenPercentageData
{
public:
int32 QualitySetting = 0;
bool bDLAAEnabled = false;
};
#endif
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
using UnrealBuildTool;
@@ -45,11 +36,9 @@ public class DLSSBlueprint : ModuleRules
);
// for ITemporalUpscaler in PostProcess/TemporalAA.h
PrivateIncludePaths.AddRange(
new string[] {
EngineDirectory + "/Source/Runtime/Renderer/Private",
// ... add other private include paths required here ...
Path.Combine(GetModuleDirectory("Renderer"), "Private"),
}
);
@@ -62,15 +51,14 @@ public class DLSSBlueprint : ModuleRules
PublicIncludePaths.AddRange(
new string[]
{
Path.Combine(ModuleDirectory, "../DLSS/Public"),
Path.Combine(GetModuleDirectory("DLSS"), "Public"),
}
);
PrivateIncludePaths.AddRange(
new string[]
{
Path.Combine(EngineDirectory,"Source/Runtime/Renderer/Private"),
Path.Combine(ModuleDirectory, "../DLSS/Private")
Path.Combine(GetModuleDirectory("DLSS"), "Private"),
}
);
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "DLSSLibrary.h"
@@ -32,18 +23,21 @@
#include "Interfaces/IPluginManager.h"
#include "ShaderCore.h"
#include UE_INLINE_GENERATED_CPP_BY_NAME(DLSSLibrary)
#define LOCTEXT_NAMESPACE "FDLSSBlueprintModule"
DEFINE_LOG_CATEGORY_STATIC(LogDLSSBlueprint, Log, All);
static TAutoConsoleVariable<int32> CVarNGXDLSSPreferNISSharpen(
TEXT("r.NGX.DLSS.PreferNISSharpen"),
2,
TEXT("Prefer sharpening with an extra NIS plugin sharpening pass instead of DLSS sharpening if the NIS plugin is also enabled for the project. (default: true)\n")
TEXT("Requires UE4.27.1 and the NIS plugin to be enabled, DLSS sharpening will be used otherwise \n")
TEXT("Prefer sharpening with an extra NIS plugin sharpening pass instead of DLSS sharpening if the NIS plugin is also enabled for the project. (default: 1)\n")
TEXT("Requires the NIS plugin to be enabled\n")
TEXT(" 0: Softening/sharpening with the DLSS pass.\n")
TEXT(" 1: Sharpen with the NIS plugin. Softening is not supported. Requires the NIS plugin to be enabled.\n")
TEXT(" 2: Sharpen with the NIS plugin. Softening (i.e. negative sharpness)with the DLSS plugin. Requires the NIS plugin to be enabled.\n")
TEXT("Note: This cvar is only evaluated when using the `SetDLSSSharpness` Blueprint function, from either C++ or a Blueprint event graph!"),
TEXT(" 2: Sharpen with the NIS plugin. Softening (i.e. negative sharpness) with the DLSS plugin. Requires the NIS plugin to be enabled.\n")
TEXT("Note: This cvar is only evaluated when using the deprecated `SetDLSSSharpness` Blueprint function, from either C++ or a Blueprint event graph!")
TEXT("Note: DLSS sharpening is deprecated, future plugin versions will remove DLSS sharpening. Use the NIS plugin for sharpening instead\n"),
ECVF_RenderThreadSafe);
static const FName SetDLSSModeInvalidEnumValueError= FName("SetDLSSModeInvalidEnumValueError");
@@ -178,7 +172,8 @@ bool UDLSSLibrary::IsDLSSModeSupported(UDLSSMode DLSSMode)
}
else if (DLSSMode == UDLSSMode::Auto)
{
return true;
// support for auto quality mode was dropped with UE 5.1
return false;
}
else
{
@@ -220,7 +215,7 @@ void UDLSSLibrary::GetDLSSModeInformation(UDLSSMode DLSSMode, FVector2D ScreenRe
bIsSupported = IsDLSSModeSupported(DLSSMode);
#if WITH_DLSS
if ((DLSSMode != UDLSSMode::Off) && bIsSupported)
if ((DLSSMode != UDLSSMode::Off) && bIsSupported || (DLSSMode == UDLSSMode::Auto))
{
EDLSSQualityMode EDLSSMode;
if (DLSSMode != UDLSSMode::Auto)
@@ -345,6 +340,60 @@ void UDLSSLibrary::GetDLSSMinimumDriverVersion(int32& MinDriverVersionMajor, int
#endif
}
void UDLSSLibrary::EnableDLSS(bool bEnabled)
{
#if WITH_DLSS
if (!TryInitDLSSLibrary())
{
UE_LOG(LogDLSSBlueprint, Error, TEXT("EnableDLSS should not be called before PostEngineInit"));
return;
}
const bool bDLSSSupported = (DLSSSupport == UDLSSSupport::Supported);
if (!bDLSSSupported)
{
return;
}
static IConsoleVariable* CVarDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Enable"));
if (CVarDLSSEnable)
{
CVarDLSSEnable->Set(bEnabled ? 1 : 0, ECVF_SetByCommandline);
// Spatial upscalers such as NIS might set this to 0, but we need r.TemporalAA.Upscaler to be 1 for DLSS to work.
// but we don't want to change the Cvar if DLSS is not active as to avoid impacting other code paths
// we don't need to set r.TemporalAA.Upsampling since r.TemporalAA.Upscaler implies that
if (bEnabled)
{
static const auto CVarTemporalAAUpscaler = IConsoleManager::Get().FindConsoleVariable(TEXT("r.TemporalAA.Upscaler"));
CVarTemporalAAUpscaler->Set(1, ECVF_SetByCommandline);
}
}
#endif
}
bool UDLSSLibrary::IsDLSSEnabled()
{
#if WITH_DLSS
if (!TryInitDLSSLibrary())
{
UE_LOG(LogDLSSBlueprint, Error, TEXT("IsDLSSEnabled should not be called before PostEngineInit"));
return false;
}
// if NGX library loading was disabled, DLSS will be unsupported
const bool bDLSSSupported = (DLSSSupport == UDLSSSupport::Supported);
static const IConsoleVariable* CVarDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Enable"));
const bool bDLSSEnabled = CVarDLSSEnable && (CVarDLSSEnable->GetInt() != 0);
return bDLSSSupported && bDLSSEnabled;
#else
return false;
#endif
}
// deprecated
void UDLSSLibrary::EnableDLAA(bool bEnabled)
{
#if WITH_DLSS
@@ -354,14 +403,12 @@ void UDLSSLibrary::EnableDLAA(bool bEnabled)
return;
}
static const auto CVarNGXEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.Enable"));
bool bNGXEnabled = CVarNGXEnable && (CVarNGXEnable->GetInt() != 0);
const bool bDLAASupported = (DLSSSupport == UDLSSSupport::Supported);
static auto CVarDLAAEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLAA.Enable"));
if (CVarDLAAEnable)
{
// r.NGX.Enable might be set to 0 via hotfix so disable DLAA too (in case it might come from saved settings)
bool bDLAAEnabled = bNGXEnabled && bEnabled;
bool bDLAAEnabled = bDLAASupported && bEnabled;
CVarDLAAEnable->Set(bDLAAEnabled, ECVF_SetByCommandline);
if (bDLAAEnabled)
{
@@ -373,6 +420,7 @@ void UDLSSLibrary::EnableDLAA(bool bEnabled)
#endif
}
// deprecated
bool UDLSSLibrary::IsDLAAEnabled()
{
#if WITH_DLSS
@@ -382,18 +430,18 @@ bool UDLSSLibrary::IsDLAAEnabled()
return false;
}
static const auto CVarNGXEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.Enable"));
const bool bNGXEnabled = CVarNGXEnable && (CVarNGXEnable->GetInt() != 0);
const bool bDLAASupported = (DLSSSupport == UDLSSSupport::Supported);
const bool bDLAAEnabled = (DLSSUpscaler != nullptr) && DLSSUpscaler->IsDLAAMode();
return bNGXEnabled && bDLAAEnabled;
return bDLAASupported && bDLAAEnabled;
#else
return false;
#endif
}
void UDLSSLibrary::SetDLSSMode(UDLSSMode DLSSMode)
// deprecated
void UDLSSLibrary::SetDLSSMode(UObject* WorldContextObject, UDLSSMode DLSSMode)
{
#if WITH_DLSS
if (!TryInitDLSSLibrary())
@@ -407,33 +455,41 @@ void UDLSSLibrary::SetDLSSMode(UDLSSMode DLSSMode)
// UEnums are strongly typed, but then one can also cast a byte to an UEnum ...
if(Enum->IsValidEnumValue(int64(DLSSMode)) && (Enum->GetMaxEnumValue() != int64(DLSSMode)))
{
static const auto CVarNGXEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.Enable"));
const bool bNGXEnabled = CVarNGXEnable && CVarNGXEnable->GetInt();
const bool bDLSSSupported = (DLSSSupport == UDLSSSupport::Supported);
static auto CVarDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Enable"));
if (CVarDLSSEnable)
TOptional<EDLSSQualityMode> MaybeQualityMode{};
if (bDLSSSupported)
{
// r.NGX.Enable might be set to 0 via hotfix so set r.NGX.DLSS.Enable to 0 too (in case it might come from saved settings)
const bool bDLSSEnabled = bNGXEnabled && (DLSSMode != UDLSSMode::Off);
CVarDLSSEnable->Set(bDLSSEnabled ? 1 : 0, ECVF_SetByCommandline);
// Spatial upscalers such as NIS might set this to 0, but we need r.TemporalAA.Upscaler to be 1 for DLSS to work.
// but we don't want to change the Cvar if DLSS is not active as to avoid impacting other code paths
// we don't need to set r.TemporalAA.Upsampling since r.TemporalAA.Upscaler implies that
if (bDLSSEnabled)
if ((DLSSMode != UDLSSMode::Off) && (DLSSMode != UDLSSMode::Auto))
{
static const auto CVarTemporalAAUpscaler = IConsoleManager::Get().FindConsoleVariable(TEXT("r.TemporalAA.Upscaler"));
CVarTemporalAAUpscaler->Set(1, ECVF_SetByCommandline);
MaybeQualityMode = ToEDLSSQualityMode(DLSSMode);
}
}
static auto CVarDLSSAutoQualityMode = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Quality.Auto"));
if (CVarDLSSAutoQualityMode)
static IConsoleVariable* CVarScreenPercentage = IConsoleManager::Get().FindConsoleVariable(TEXT("r.ScreenPercentage"));
if (MaybeQualityMode.IsSet() && DLSSUpscaler->IsQualityModeSupported(*MaybeQualityMode))
{
bool bIsAutoQualityMode = bNGXEnabled && (DLSSMode == UDLSSMode::Auto);
CVarDLSSAutoQualityMode->Set(bIsAutoQualityMode, ECVF_SetByCommandline);
// enable DLSS, and set screen percentage for backward compatibility with earlier plugin versions
float OptimalScreenPercentage = 100.0f * DLSSUpscaler->GetOptimalResolutionFractionForQuality(*MaybeQualityMode);
if (CVarScreenPercentage != nullptr)
{
EConsoleVariableFlags Priority = static_cast<EConsoleVariableFlags>(CVarScreenPercentage->GetFlags() & ECVF_SetByMask);
CVarScreenPercentage->Set(OptimalScreenPercentage, Priority);
}
EnableDLSS(true);
}
else
{
// disable DLSS, and set screen percentage to 100 for backward compatibility with earlier plugin versions
if (CVarScreenPercentage != nullptr)
{
EConsoleVariableFlags Priority = static_cast<EConsoleVariableFlags>(CVarScreenPercentage->GetFlags() & ECVF_SetByMask);
CVarScreenPercentage->Set(100.0f, Priority);
}
EnableDLSS(false);
}
// TODO: this cvar does nothing
static auto CVarDLSSQuality = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Quality"));
if (CVarDLSSQuality && (DLSSMode != UDLSSMode::Off) && (DLSSMode != UDLSSMode::Auto))
@@ -458,6 +514,7 @@ void UDLSSLibrary::SetDLSSMode(UDLSSMode DLSSMode)
#endif // WITH_DLSS
}
// deprecated
UDLSSMode UDLSSLibrary::GetDLSSMode()
{
#if WITH_DLSS
@@ -470,8 +527,7 @@ UDLSSMode UDLSSLibrary::GetDLSSMode()
static const auto CVarTemporalAAUpscaler = IConsoleManager::Get().FindConsoleVariable(TEXT("r.TemporalAA.Upscaler"));
const bool bTemporalUpscalerActive = CVarTemporalAAUpscaler && CVarTemporalAAUpscaler->GetInt() != 0;
static const auto CVarNGXEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.Enable"));
const bool bNGXEnabled = CVarNGXEnable && CVarNGXEnable->GetInt();
const bool bDLSSSupported = (DLSSSupport == UDLSSSupport::Supported);
static const auto CVarDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Enable"));
const bool bDLSSEnabled = CVarDLSSEnable && CVarDLSSEnable->GetInt();
@@ -488,11 +544,11 @@ UDLSSMode UDLSSLibrary::GetDLSSMode()
// DLSS is mutually exclusive with DLAA, DLAA wins
return UDLSSMode::Off;
}
else if (bTemporalUpscalerActive && bNGXEnabled && bDLSSEnabled && bIsAutoQualityMode)
else if (bTemporalUpscalerActive && bDLSSSupported && bDLSSEnabled && bIsAutoQualityMode)
{
return UDLSSMode::Auto;
}
else if (bTemporalUpscalerActive && bNGXEnabled && bDLSSEnabled && CVarDLSSQuality)
else if (bTemporalUpscalerActive && bDLSSSupported && bDLSSEnabled && CVarDLSSQuality)
{
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new enum values");
@@ -522,9 +578,10 @@ UDLSSMode UDLSSLibrary::GetDLSSMode()
}
#ifndef ENGINE_CAN_SUPPORT_NIS_PLUGIN
#define ENGINE_CAN_SUPPORT_NIS_PLUGIN (ENGINE_MAJOR_VERSION == 5 || (ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION ==27 && ENGINE_PATCH_VERSION >=1 ))
#define ENGINE_CAN_SUPPORT_NIS_PLUGIN 1
#endif
// deprecated
void UDLSSLibrary::SetDLSSSharpness(float Sharpness)
{
#if WITH_DLSS
@@ -567,6 +624,7 @@ void UDLSSLibrary::SetDLSSSharpness(float Sharpness)
#endif
}
// deprecated
float UDLSSLibrary::GetDLSSSharpness()
{
#if WITH_DLSS
@@ -624,7 +682,7 @@ UDLSSMode UDLSSLibrary::GetDefaultDLSSMode()
#endif
if (UDLSSLibrary::IsDLSSSupported())
{
return UDLSSMode::Auto;
return UDLSSMode::Quality;
}
else
{
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
@@ -53,7 +44,7 @@ UENUM(BlueprintType)
enum class UDLSSMode : uint8
{
Off UMETA(DisplayName = "Off"),
Auto UMETA(DisplayName = "Auto"),
Auto UMETA(DisplayName = "Auto", ToolTip = "Not a real quality mode. Use Auto to query best settings for a given resolution with GetDLSSModeInformation"),
UltraQuality UMETA(DisplayName = "Ultra Quality"),
Quality UMETA(DisplayName = "Quality"),
Balanced UMETA(DisplayName = "Balanced"),
@@ -80,12 +71,24 @@ public:
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Get DLSS Minimum DriverVersion"))
static DLSSBLUEPRINT_API void GetDLSSMinimumDriverVersion(int32& MinDriverVersionMajor, int32& MinDriverVersionMinor);
/**
* Enable/disable DLSS/DLAA
* To select a DLSS quality mode, set an appropriate upscale screen percentage with r.ScreenPercentage. Use GetDlssModeInformation to find optimal screen percentage
* To select DLAA, set the upscale screen percentage to 100 (r.ScreenPercentage=100)
*/
UFUNCTION(BlueprintCallable, Category = "DLSS", meta = (DisplayName = "Enable DLSS"))
static DLSSBLUEPRINT_API void EnableDLSS(bool bEnabled);
/** Checks whether DLSS/DLAA is enabled */
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Is DLSS Enabled"))
static DLSSBLUEPRINT_API bool IsDLSSEnabled();
/** Enable/disable DLAA. Note that while DLAA is enabled, DLSS will be automatically disabled */
UFUNCTION(BlueprintCallable, Category = "DLSS", meta = (DisplayName = "Enable DLAA"))
UFUNCTION(BlueprintCallable, Category = "DLSS", meta = (DisplayName = "Enable DLAA", DeprecatedFunction, DeprecationMessage = "Use EnableDLSS instead"))
static DLSSBLUEPRINT_API void EnableDLAA(bool bEnabled);
/** Checks whether DLAA is enabled */
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Is DLAA Enabled"))
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Is DLAA Enabled", DeprecatedFunction, DeprecationMessage = "Use IsDLSSEnabled instead"))
static DLSSBLUEPRINT_API bool IsDLAAEnabled();
/** Checks whether a DLSS mode is supported */
@@ -105,19 +108,19 @@ public:
static DLSSBLUEPRINT_API void GetDLSSScreenPercentageRange(float& MinScreenPercentage, float& MaxScreenPercentage);
/** Sets the console variables to enable/disable DLSS (r.NGX.DLSS.Enable, r.NGX.DLSS.Quality)*/
UFUNCTION(BlueprintCallable, Category = "DLSS", meta = (DisplayName = "Set DLSS Mode"))
static DLSSBLUEPRINT_API void SetDLSSMode(UDLSSMode DLSSMode);
UFUNCTION(BlueprintCallable, Category = "DLSS", meta=(WorldContext="WorldContextObject", DisplayName = "Set DLSS Mode", DeprecatedFunction, DeprecationMessage = "Use EnableDLSS instead"))
static DLSSBLUEPRINT_API void SetDLSSMode(UObject* WorldContextObject, UDLSSMode DLSSMode);
/* Reads the console variables to infer the current DLSS mode (r.NGX.DLSS.Enable, r.NGX.DLSS.Quality, r.TemporalAA.Upscaler)*/
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Get DLSS Mode"))
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Get DLSS Mode", DeprecatedFunction, DeprecationMessage = "Use IsDLSSEnabled instead"))
static DLSSBLUEPRINT_API UDLSSMode GetDLSSMode();
/* Sets the console variables to enable additional DLSS sharpening. Set to 0 to disable (r.NGX.DLSS.Sharpness) */
UFUNCTION(BlueprintCallable, Category = "DLSS", meta = (DisplayName = "Set DLSS Sharpness"))
UFUNCTION(BlueprintCallable, Category = "DLSS", meta = (DisplayName = "Set DLSS Sharpness", DeprecatedFunction, DeprecationMessage = "Use NIS sharpening instead"))
static DLSSBLUEPRINT_API void SetDLSSSharpness(float Sharpness);
/*Reads the console variables to infer the current DLSS sharpness (r.NGX.DLSS.Sharpness) */
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Get DLSS Sharpness"))
UFUNCTION(BlueprintPure, Category = "DLSS", meta = (DisplayName = "Get DLSS Sharpness", DeprecatedFunction, DeprecationMessage = "Use NIS sharpening instead"))
static DLSSBLUEPRINT_API float GetDLSSSharpness();
/* Find a reasonable default DLSS mode based on current hardware */
@@ -27,17 +27,14 @@ public class DLSSEditor : ModuleRules
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDirectory,"Source/Runtime/Renderer/Private"),
Path.Combine(EngineDirectory,"Source/Editor/LevelEditor/Private"),
Path.Combine(ModuleDirectory, "../DLSS/Private")
Path.Combine(GetModuleDirectory("DLSS"), "Private"),
Path.Combine(GetModuleDirectory("Renderer"), "Private"),
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"DLSS",
}
);
@@ -47,38 +44,12 @@ public class DLSSEditor : ModuleRules
"Core",
"CoreUObject",
"Engine",
"RenderCore",
"Renderer",
"RHI",
"Settings",
"LevelEditor",
"ToolMenus",
"Slate",
"SlateCore",
"EditorWidgets",
"EditorStyle",
"InputCore",
"UnrealEd",
"Projects",
"NGX",
"DLSS",
"NGXRHI",
}
);
// We can't quite check whether we have CL 16509387 (in UE5-Release) so we do this in a round about way
bool bUseSlotsArgumentsAPI = (Target.Version.MajorVersion == 5) && (Target.Version.BranchName != "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("USE_SLOT_SLOT_ARGUMENTS_API={0}", bUseSlotsArgumentsAPI ? "1" : "0"));
// We can't quite check whether we have CL 16848904 (in UE5-Main) so we do this in a round about way
bool bSupportsPostProcessingScreenPercentage = (Target.Version.MajorVersion == 4) ||
((Target.Version.MajorVersion == 5) && (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess"))
;
PrivateDefinitions.Add(string.Format("SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE={0}", bSupportsPostProcessingScreenPercentage ? "1" : "0"));
// 4.x and early access 5.0 engines had GTemporalUpscaler interface
bool bEngineHasGTemporalUpscaler = (Target.Version.MajorVersion == 4) || (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("DLSS_ENGINE_HAS_GTEMPORALUPSCALER={0}", bEngineHasGTemporalUpscaler ? "1" : "0"));
}
}
@@ -21,7 +21,6 @@
#include "DLSSEditor.h"
#include "DLSSUpscaler.h"
#include "DLSSUpscalerEditor.h"
#include "DLSS.h"
#include "DLSSSettings.h"
#include "NGXRHI.h"
@@ -50,14 +49,6 @@ void FDLSSEditorModule::StartupModule()
UE_LOG(LogDLSSEditor, Log, TEXT("DLSS module %p, QueryDLSSSupport = %u DLSSUpscaler = %p"), DLSSModule, DLSSModule->QueryDLSSSupport(), DLSSModule->GetDLSSUpscaler());
bIsDLSSAvailable = DLSSModule->QueryDLSSSupport() == EDLSSSupport::Supported;
if (bIsDLSSAvailable)
{
checkf(GCustomStaticScreenPercentage == DLSSModule->GetDLSSUpscaler(),TEXT("GCustomStaticScreenPercentage is not set to the DLSS upscaler. Please check that only one upscaling plugin is active."));
DLSSUpscalerEditor = MakeShared<FDLSSUpscalerEditor>(DLSSModule->GetDLSSUpscaler());
checkf(GCustomEditorStaticScreenPercentage == nullptr, TEXT("GCustomEditorStaticScreenPercentage is already in use. Please check that only one upscaling active is active."));
GCustomEditorStaticScreenPercentage = DLSSUpscalerEditor.Get();
}
}
// register settings
@@ -104,20 +95,9 @@ void FDLSSEditorModule::ShutdownModule()
{
UE_LOG(LogDLSSEditor, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
if (bIsDLSSAvailable)
{
GCustomEditorStaticScreenPercentage = nullptr;
DLSSUpscalerEditor = nullptr;
}
UE_LOG(LogDLSSEditor, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
FDLSSUpscalerEditor* FDLSSEditorModule::GetDLSSUpscalerEditor() const
{
return DLSSUpscalerEditor.Get();
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FDLSSEditorModule, DLSSEditor)
@@ -1,549 +0,0 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "DLSSUpscalerEditor.h"
#include "DLSSUpscaler.h"
#include "LegacyScreenPercentageDriver.h"
#include "DLSSSettings.h"
#include "Editor.h"
#include "SLevelViewportToolBar.h"
#include "ToolMenus.h"
#include "Widgets/Layout/SBox.h"
#include "Widgets/Input/SSpinBox.h"
#include "Framework/Commands/Commands.h"
#include "ISettingsModule.h"
#include "ISettingsSection.h"
#include "UObject/Class.h"
#include "UObject/WeakObjectPtr.h"
#include "Widgets/SBoxPanel.h"
#include "Widgets/SNullWidget.h"
#include "Styling/SlateTypes.h"
#include "Widgets/Layout/SBorder.h"
#include "Widgets/Text/STextBlock.h"
#include "Widgets/Input/SButton.h"
#include "Widgets/Input/SCheckBox.h"
#include "Widgets/Input/SSlider.h"
#include "Widgets/Layout/SGridPanel.h"
#include "EditorStyleSet.h"
#include "Editor.h"
#include "Settings/EditorSettings.h"
#include "Editor/EditorPerformanceSettings.h"
#define LOCTEXT_NAMESPACE "FDLSSEditorModule"
// We can't quite check whether we have CL 16509387 in UE5-Release-5.0 so we do this in a round about way by branch name
// We also can't do a preprocessor string compare in C++ so we resolve this in DLSSEditor.Build.cs;
#ifndef USE_SLOT_SLOT_ARGUMENTS_API
#define USE_SLOT_SLOT_ARGUMENTS_API 1
#endif
// We can't quite check whether we have CL 16848904 (in UE5-Main) so we do this in a round about way
#ifndef SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
#define SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE 1
#endif
// DLSS_TODO move the implementation of this to FDLSSUpscalerEditor?
class DLSSEDITOR_API SDLSSSettings : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SDLSSSettings)
{}
SLATE_ARGUMENT(FDLSSUpscalerEditor*, UpscalerEditor)
SLATE_ARGUMENT(ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments,ViewportMenuEntryArguments)
SLATE_END_ARGS()
// Widget construction
void Construct(const FArguments& InArgs);
~SDLSSSettings();
private:
// Makes a general quality level header button widget
TSharedRef<SWidget> MakeHeaderButtonWidget(const FText& InName, EDLSSQualityMode InQualityLevel, const FText& InToolTip);
// Callback for when a quality level header button is pressed
FReply OnHeaderClicked(EDLSSQualityMode InQualityLevel);
// Create a gridslot for the group quality level with all the required formatting
#if USE_SLOT_SLOT_ARGUMENTS_API
SGridPanel::FSlot::FSlotArguments MakeGridSlot(int32 InCol, int32 InRow, int32 InColSpan = 1, int32 InRowSpan = 1);
#else
SGridPanel::FSlot& MakeGridSlot(int32 InCol, int32 InRow, int32 InColSpan = 1, int32 InRowSpan = 1);
#endif
private:
FDLSSUpscalerEditor* UpscalerEditor;
ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments ViewportMenuEntryArguments;
};
TSharedRef<SWidget> SDLSSSettings::MakeHeaderButtonWidget(const FText& InName, EDLSSQualityMode InQualityLevel, const FText& InToolTip)
{
return SNew(SButton)
.OnClicked(this, &SDLSSSettings::OnHeaderClicked, InQualityLevel)
.ToolTipText(InToolTip)
.Content()
[
SNew(STextBlock)
.Text(InName)
];
}
FReply SDLSSSettings::OnHeaderClicked(EDLSSQualityMode InQualityLevel)
{
UE_LOG(LogDLSSEditor, Log, TEXT("%s InQualityLevel = %d"), ANSI_TO_TCHAR(__FUNCTION__), InQualityLevel);
if (InQualityLevel != EDLSSQualityMode::NumValues)
{
const int32 ScreenPercentage = UpscalerEditor->DLSSUpscaler->GetOptimalResolutionFractionForQuality(InQualityLevel) * 100.0f;
UpscalerEditor->OnQualityModeSelected(InQualityLevel, ViewportMenuEntryArguments);
UpscalerEditor->OnScreenPercentageValueChanged(ScreenPercentage, ViewportMenuEntryArguments);
UpscalerEditor->OnSetPreviewCustomTemporalUpscaler(true, ViewportMenuEntryArguments);
}
else
{
UpscalerEditor->OnSetPreviewCustomTemporalUpscaler(false, ViewportMenuEntryArguments);
}
return FReply::Handled();
}
#if USE_SLOT_SLOT_ARGUMENTS_API
SGridPanel::FSlot::FSlotArguments SDLSSSettings::MakeGridSlot(int32 InCol, int32 InRow, int32 InColSpan /*= 1*/, int32 InRowSpan /*= 1*/)
{
float PaddingH = 2.0f;
float PaddingV = InRow == 0 ? 8.0f : 2.0f;
return MoveTemp(SGridPanel::Slot(InCol, InRow)
.Padding(PaddingH, PaddingV)
.RowSpan(InRowSpan)
.ColumnSpan(InColSpan));
}
#else
SGridPanel::FSlot& SDLSSSettings::MakeGridSlot(int32 InCol, int32 InRow, int32 InColSpan /*= 1*/, int32 InRowSpan /*= 1*/)
{
float PaddingH = 2.0f;
float PaddingV = InRow == 0 ? 8.0f : 2.0f;
return SGridPanel::Slot(InCol, InRow)
.Padding(PaddingH, PaddingV)
.RowSpan(InRowSpan)
.ColumnSpan(InColSpan);
}
#endif
void SDLSSSettings::Construct(const FArguments& InArgs)
{
this->UpscalerEditor = InArgs._UpscalerEditor;
this->ViewportMenuEntryArguments = InArgs._ViewportMenuEntryArguments;
auto TitleFont = FEditorStyle::GetFontStyle(TEXT("MenuItem.Font"));
static float QualityColumnCoeff = 1.0f;
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new enum values");
auto MakeWidget = [this](EDLSSQualityMode QualityMode, const FText& InName, const FText& InToolTip)
{
const bool bSupported = UpscalerEditor->DLSSUpscaler->IsQualityModeSupported(QualityMode);
if (!bSupported)
{
return SNullWidget::NullWidget;
}
else
{
return MakeHeaderButtonWidget(InName, QualityMode, InToolTip);
}
};
TSharedRef<SGridPanel> ButtonMatrix =
SNew(SGridPanel)
.FillColumn(0, QualityColumnCoeff)
+ MakeGridSlot(0, 0).VAlign(VAlign_Center)[SNew(STextBlock).Text(LOCTEXT("DLSSModeLabel" , "DLSS Mode")).Font(TitleFont)]
+ MakeGridSlot(1, 0)[MakeHeaderButtonWidget(LOCTEXT("DLSSModeOffLabel", "Off"), EDLSSQualityMode::NumValues, LOCTEXT("DLSSModeOff" , "Turn DLSS off and use built-in TAA"))]
+ MakeGridSlot(2, 0)[MakeWidget(EDLSSQualityMode::UltraQuality, LOCTEXT("DLSSModeUltraQualityLabel", "Ultra Quality"), LOCTEXT("DLSSModeUltraQuality", "Set DLSS mode to Ultra Quality"))]
+ MakeGridSlot(3, 0)[MakeWidget(EDLSSQualityMode::Quality, LOCTEXT("DLSSModeQualityLabel", "Quality"), LOCTEXT("DLSSModeQuality", "Set DLSS mode to Quality"))]
+ MakeGridSlot(4, 0)[MakeWidget(EDLSSQualityMode::Balanced, LOCTEXT("DLSSModeBalancedLabel", "Balanced"), LOCTEXT("DLSSModeBalanced", "Set DLSS mode to Balanced"))]
+ MakeGridSlot(5, 0)[MakeWidget(EDLSSQualityMode::Performance, LOCTEXT("DLSSModePerformanceLabel", "Performance"), LOCTEXT("DLSSModePerformance", "Set DLSS mode to Performance"))]
+ MakeGridSlot(6, 0)[MakeWidget(EDLSSQualityMode::UltraPerformance, LOCTEXT("DLSSModeUltraPerformanceLabel", "Ultra Performance"), LOCTEXT("DLSSModeUltraPerformance", "Set DLSS mode to Ultra Performance"))];
this->ChildSlot
.HAlign(EHorizontalAlignment::HAlign_Fill)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
[
ButtonMatrix
]
];
}
SDLSSSettings::~SDLSSSettings()
{
}
static void MakeDLSSQualitySettingsMenu(UToolMenu* InMenu, FDLSSUpscalerEditor* DLSSUpscalerEditor, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments)
{
{
FToolMenuSection& Section = InMenu->AddSection("Section");
Section.AddEntry(FToolMenuEntry::InitWidget("DLSSQualitySettings", SNew(SDLSSSettings).UpscalerEditor(DLSSUpscalerEditor).ViewportMenuEntryArguments(Arguments), FText(), true));
}
}
class DLSSEDITOR_API FFDLSSEditorViewportClientData final : public FEditorViewportClient::ICustomTemporalUpscalerData
{
public:
bool bIsDLSSEnabled;
float ResolutionFraction;
EDLSSQualityMode DLSSQualityMode = EDLSSQualityMode::NumValues;
float MinResolutionFraction = 0.0f;
float MaxResolutionFraction = 1.0f;
bool bIsFixedResolutionFraction = false;
};
TSharedPtr<FFDLSSEditorViewportClientData> FDLSSUpscalerEditor::GetOrCreateDLSSViewportData(FEditorViewportClient* ViewportClient)
{
check(ViewportClient);
TSharedPtr<FEditorViewportClient::ICustomTemporalUpscalerData> CustomData = ViewportClient->GetCustomTemporalUpscalerData();
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData;
if (CustomData)
{
DLSSViewportData = StaticCastSharedPtr<FFDLSSEditorViewportClientData>(CustomData);
check(DLSSViewportData);
}
else
{
DLSSViewportData = MakeShared< FFDLSSEditorViewportClientData>();
ViewportClient->SetCustomTemporalUpscalerData(DLSSViewportData);
}
return DLSSViewportData;
}
FDLSSUpscalerEditor::FDLSSUpscalerEditor(FDLSSUpscaler* InDLSSUpscaler)
: DLSSUpscaler(InDLSSUpscaler)
{
}
FDLSSUpscalerEditor::~FDLSSUpscalerEditor()
{
UE_LOG(LogDLSSEditor, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSSEditor, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
void FDLSSUpscalerEditor::SetupEditorViewFamily(FSceneViewFamily& ViewFamily, FEditorViewportClient* ViewportClient)
{
// this purpusefully does not check "r.TemporalAA.Upscaler", which is used at runtime since the enable/disable comes from DLSSViewportData->bIsDLSSEnabled
// however make sure that the upscaler is "ours"
static const auto CVarDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Enable"));
const bool bDLSSActive = CVarDLSSEnable && (CVarDLSSEnable->GetInt() != 0);
static const auto CVarDLSSAutomationTesting = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.AutomationTesting"));
const bool bDLSSActiveWithAutomation = !GIsAutomationTesting || (GIsAutomationTesting && CVarDLSSAutomationTesting && (CVarDLSSAutomationTesting->GetInt() != 0));
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
if ((GTemporalUpscaler == DLSSUpscaler) && bDLSSActive && bDLSSActiveWithAutomation)
#else
if (bDLSSActive && bDLSSActiveWithAutomation)
#endif
{
check(GIsEditor);
checkf(GCustomStaticScreenPercentage == DLSSUpscaler, TEXT("GCustomStaticScreenPercentage is not set to the DLSS upscaler. Please check that only one upscaling plugin is active."));
checkf(GCustomEditorStaticScreenPercentage == this, TEXT("GCustomEditorStaticScreenPercentage is not set to the DLSS upscaler. Please check that only one upscaling plugin is active."));
check(ViewportClient);
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(ViewportClient);
if(DLSSViewportData->bIsDLSSEnabled && EnableDLSSInEditorViewports())
{
ViewFamily.SetTemporalUpscalerInterface(DLSSUpscaler->GetUpscalerInstanceForViewFamily(DLSSUpscaler, DLSSViewportData->DLSSQualityMode));
// DLSS_TODO figure out what to do, should this ever be the case
checkf(ViewFamily.GetScreenPercentageInterface() == nullptr, TEXT("ViewFamily.GetScreenPercentageInterface() is already in use. Please check that only one upscaling plugin active is active."));
ViewFamily.EngineShowFlags.ScreenPercentage = true;
const float ResolutionFraction = DLSSViewportData->ResolutionFraction;
ViewFamily.SetScreenPercentageInterface(new FLegacyScreenPercentageDriver(
ViewFamily, ResolutionFraction
#if SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
/* AllowPostProcessSettingsScreenPercentage = */, false
#endif
));
}
}
}
bool FDLSSUpscalerEditor::GenerateEditorViewportOptionsMenuEntry(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments& Arguments)
{
// this purpusefully does not check "r.TemporalAA.Upscaler", which is used at runtime since the enable/disable comes from DLSSViewportData->bIsDLSSEnabled
// however make sure that the upscaler is "ours"
static const auto CVarDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.DLSS.Enable"));
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
if ((GTemporalUpscaler == DLSSUpscaler) && CVarDLSSEnable && (CVarDLSSEnable->GetInt() != 0))
#else
if (CVarDLSSEnable && (CVarDLSSEnable->GetInt() != 0))
#endif
{
check(GIsEditor);
checkf(GCustomStaticScreenPercentage == DLSSUpscaler, TEXT("GCustomStaticScreenPercentage is not set to the DLSS upscaler. Please check that only one upscaling plugin is active."));
checkf(GCustomEditorStaticScreenPercentage == this, TEXT("GCustomEditorStaticScreenPercentage is not set to the DLSS upscaler. Please check that only one upscaling plugin is active."));
FLevelEditorViewportClient& Levelviewport = Arguments.Viewport->GetLevelViewportClient();
FEngineShowFlags ShowFlags = Levelviewport.EngineShowFlags;
// DLSS_TODO is there a better way to detect whether TAA (and thus DLSS) is turned off?
// maybe pass this in as a flag or have the callsite do this
// FEditorViewportClient::Draw calls EngineShowFlagOrthographicOverride(IsPerspective(), ViewFamily.EngineShowFlags); which turns TAA off. And DLSS is a TAA flavor
// EngineShowFlags.TemporalAA = 0;
// EngineShowFlags.MotionBlur = 0;
// but that well only be called later so emulate this here.
if (!ShowFlags.Lighting)
{
return false;
}
if (!Levelviewport.IsPerspective())
{
return false;
}
if (!EnableDLSSInEditorViewports())
{
return false;
}
const bool bUseSubmenuForDLSSSettings = true;
if(bUseSubmenuForDLSSSettings)
{
Arguments.Section->AddSubMenu(
"DLSSSettings",
LOCTEXT("DLSSSettingsSubMenu", "DLSS Settings"),
LOCTEXT("DLSSSettingsSubMenu_ToolTip", "Open the DLSS settings"),
FNewToolMenuDelegate::CreateStatic(&MakeDLSSQualitySettingsMenu, this, Arguments));
}
else
{
Arguments.Section->AddEntry(FToolMenuEntry::InitWidget("DLSSSettings", SNew(SDLSSSettings).UpscalerEditor(this).ViewportMenuEntryArguments(Arguments), FText(), true));
}
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&Arguments.Viewport->GetLevelViewportClient());
if (DLSSViewportData->bIsDLSSEnabled)
{
Arguments.Section->AddEntry(FToolMenuEntry::InitWidget("DLSSScreenPercentage", GenerateScreenPercentageMenu(Arguments), LOCTEXT("DLSSScreenPercentage", "Screen Percentage (DLSS)")));
const int32 PreviewScreenPercentageMin = DLSSViewportData->MinResolutionFraction * 100.0f;
const int32 PreviewScreenPercentageMax = DLSSViewportData->MaxResolutionFraction * 100.0f;
// clamp the current preview screen percentage (which might be 100%) to the supported DLSS range
this->OnScreenPercentageValueChanged(FMath::Clamp(this->OnGetScreenPercentageValue(Arguments), PreviewScreenPercentageMin, PreviewScreenPercentageMax), Arguments);
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
TSharedRef<SWidget> FDLSSUpscalerEditor::GenerateScreenPercentageMenu(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments& Arguments) const
{
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&Arguments.Viewport->GetLevelViewportClient());
const int32 PreviewScreenPercentageMin = DLSSViewportData->MinResolutionFraction * 100.0f;
const int32 PreviewScreenPercentageMax = DLSSViewportData->MaxResolutionFraction * 100.0f;
#if ENGINE_MAJOR_VERSION==4
return
SNew(SBox)
.HAlign(HAlign_Right)
.IsEnabled(this, &FDLSSUpscalerEditor::OnScreenPercentageIsEnabled, Arguments)
[
SNew(SBox)
.Padding(FMargin(4.0f, 0.0f, 0.0f, 0.0f))
.WidthOverride(100.0f)
[
SNew(SSpinBox<int32>)
.Font(FEditorStyle::GetFontStyle(TEXT("MenuItem.Font")))
.MinValue(PreviewScreenPercentageMin)
.MaxValue(PreviewScreenPercentageMax)
.Value(this, &FDLSSUpscalerEditor::OnGetScreenPercentageValue, Arguments)
.OnValueChanged(this, &FDLSSUpscalerEditor::OnScreenPercentageValueChanged, Arguments)
.ToolTipText(
DLSSViewportData->bIsFixedResolutionFraction ?
FText(LOCTEXT("DLSSScreenPercentageTooltipFixedResolution", "This DLSS quality mode has a fixed screen percentage and cannot be adjusted at runtime.")) :
FText( LOCTEXT("DLSSScreenPercentageTooltip",
"At runtime, the screen percentage is controlled by the r.NGX.DLSS.Quality cvar. To enable adjusting the screenpercentage directly in the editor, set the \"Enable Screenpercentage Manipulation In DLSS Editor Viewports\" setting under Editor Preferences -> Plugins -> NVIDIA DLSS"))
)
]
];
#elif ENGINE_MAJOR_VERSION==5
return
SNew(SBox)
.HAlign(HAlign_Right)
.IsEnabled(this, &FDLSSUpscalerEditor::OnScreenPercentageIsEnabled, Arguments)
[
SNew(SBox)
.Padding(FMargin(4.0f, 0.0f, 0.0f, 0.0f))
.WidthOverride(100.0f)
[
SNew(SBorder)
.BorderImage(FAppStyle::Get().GetBrush("Menu.WidgetBorder"))
.Padding(FMargin(1.0f))
[
SNew(SSpinBox<int32>)
.Style(&FAppStyle::Get(), "Menu.SpinBox")
.Font(FEditorStyle::GetFontStyle(TEXT("MenuItem.Font")))
.MinValue(PreviewScreenPercentageMin)
.MaxValue(PreviewScreenPercentageMax)
.Value(this, &FDLSSUpscalerEditor::OnGetScreenPercentageValue, Arguments)
.OnValueChanged(this, &FDLSSUpscalerEditor::OnScreenPercentageValueChanged, Arguments)
.ToolTipText(
DLSSViewportData->bIsFixedResolutionFraction ?
FText(LOCTEXT("DLSSScreenPercentageTooltipFixedResolution", "This DLSS quality mode has a fixed screen percentage and cannot be adjusted at runtime.")) :
FText(LOCTEXT("DLSSScreenPercentageTooltip",
"At runtime, the screen percentage is controlled by the r.NGX.DLSS.Quality cvar. To enable adjusting the screenpercentage directly in the editor, set the \"Enable Screenpercentage Manipulation In DLSS Editor Viewports\" setting under Editor Preferences -> Plugins -> NVIDIA DLSS"))
)
]
]
];
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
}
bool FDLSSUpscalerEditor::EnableScreenpercentageInEditorViewports() const
{
if (GetDefault<UDLSSOverrideSettings>()->EnableScreenpercentageManipulationInDLSSEditorViewportsOverride == EDLSSSettingOverride::UseProjectSettings)
{
return GetDefault<UDLSSSettings>()->bEnableScreenpercentageManipulationInDLSSEditorViewports;
}
else
{
return GetDefault<UDLSSOverrideSettings>()->EnableScreenpercentageManipulationInDLSSEditorViewportsOverride == EDLSSSettingOverride::Enabled;
}
}
bool FDLSSUpscalerEditor::EnableDLSSInEditorViewports() const
{
if (GetDefault<UDLSSOverrideSettings>()->EnableDLSSInEditorViewportsOverride == EDLSSSettingOverride::UseProjectSettings)
{
return GetDefault<UDLSSSettings>()->bEnableDLSSInEditorViewports;
}
else
{
return GetDefault<UDLSSOverrideSettings>()->EnableDLSSInEditorViewportsOverride == EDLSSSettingOverride::Enabled;
}
}
bool FDLSSUpscalerEditor::OnScreenPercentageIsEnabled(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const
{
check(DLSSUpscaler);
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&Arguments.Viewport->GetLevelViewportClient());
// adapted from SLevelViewportToolBar::OnScreenPercentageIsEnabled()
return EnableScreenpercentageInEditorViewports() && !DLSSViewportData->bIsFixedResolutionFraction && Arguments.Viewport->GetLevelViewportClient().SupportsPreviewResolutionFraction();
}
int32 FDLSSUpscalerEditor::OnGetScreenPercentageValue(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const
{
// adapted from SLevelViewportToolBar::OnGetScreenPercentageValue(), using DLSSViewportData->ResolutionFraction
// We expose the resolution fraction derived from DPI, to not lie to the artist when screen percentage = 100%.
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&Arguments.Viewport->GetLevelViewportClient());
return FMath::RoundToInt(FMath::Clamp(
DLSSViewportData->ResolutionFraction,
DLSSViewportData->MinResolutionFraction,
DLSSViewportData->MaxResolutionFraction) * 100.0f);
}
void FDLSSUpscalerEditor::OnScreenPercentageValueChanged(int32 NewValue, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const
{
// adapted from SLevelViewportToolBar::OnScreenPercentageValueChanged() and SetPreviewScreenPercentage()
FLevelEditorViewportClient& ViewportClient = Arguments.Viewport->GetLevelViewportClient();
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&ViewportClient);
DLSSViewportData->ResolutionFraction = (NewValue / 100.0f);
ViewportClient.Invalidate();
}
bool FDLSSUpscalerEditor::OnGetPreviewCustomTemporalUpscaler(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const
{
return GetOrCreateDLSSViewportData(&Arguments.Viewport->GetLevelViewportClient())->bIsDLSSEnabled;
}
void FDLSSUpscalerEditor::OnSetPreviewCustomTemporalUpscaler(bool NewValue, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const
{
FLevelEditorViewportClient& ViewportClient = Arguments.Viewport->GetLevelViewportClient();
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&ViewportClient);
DLSSViewportData->bIsDLSSEnabled = NewValue;
ViewportClient.Invalidate();
}
void FDLSSUpscalerEditor::OnPreviewCustomTemporalUpscalerChanged(bool NewValue, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const
{
FLevelEditorViewportClient& ViewportClient = Arguments.Viewport->GetLevelViewportClient();
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&ViewportClient);
DLSSViewportData->bIsDLSSEnabled = NewValue;
ViewportClient.Invalidate();
}
void FDLSSUpscalerEditor::OnQualityModeSelected(EDLSSQualityMode InQualityLevel, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments)
{
TSharedPtr<FFDLSSEditorViewportClientData> DLSSViewportData = GetOrCreateDLSSViewportData(&Arguments.Viewport->GetLevelViewportClient());
DLSSViewportData->bIsFixedResolutionFraction = DLSSUpscaler->IsFixedResolutionFraction(InQualityLevel);
DLSSViewportData->DLSSQualityMode = InQualityLevel;
if (DLSSViewportData->bIsFixedResolutionFraction)
{
DLSSViewportData->MinResolutionFraction = DLSSUpscaler->GetOptimalResolutionFractionForQuality(InQualityLevel);
DLSSViewportData->MaxResolutionFraction = DLSSUpscaler->GetOptimalResolutionFractionForQuality(InQualityLevel);
}
else
{
DLSSViewportData->MinResolutionFraction = DLSSUpscaler->GetMinUpsampleResolutionFraction();
DLSSViewportData->MaxResolutionFraction = DLSSUpscaler->GetMaxUpsampleResolutionFraction();
}
}
#undef LOCTEXT_NAMESPACE
@@ -1,37 +1,21 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
#include "Modules/ModuleManager.h"
DECLARE_LOG_CATEGORY_EXTERN(LogDLSSEditor, Log, All);
class FDLSSUpscalerEditor;
class IDLSSEditorModuleInterface : public IModuleInterface
{
public:
virtual FDLSSUpscalerEditor* GetDLSSUpscalerEditor() const = 0;
};
class FDLSSEditorModule final : public IDLSSEditorModuleInterface
class FDLSSEditorModule final : public IModuleInterface
{
public:
@@ -39,11 +23,7 @@ public:
virtual void StartupModule() final;
virtual void ShutdownModule() final;
// Inherited via IDLSSEditorModuleInterface
virtual FDLSSUpscalerEditor* GetDLSSUpscalerEditor() const ;
private:
TSharedPtr<FDLSSUpscalerEditor> DLSSUpscalerEditor;
bool bIsDLSSAvailable = false;
};
@@ -1,70 +0,0 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#pragma once
#include "CustomEditorStaticScreenPercentage.h"
DECLARE_LOG_CATEGORY_EXTERN(LogDLSSEditor, Log, All);
class FDLSSUpscaler;
enum class EDLSSQualityMode;
class SWidget;
class SLevelViewportToolBar;
class SDLSSSettings;
class FFDLSSEditorViewportClientData;
class FEditorViewportClient;
class DLSSEDITOR_API FDLSSUpscalerEditor : public TSharedFromThis<FDLSSUpscalerEditor>, public ICustomEditorStaticScreenPercentage
{
friend class SDLSSSettings;
public:
FDLSSUpscalerEditor(FDLSSUpscaler* InDLSSUpscaler);
virtual ~FDLSSUpscalerEditor();
// Inherited via ICustomEditorStaticScreenPercentage
virtual bool GenerateEditorViewportOptionsMenuEntry(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments& Arguments) final;
virtual void SetupEditorViewFamily(FSceneViewFamily& ViewFamily, FEditorViewportClient* ViewportClient) final;
private:
bool OnScreenPercentageIsEnabled(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const;
int32 OnGetScreenPercentageValue(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const;
void OnScreenPercentageValueChanged(int32 NewValue, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const;
bool OnGetPreviewCustomTemporalUpscaler(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const;
void OnSetPreviewCustomTemporalUpscaler(bool NewValue, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const;
void OnPreviewCustomTemporalUpscalerChanged(bool NewValue, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments) const;
bool EnableScreenpercentageInEditorViewports() const;
bool EnableDLSSInEditorViewports() const;
TSharedRef<SWidget> GenerateScreenPercentageMenu(const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments& Arguments) const;
FDLSSUpscaler* DLSSUpscaler;
void OnQualityModeSelected(EDLSSQualityMode InQualityLevel, const ICustomEditorStaticScreenPercentage::FViewportMenuEntryArguments Arguments);
static TSharedPtr<FFDLSSEditorViewportClientData> GetOrCreateDLSSViewportData(FEditorViewportClient* ViewportClient);
};
@@ -25,7 +25,7 @@ public class DLSSUtility : ModuleRules
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDirectory,"Source/Runtime/Renderer/Private"),
Path.Combine(GetModuleDirectory("Renderer"), "Private"),
}
);
@@ -36,7 +36,6 @@ public class DLSSUtility : ModuleRules
"Core",
"RenderCore",
"Renderer",
}
);
@@ -49,9 +48,5 @@ public class DLSSUtility : ModuleRules
"Projects"
}
);
// 4.x and early access 5.0 engines used FVector2D type instead of FVector2f type for shader parameters
bool bEngineUsesFVector2D = (Target.Version.MajorVersion == 4) || (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("DLSS_ENGINE_USES_FVECTOR2D={0}", bEngineUsesFVector2D ? "1" : "0"));
}
}
@@ -10,6 +10,7 @@
*/
#include "VelocityCombinePass.h"
#include "Runtime/Launch/Resources/Version.h"
const int32 kVelocityCombineComputeTileSizeX = FComputeShaderUtils::kGolden2DGroupSize;
@@ -27,12 +28,7 @@ public:
return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5) &&
IsPCPlatform(Parameters.Platform) && (
IsVulkanSM5Platform(Parameters.Platform) ||
#if (ENGINE_MAJOR_VERSION == 4) && (ENGINE_MINOR_VERSION == 26)
IsD3DPlatform(Parameters.Platform, false));
#else
IsD3DPlatform(Parameters.Platform));
#endif
}
static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
@@ -55,11 +51,7 @@ public:
SHADER_PARAMETER_RDG_TEXTURE(Texture2D, DepthTexture)
SHADER_PARAMETER_SAMPLER(SamplerState, DepthTextureSampler)
#if DLSS_ENGINE_USES_FVECTOR2D
SHADER_PARAMETER(FVector2D, TemporalJitterPixels)
#else
SHADER_PARAMETER(FVector2f, TemporalJitterPixels)
#endif
SHADER_PARAMETER_STRUCT_REF(FViewUniformShaderParameters, View)
@@ -124,12 +116,7 @@ FRDGTextureRef AddVelocityCombinePass(
// various state
{
#if ENGINE_MAJOR_VERSION < 5
PassParameters->TemporalJitterPixels = View.TemporalJitterPixels;
#else
PassParameters->TemporalJitterPixels = FVector2f(View.TemporalJitterPixels); // LWC_TODO: Precision loss
#endif
PassParameters->View = View.ViewUniformBuffer;
}
@@ -1,28 +1,16 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
using UnrealBuildTool;
using System.IO;
public class NGXD3D11RHI : ModuleRules
{
public NGXD3D11RHI(ReadOnlyTargetRules Target) : base(Target)
@@ -37,8 +25,6 @@ public class NGXD3D11RHI : ModuleRules
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDirectory,"Source/Runtime/Windows/D3D11RHI/Private"),
Path.Combine(EngineDirectory,"Source/Runtime/Windows/D3D11RHI/Private/Windows"),
}
);
@@ -64,16 +50,7 @@ public class NGXD3D11RHI : ModuleRules
}
);
if (ReadOnlyBuildVersion.Current.MajorVersion == 5)
{
PrivateDependencyModuleNames.Add("RHICore");
}
// those come from the D3D11RHI
AddEngineThirdPartyPrivateStaticDependencies(Target, "DX11");
AddEngineThirdPartyPrivateStaticDependencies(Target, "NVAPI");
AddEngineThirdPartyPrivateStaticDependencies(Target, "NVAftermath");
AddEngineThirdPartyPrivateStaticDependencies(Target, "IntelMetricsDiscovery");
AddEngineThirdPartyPrivateStaticDependencies(Target, "IntelExtensionsFramework");
}
}
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 - 2021 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "NGXD3D11RHI.h"
@@ -23,16 +14,9 @@
#include "nvsdk_ngx.h"
#include "nvsdk_ngx_helpers.h"
#include "D3D11RHIPrivate.h"
#include "D3D11Util.h"
#include "D3D11State.h"
#include "D3D11Resources.h"
#include "D3D11Viewport.h"
#include "D3D11ConstantBuffer.h"
#include "D3D11StateCache.h"
#include "RHIValidationCommon.h"
#include "ID3D11DynamicRHI.h"
#include "GenericPlatform/GenericPlatformFile.h"
DEFINE_LOG_CATEGORY_STATIC(LogDLSSNGXD3D11RHI, Log, All);
#define LOCTEXT_NAMESPACE "FNGXD3D11RHIModule"
@@ -51,7 +35,7 @@ public:
NVSDK_NGX_Result ResultReleaseFeature = NVSDK_NGX_D3D11_ReleaseFeature(Feature);
checkf(NVSDK_NGX_SUCCEED(ResultReleaseFeature), TEXT("NVSDK_NGX_D3D11_ReleaseFeature failed! (%u %s), %s"), ResultReleaseFeature, GetNGXResultAsString(ResultReleaseFeature), *Desc.GetDebugDescription());
if (NGXRHI::SupportsAllocateParameters())
if (Parameter != nullptr)
{
NVSDK_NGX_Result ResultDestroyParameter = NVSDK_NGX_D3D11_DestroyParameters(Parameter);
checkf(NVSDK_NGX_SUCCEED(ResultDestroyParameter), TEXT("NVSDK_NGX_D3D11_DestroyParameters failed! (%u %s), %s"), ResultDestroyParameter, GetNGXResultAsString(ResultDestroyParameter), *Desc.GetDebugDescription());
@@ -68,7 +52,7 @@ public:
virtual ~FNGXD3D11RHI();
private:
FD3D11DynamicRHI* D3D11RHI = nullptr;
ID3D11DynamicRHI* D3D11RHI = nullptr;
ID3D11Device* Direct3DDevice = nullptr;
ID3D11DeviceContext* Direct3DDeviceIMContext = nullptr;
@@ -129,9 +113,9 @@ NVSDK_NGX_Result FNGXD3D11RHI::Init_NGX_D3D11(const FNGXRHICreateArguments& InAr
FNGXD3D11RHI::FNGXD3D11RHI(const FNGXRHICreateArguments& Arguments)
: NGXRHI(Arguments)
, D3D11RHI(static_cast<FD3D11DynamicRHI*>(Arguments.DynamicRHI))
, Direct3DDevice(D3D11RHI->GetDevice())
, Direct3DDeviceIMContext(D3D11RHI->GetDeviceContext())
, D3D11RHI(CastDynamicRHI<ID3D11DynamicRHI>(Arguments.DynamicRHI))
, Direct3DDevice(D3D11RHI->RHIGetDevice())
, Direct3DDeviceIMContext(D3D11RHI->RHIGetDeviceContext())
{
ensure(D3D11RHI);
ensure(Direct3DDevice);
@@ -164,14 +148,6 @@ FNGXD3D11RHI::FNGXD3D11RHI(const FNGXRHICreateArguments& Arguments)
DLSSQueryFeature.DriverRequirements.DriverUpdateRequired = true;
}
if (NVSDK_NGX_FAILED(ResultGetParameters))
{
ResultGetParameters = NVSDK_NGX_D3D11_GetParameters(&DLSSQueryFeature.CapabilityParameters);
UE_LOG(LogDLSSNGXD3D11RHI, Log, TEXT("NVSDK_NGX_D3D11_GetParameters -> (%u %s)"), ResultGetParameters, GetNGXResultAsString(ResultGetParameters));
bSupportsAllocateParameters = false;
}
if (NVSDK_NGX_SUCCEED(ResultGetParameters))
{
DLSSQueryFeature.QueryDLSSSupport();
@@ -188,7 +164,7 @@ FNGXD3D11RHI::~FNGXD3D11RHI()
ReleaseAllocatedFeatures();
NVSDK_NGX_Result Result;
if (bSupportsAllocateParameters && DLSSQueryFeature.CapabilityParameters)
if (DLSSQueryFeature.CapabilityParameters != nullptr)
{
Result = NVSDK_NGX_D3D11_DestroyParameters(DLSSQueryFeature.CapabilityParameters);
UE_LOG(LogDLSSNGXD3D11RHI, Log, TEXT("NVSDK_NGX_D3D11_DestroyParameters -> (%u %s)"), Result, GetNGXResultAsString(Result));
@@ -225,16 +201,8 @@ void FNGXD3D11RHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArguments
{
NVSDK_NGX_Parameter* NewNGXParameterHandle = nullptr;
if (NGXRHI::SupportsAllocateParameters())
{
NVSDK_NGX_Result Result = NVSDK_NGX_D3D11_AllocateParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_D3D11_AllocateParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
}
else
{
NVSDK_NGX_Result Result = NVSDK_NGX_D3D11_GetParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_D3D11_GetParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
}
NVSDK_NGX_Result Result = NVSDK_NGX_D3D11_AllocateParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_D3D11_AllocateParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
ApplyCommonNGXParameterSettings(NewNGXParameterHandle, InArguments);
@@ -255,32 +223,32 @@ void FNGXD3D11RHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArguments
// execute
D3D11RHI->RegisterGPUWork(1);
D3D11RHI->RHIRegisterWork(1);
NVSDK_NGX_D3D11_DLSS_Eval_Params DlssEvalParams;
FMemory::Memzero(DlssEvalParams);
DlssEvalParams.Feature.pInOutput = GetD3D11TextureFromRHITexture(InArguments.OutputColor)->GetResource();
DlssEvalParams.Feature.pInOutput = D3D11RHI->RHIGetResource(InArguments.OutputColor);
DlssEvalParams.InOutputSubrectBase.X = InArguments.DestRect.Min.X;
DlssEvalParams.InOutputSubrectBase.Y = InArguments.DestRect.Min.Y;
DlssEvalParams.InRenderSubrectDimensions.Width = InArguments.SrcRect.Width();
DlssEvalParams.InRenderSubrectDimensions.Height = InArguments.SrcRect.Height();
DlssEvalParams.Feature.pInColor = GetD3D11TextureFromRHITexture(InArguments.InputColor)->GetResource();
DlssEvalParams.Feature.pInColor = D3D11RHI->RHIGetResource(InArguments.InputColor);
DlssEvalParams.InColorSubrectBase.X = InArguments.SrcRect.Min.X;
DlssEvalParams.InColorSubrectBase.Y = InArguments.SrcRect.Min.Y;
DlssEvalParams.pInDepth = GetD3D11TextureFromRHITexture(InArguments.InputDepth)->GetResource();
DlssEvalParams.pInDepth = D3D11RHI->RHIGetResource(InArguments.InputDepth);
DlssEvalParams.InDepthSubrectBase.X = InArguments.SrcRect.Min.X;
DlssEvalParams.InDepthSubrectBase.Y = InArguments.SrcRect.Min.Y;
// The VelocityCombine pass puts the motion vectors into the top left corner
DlssEvalParams.pInMotionVectors = GetD3D11TextureFromRHITexture(InArguments.InputMotionVectors)->GetResource();
DlssEvalParams.pInMotionVectors = D3D11RHI->RHIGetResource(InArguments.InputMotionVectors);
DlssEvalParams.InMVSubrectBase.X = 0;
DlssEvalParams.InMVSubrectBase.Y = 0;
DlssEvalParams.pInExposureTexture = InArguments.bUseAutoExposure ? nullptr : GetD3D11TextureFromRHITexture(InArguments.InputExposure)->GetResource();
DlssEvalParams.pInExposureTexture = InArguments.bUseAutoExposure ? nullptr : D3D11RHI->RHIGetResource(InArguments.InputExposure);
DlssEvalParams.InPreExposure = InArguments.PreExposure;
DlssEvalParams.Feature.InSharpness = InArguments.Sharpness;
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
using UnrealBuildTool;
@@ -33,8 +24,6 @@ public class NGXD3D12RHI : ModuleRules
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDirectory,"Source/Runtime/D3D12RHI/Private"),
Path.Combine(EngineDirectory,"Source/Runtime/D3D12RHI/Private/Windows"),
}
);
@@ -59,15 +48,7 @@ public class NGXD3D12RHI : ModuleRules
}
);
if (ReadOnlyBuildVersion.Current.MajorVersion == 5)
{
PrivateDependencyModuleNames.Add("RHICore");
}
// those come from the D3D12RHI
AddEngineThirdPartyPrivateStaticDependencies(Target, "DX12");
AddEngineThirdPartyPrivateStaticDependencies(Target, "NVAPI");
AddEngineThirdPartyPrivateStaticDependencies(Target, "NVAftermath");
AddEngineThirdPartyPrivateStaticDependencies(Target, "IntelMetricsDiscovery");
AddEngineThirdPartyPrivateStaticDependencies(Target, "IntelExtensionsFramework");
}
}
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 - 2021 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "NGXD3D12RHI.h"
@@ -23,14 +14,7 @@
#include "nvsdk_ngx.h"
#include "nvsdk_ngx_helpers.h"
#include "D3D12RHIPrivate.h"
#include "D3D12Util.h"
#include "D3D12State.h"
#include "D3D12Resources.h"
#include "D3D12Viewport.h"
#include "D3D12ConstantBuffer.h"
#include "RHIValidationCommon.h"
#include "ID3D12DynamicRHI.h"
#include "GenericPlatform/GenericPlatformFile.h"
@@ -52,7 +36,7 @@ public:
NVSDK_NGX_Result ResultReleaseFeature = NVSDK_NGX_D3D12_ReleaseFeature(Feature);
checkf(NVSDK_NGX_SUCCEED(ResultReleaseFeature), TEXT("NVSDK_NGX_D3D12_ReleaseFeature failed! (%u %s), %s"), ResultReleaseFeature, GetNGXResultAsString(ResultReleaseFeature), *Desc.GetDebugDescription());
if (NGXRHI::SupportsAllocateParameters())
if (Parameter != nullptr)
{
NVSDK_NGX_Result ResultDestroyParameter = NVSDK_NGX_D3D12_DestroyParameters(Parameter);
checkf(NVSDK_NGX_SUCCEED(ResultDestroyParameter), TEXT("NVSDK_NGX_D3D12_DestroyParameters failed! (%u %s), %s"), ResultDestroyParameter, GetNGXResultAsString(ResultDestroyParameter), *Desc.GetDebugDescription());
@@ -71,8 +55,7 @@ private:
NVSDK_NGX_Result Init_NGX_D3D12(const FNGXRHICreateArguments& InArguments, const wchar_t* InApplicationDataPath, ID3D12Device* InHandle, const NVSDK_NGX_FeatureCommonInfo* InFeatureInfo);
static bool IsIncompatibleAPICaptureToolActive(ID3D12Device* InDirect3DDevice);
FD3D12DynamicRHI* D3D12RHI = nullptr;
ID3D12DynamicRHI* D3D12RHI = nullptr;
};
@@ -130,10 +113,11 @@ NVSDK_NGX_Result FNGXD3D12RHI::Init_NGX_D3D12(const FNGXRHICreateArguments& InAr
FNGXD3D12RHI::FNGXD3D12RHI(const FNGXRHICreateArguments& Arguments)
: NGXRHI(Arguments)
, D3D12RHI(static_cast<FD3D12DynamicRHI*>(Arguments.DynamicRHI))
, D3D12RHI(CastDynamicRHI<ID3D12DynamicRHI>(Arguments.DynamicRHI))
{
ID3D12Device* Direct3DDevice = D3D12RHI->GetAdapter().GetD3DDevice();
// TODO: adapter index
ID3D12Device* Direct3DDevice = D3D12RHI->RHIGetDevice(0);
ensure(D3D12RHI);
ensure(Direct3DDevice);
@@ -165,14 +149,6 @@ FNGXD3D12RHI::FNGXD3D12RHI(const FNGXRHICreateArguments& Arguments)
DLSSQueryFeature.DriverRequirements.DriverUpdateRequired = true;
}
if (NVSDK_NGX_FAILED(ResultGetParameters))
{
ResultGetParameters = NVSDK_NGX_D3D12_GetParameters(&DLSSQueryFeature.CapabilityParameters);
UE_LOG(LogDLSSNGXD3D12RHI, Log, TEXT("NVSDK_NGX_D3D12_GetParameters -> (%u %s)"), ResultGetParameters, GetNGXResultAsString(ResultGetParameters));
bSupportsAllocateParameters = false;
}
if (NVSDK_NGX_SUCCEED(ResultGetParameters))
{
DLSSQueryFeature.QueryDLSSSupport();
@@ -189,7 +165,7 @@ FNGXD3D12RHI::~FNGXD3D12RHI()
ReleaseAllocatedFeatures();
NVSDK_NGX_Result Result;
if (bSupportsAllocateParameters && DLSSQueryFeature.CapabilityParameters)
if (DLSSQueryFeature.CapabilityParameters != nullptr)
{
Result = NVSDK_NGX_D3D12_DestroyParameters(DLSSQueryFeature.CapabilityParameters);
UE_LOG(LogDLSSNGXD3D12RHI, Log, TEXT("NVSDK_NGX_D3D12_DestroyParameters -> (%u %s)"), Result, GetNGXResultAsString(Result));
@@ -209,8 +185,9 @@ void FNGXD3D12RHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArguments
InArguments.Validate();
FD3D12Device* Device = D3D12RHI->GetAdapter().GetDevice(CmdList.GetGPUMask().ToIndex());
ID3D12GraphicsCommandList* D3DGraphicsCommandList = Device->GetCommandContext().CommandListHandle.GraphicsCommandList();
const uint32 DeviceIndex = D3D12RHI->RHIGetResourceDeviceIndex(InArguments.InputColor);
ID3D12GraphicsCommandList* D3DGraphicsCommandList = D3D12RHI->RHIGetGraphicsCommandList(DeviceIndex);
if (InDLSSState->RequiresFeatureRecreation(InArguments))
{
check(!InDLSSState->DLSSFeature || InDLSSState->HasValidFeature());
@@ -226,16 +203,8 @@ void FNGXD3D12RHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArguments
if (!InDLSSState->DLSSFeature)
{
NVSDK_NGX_Parameter* NewNGXParameterHandle = nullptr;
if (NGXRHI::SupportsAllocateParameters())
{
NVSDK_NGX_Result Result = NVSDK_NGX_D3D12_AllocateParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_D3D12_AllocateParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
}
else
{
NVSDK_NGX_Result Result = NVSDK_NGX_D3D12_GetParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_D3D12_GetParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
}
NVSDK_NGX_Result Result = NVSDK_NGX_D3D12_AllocateParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_D3D12_AllocateParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
ApplyCommonNGXParameterSettings(NewNGXParameterHandle, InArguments);
@@ -261,35 +230,39 @@ void FNGXD3D12RHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArguments
check(InDLSSState->HasValidFeature());
// execute
//TODO: replaced with what in 5.1? will something be missing from gpu profiling? see commit 305e264e
#if 0
if (Device->GetCommandContext().IsDefaultContext())
{
Device->RegisterGPUWork(1);
}
#endif
NVSDK_NGX_D3D12_DLSS_Eval_Params DlssEvalParams;
FMemory::Memzero(DlssEvalParams);
DlssEvalParams.Feature.pInOutput = GetD3D12TextureFromRHITexture(InArguments.OutputColor, InArguments.GPUNode)->GetResource()->GetResource();
//TODO: does RHIGetResource do the right thing with multiple GPUs?
DlssEvalParams.Feature.pInOutput = D3D12RHI->RHIGetResource(InArguments.OutputColor);
DlssEvalParams.InOutputSubrectBase.X = InArguments.DestRect.Min.X;
DlssEvalParams.InOutputSubrectBase.Y = InArguments.DestRect.Min.Y;
DlssEvalParams.InRenderSubrectDimensions.Width = InArguments.SrcRect.Width();
DlssEvalParams.InRenderSubrectDimensions.Height = InArguments.SrcRect.Height();
DlssEvalParams.Feature.pInColor = GetD3D12TextureFromRHITexture(InArguments.InputColor, InArguments.GPUNode)->GetResource()->GetResource();
DlssEvalParams.Feature.pInColor = D3D12RHI->RHIGetResource(InArguments.InputColor);
DlssEvalParams.InColorSubrectBase.X = InArguments.SrcRect.Min.X;
DlssEvalParams.InColorSubrectBase.Y = InArguments.SrcRect.Min.Y;
DlssEvalParams.pInDepth = GetD3D12TextureFromRHITexture(InArguments.InputDepth, InArguments.GPUNode)->GetResource()->GetResource();
DlssEvalParams.pInDepth = D3D12RHI->RHIGetResource(InArguments.InputDepth);
DlssEvalParams.InDepthSubrectBase.X = InArguments.SrcRect.Min.X;
DlssEvalParams.InDepthSubrectBase.Y = InArguments.SrcRect.Min.Y;
DlssEvalParams.pInMotionVectors = GetD3D12TextureFromRHITexture(InArguments.InputMotionVectors, InArguments.GPUNode)->GetResource()->GetResource();
DlssEvalParams.pInMotionVectors = D3D12RHI->RHIGetResource(InArguments.InputMotionVectors);
// The VelocityCombine pass puts the motion vectors into the top left corner
DlssEvalParams.InMVSubrectBase.X = 0;
DlssEvalParams.InMVSubrectBase.Y = 0;
DlssEvalParams.pInExposureTexture = InArguments.bUseAutoExposure ? nullptr : GetD3D12TextureFromRHITexture(InArguments.InputExposure, InArguments.GPUNode)->GetResource()->GetResource();
DlssEvalParams.pInExposureTexture = InArguments.bUseAutoExposure ? nullptr : D3D12RHI->RHIGetResource(InArguments.InputExposure);
DlssEvalParams.InPreExposure = InArguments.PreExposure;
DlssEvalParams.Feature.InSharpness = InArguments.Sharpness;
@@ -311,9 +284,7 @@ void FNGXD3D12RHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArguments
checkf(NVSDK_NGX_SUCCEED(ResultEvaluate), TEXT("NGX_D3D12_EVALUATE_DLSS_EXT failed! (%u %s), %s"), ResultEvaluate, GetNGXResultAsString(ResultEvaluate), *InDLSSState->DLSSFeature->Desc.GetDebugDescription());
InDLSSState->DLSSFeature->Tick(FrameCounter);
Device->GetCommandContext().StateCache.ForceSetComputeRootSignature();
Device->GetCommandContext().StateCache.GetDescriptorCache()->SetCurrentCommandList(Device->GetCommandContext().CommandListHandle);
D3D12RHI->RHIFinishExternalComputeWork(DeviceIndex, D3DGraphicsCommandList);
}
/** IModuleInterface implementation */
+9 -32
View File
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 - 2021 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "NGXRHI.h"
@@ -117,9 +108,6 @@ void NVSDK_CONV NGXLogSink(const char* InNGXMessage, NVSDK_NGX_Logging_Level InL
}
// the derived RHIs will set this to false based on runtime support
bool NGXRHI::bSupportsAllocateParameters = true;
bool NGXRHI::bNGXInitialized = false;
// the derived RHIs will set this to true during their initialization
@@ -252,23 +240,17 @@ void NGXRHI::FDLSSQueryFeature::QueryDLSSSupport()
UE_LOG(LogDLSSNGXRHI, Log, TEXT("Get NVSDK_NGX_Parameter_SuperSampling_MinDriverVersionMajor -> (%u %s), MinDriverVersionMajor = %d"), ResultMinDriverVersionMajor, GetNGXResultAsString(ResultMinDriverVersionMajor), MinDriverVersionMajor);
UE_LOG(LogDLSSNGXRHI, Log, TEXT("Get NVSDK_NGX_Parameter_SuperSampling_MinDriverVersionMinor -> (%u %s), MinDriverVersionMinor = %d"), ResultMinDriverVersionMinor, GetNGXResultAsString(ResultMinDriverVersionMinor), MinDriverVersionMinor);
if (NVSDK_NGX_SUCCEED(ResultUpdatedDriver) && NVSDK_NGX_SUCCEED(ResultMinDriverVersionMajor) && NVSDK_NGX_SUCCEED(ResultMinDriverVersionMinor))
if (NVSDK_NGX_SUCCEED(ResultUpdatedDriver))
{
DriverRequirements.DriverUpdateRequired = DriverRequirements.DriverUpdateRequired || bNeedsUpdatedDriver != 0;
// ignore 0.0 and fall back to the what's baked into FNGXDriverRequirements;
if (MinDriverVersionMajor)
if (NVSDK_NGX_SUCCEED(ResultMinDriverVersionMajor) && NVSDK_NGX_SUCCEED(ResultMinDriverVersionMinor) && MinDriverVersionMajor != 0)
{
DriverRequirements.MinDriverVersionMajor = MinDriverVersionMajor;
}
if (MinDriverVersionMinor)
{
DriverRequirements.MinDriverVersionMinor = MinDriverVersionMinor;
}
if (bNeedsUpdatedDriver)
{
UE_LOG(LogDLSSNGXRHI, Log, TEXT("NVIDIA NGX DLSS cannot be loaded due to an outdated driver. Minimum Driver Version required : %u.%u"), MinDriverVersionMajor, MinDriverVersionMinor);
@@ -473,13 +455,8 @@ void NGXRHI::TickPoolElements()
SET_DWORD_STAT(STAT_DLSSNumFeatures, AllocatedDLSSFeatures.Num());
// if r.NGX.Enable is 0 then this should be nullptr
if(DLSSQueryFeature.CapabilityParameters)
{
static const auto CVarNGXDLSSEnable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.NGX.Enable"));
check(CVarNGXDLSSEnable && CVarNGXDLSSEnable->GetInt() != 0);
unsigned long long VRAM = 0;
NVSDK_NGX_Result ResultGetStats = NGX_DLSS_GET_STATS(DLSSQueryFeature.CapabilityParameters, &VRAM);
+7 -28
View File
@@ -1,21 +1,12 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
@@ -24,7 +15,6 @@
#include "CoreMinimal.h"
#include "RendererInterface.h"
#include "Runtime/Launch/Resources/Version.h"
#include "nvsdk_ngx_params.h"
@@ -103,13 +93,8 @@ struct NGXRHI_API FRHIDLSSArguments
FIntRect SrcRect = FIntRect(FIntPoint::ZeroValue, FIntPoint::ZeroValue);
FIntRect DestRect = FIntRect(FIntPoint::ZeroValue, FIntPoint::ZeroValue);
#if ENGINE_MAJOR_VERSION < 5
FVector2D JitterOffset= FVector2D::ZeroVector;
FVector2D MotionVectorScale{ 1.0f,1.0f };
#else
FVector2f JitterOffset = FVector2f::ZeroVector;
FVector2f MotionVectorScale = FVector2f::UnitVector;
#endif
bool bHighResolutionMotionVectors = false;
float Sharpness = 0.0f;
@@ -335,11 +320,6 @@ public:
void TickPoolElements();
static bool SupportsAllocateParameters()
{
return bSupportsAllocateParameters;
}
static bool NGXInitialized()
{
return bNGXInitialized;
@@ -377,7 +357,6 @@ protected:
uint32 FrameCounter = 1;
static bool bNGXInitialized;
static bool bSupportsAllocateParameters;
static bool bIsIncompatibleAPICaptureToolActive;
private:
TArray< TSharedPtr<NGXDLSSFeature>> AllocatedDLSSFeatures;
@@ -1,26 +1,15 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
using UnrealBuildTool;
using System.IO;
public class NGXVulkanRHI : ModuleRules
{
@@ -36,8 +25,6 @@ public class NGXVulkanRHI : ModuleRules
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDirectory,"Source/Runtime/VulkanRHI/Private"),
Path.Combine(EngineDirectory,"Source/Runtime/VulkanRHI/Private/Windows"),
}
);
@@ -63,11 +50,6 @@ public class NGXVulkanRHI : ModuleRules
}
);
if (ReadOnlyBuildVersion.Current.MajorVersion == 5)
{
PrivateDependencyModuleNames.Add("RHICore");
}
// those come from the VulkanRHI
AddEngineThirdPartyPrivateStaticDependencies(Target, "Vulkan");
@@ -11,10 +11,7 @@
#include "NGXVulkanRHI.h"
#include "VulkanRHIPrivate.h"
#include "VulkanPendingState.h"
#include "VulkanRHIBridge.h"
#include "VulkanContext.h"
#include "IVulkanDynamicRHI.h"
#include "nvsdk_ngx_vk.h"
#include "nvsdk_ngx_helpers_vk.h"
@@ -38,7 +35,7 @@ public:
NVSDK_NGX_Result ResultReleaseFeature = NVSDK_NGX_VULKAN_ReleaseFeature(Feature);
checkf(NVSDK_NGX_SUCCEED(ResultReleaseFeature), TEXT("NVSDK_NGX_VULKAN_ReleaseFeature failed! (%u %s), %s"), ResultReleaseFeature, GetNGXResultAsString(ResultReleaseFeature), *Desc.GetDebugDescription());
if (NGXRHI::SupportsAllocateParameters())
if (Parameter != nullptr)
{
NVSDK_NGX_Result ResultDestroyParameter = NVSDK_NGX_VULKAN_DestroyParameters(Parameter);
checkf(NVSDK_NGX_SUCCEED(ResultDestroyParameter), TEXT("NVSDK_NGX_VULKAN_DestroyParameters failed! (%u %s), %s"), ResultDestroyParameter, GetNGXResultAsString(ResultDestroyParameter), *Desc.GetDebugDescription());
@@ -56,8 +53,7 @@ public:
virtual ~FNGXVulkanRHI();
private:
FVulkanDynamicRHI* VulkanRHI = nullptr;
FVulkanDevice* VulkanDevice = nullptr;
IVulkanDynamicRHI* VulkanRHI = nullptr;
NVSDK_NGX_Result Init_NGX_VK(const FNGXRHICreateArguments& InArguments, const wchar_t* InApplicationDataPath, VkInstance InInstance, VkPhysicalDevice InPD, VkDevice InDevice, const NVSDK_NGX_FeatureCommonInfo* InFeatureInfo);
static bool IsIncompatibleAPICaptureToolActive();
@@ -106,20 +102,18 @@ NVSDK_NGX_Result FNGXVulkanRHI::Init_NGX_VK(const FNGXRHICreateArguments& InArgu
FNGXVulkanRHI::FNGXVulkanRHI(const FNGXRHICreateArguments& Arguments)
: NGXRHI(Arguments)
, VulkanRHI(static_cast<FVulkanDynamicRHI*>(Arguments.DynamicRHI))
, VulkanDevice(VulkanRHIBridge::GetDevice(VulkanRHI)
)
, VulkanRHI(CastDynamicRHI<IVulkanDynamicRHI>(Arguments.DynamicRHI))
{
ensure(VulkanRHI);
check(VulkanRHI);
const FString NGXLogDir = GetNGXLogDirectory();
IPlatformFile::GetPlatformPhysical().CreateDirectoryTree(*NGXLogDir);
bIsIncompatibleAPICaptureToolActive = IsIncompatibleAPICaptureToolActive();
VkInstance VulkanInstance = reinterpret_cast<VkInstance>(VulkanRHIBridge::GetInstance(VulkanRHI));
VkPhysicalDevice VulkanPhysicalDevice = reinterpret_cast<VkPhysicalDevice>(VulkanRHIBridge::GetPhysicalDevice(VulkanDevice));
VkDevice VulkanLogicalDevice = reinterpret_cast<VkDevice>(VulkanRHIBridge::GetLogicalDevice(VulkanDevice));
VkInstance VulkanInstance = VulkanRHI->RHIGetVkInstance();
VkPhysicalDevice VulkanPhysicalDevice = VulkanRHI->RHIGetVkPhysicalDevice();
VkDevice VulkanLogicalDevice = VulkanRHI->RHIGetVkDevice();
NVSDK_NGX_Result ResultInit = Init_NGX_VK(Arguments, *NGXLogDir, VulkanInstance, VulkanPhysicalDevice, VulkanLogicalDevice, CommonFeatureInfo());
UE_LOG(LogDLSSNGXVulkanRHI, Log, TEXT("NVSDK_NGX_VULKAN_Init (Log %s) -> (%u %s)"), *NGXLogDir, ResultInit, GetNGXResultAsString(ResultInit));
@@ -143,14 +137,6 @@ FNGXVulkanRHI::FNGXVulkanRHI(const FNGXRHICreateArguments& Arguments)
DLSSQueryFeature.DriverRequirements.DriverUpdateRequired = true;
}
if (NVSDK_NGX_FAILED(ResultGetParameters))
{
ResultGetParameters = NVSDK_NGX_VULKAN_GetParameters(&DLSSQueryFeature.CapabilityParameters);
UE_LOG(LogDLSSNGXVulkanRHI, Log, TEXT("NVSDK_NGX_VULKAN_GetParameters -> (%u %s)"), ResultGetParameters, GetNGXResultAsString(ResultGetParameters));
bSupportsAllocateParameters = false;
}
if (NVSDK_NGX_SUCCEED(ResultGetParameters))
{
DLSSQueryFeature.QueryDLSSSupport();
@@ -167,7 +153,7 @@ FNGXVulkanRHI::~FNGXVulkanRHI()
ReleaseAllocatedFeatures();
NVSDK_NGX_Result Result;
if (bSupportsAllocateParameters && DLSSQueryFeature.CapabilityParameters)
if (DLSSQueryFeature.CapabilityParameters != nullptr)
{
Result = NVSDK_NGX_VULKAN_DestroyParameters(DLSSQueryFeature.CapabilityParameters);
UE_LOG(LogDLSSNGXVulkanRHI, Log, TEXT("NVSDK_NGX_VULKAN_DestroyParameters -> (%u %s)"), Result, GetNGXResultAsString(Result));
@@ -187,8 +173,7 @@ void FNGXVulkanRHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArgument
InArguments.Validate();
FVulkanCommandListContextImmediate& ImmediateContext = VulkanDevice->GetImmediateContext();
VkCommandBuffer VulkanCommandBuffer = ImmediateContext.GetCommandBufferManager()->GetActiveCmdBuffer()->GetHandle();
VkCommandBuffer VulkanCommandBuffer = VulkanRHI->RHIGetActiveVkCommandBuffer();
if (InDLSSState->RequiresFeatureRecreation(InArguments))
{
@@ -205,16 +190,8 @@ void FNGXVulkanRHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArgument
if (!InDLSSState->DLSSFeature)
{
NVSDK_NGX_Parameter* NewNGXParameterHandle = nullptr;
if (NGXRHI::SupportsAllocateParameters())
{
NVSDK_NGX_Result Result = NVSDK_NGX_VULKAN_AllocateParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_VULKAN_AllocateParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
}
else
{
NVSDK_NGX_Result Result = NVSDK_NGX_VULKAN_GetParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_VULKAN_GetParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
}
NVSDK_NGX_Result Result = NVSDK_NGX_VULKAN_AllocateParameters(&NewNGXParameterHandle);
checkf(NVSDK_NGX_SUCCEED(Result), TEXT("NVSDK_NGX_VULKAN_AllocateParameters failed! (%u %s)"), Result, GetNGXResultAsString(Result));
ApplyCommonNGXParameterSettings(NewNGXParameterHandle, InArguments);
@@ -242,7 +219,7 @@ void FNGXVulkanRHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArgument
// execute
NVSDK_NGX_VK_DLSS_Eval_Params DlssEvalParams;
FMemory::Memzero(DlssEvalParams);
auto NGXVulkanResourceFromRHITexture = [](FRHITexture* InRHITexture)
auto NGXVulkanResourceFromRHITexture = [VulkanRHI=VulkanRHI](FRHITexture* InRHITexture)
{
check(InRHITexture);
if (FRHITextureReference* TexRef = InRHITexture->GetTextureReference())
@@ -251,7 +228,7 @@ void FNGXVulkanRHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArgument
check(InRHITexture);
}
FVulkanTextureBase* VulkanTexture = static_cast<FVulkanTextureBase*>(InRHITexture->GetTextureBaseRHI());
const FVulkanRHIImageViewInfo ImageViewInfo = VulkanRHI->RHIGetImageViewInfo(InRHITexture);
NVSDK_NGX_Resource_VK NGXTexture;
FMemory::Memzero(NGXTexture);
@@ -259,26 +236,21 @@ void FNGXVulkanRHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArgument
NGXTexture.Type = NVSDK_NGX_RESOURCE_VK_TYPE_VK_IMAGEVIEW;
// Check for VK_IMAGE_USAGE_STORAGE_BIT. Those are not directly stored but FVulkanSurface::GenerateImageCreateInfo sets the VK flag based on those UEFlags
NGXTexture.ReadWrite = EnumHasAnyFlags(VulkanTexture->Surface.UEFlags, TexCreate_Presentable | TexCreate_UAV);
NGXTexture.ReadWrite = EnumHasAnyFlags(ImageViewInfo.UEFlags, TexCreate_Presentable | TexCreate_UAV);
NGXTexture.Resource.ImageViewInfo.ImageView = VulkanTexture->DefaultView.View;
NGXTexture.Resource.ImageViewInfo.Image = VulkanTexture->DefaultView.Image;
NGXTexture.Resource.ImageViewInfo.Format = VulkanTexture->Surface.ViewFormat;
NGXTexture.Resource.ImageViewInfo.ImageView = ImageViewInfo.ImageView;
NGXTexture.Resource.ImageViewInfo.Image = ImageViewInfo.Image;
NGXTexture.Resource.ImageViewInfo.Format = ImageViewInfo.Format;
NGXTexture.Resource.ImageViewInfo.Width = VulkanTexture->Surface.Width;
NGXTexture.Resource.ImageViewInfo.Height = VulkanTexture->Surface.Height;
check(VulkanTexture->Surface.Depth == 1);
NGXTexture.Resource.ImageViewInfo.Width = ImageViewInfo.Width;
NGXTexture.Resource.ImageViewInfo.Height = ImageViewInfo.Height;
check(ImageViewInfo.Depth == 1);
NGXTexture.Resource.ImageViewInfo.SubresourceRange.aspectMask = VulkanTexture->Surface.GetFullAspectMask();
NGXTexture.Resource.ImageViewInfo.SubresourceRange.layerCount = VulkanTexture->Surface.GetNumberOfArrayLevels();
NGXTexture.Resource.ImageViewInfo.SubresourceRange.levelCount = VulkanTexture->Surface.GetNumMips();
NGXTexture.Resource.ImageViewInfo.SubresourceRange = ImageViewInfo.SubresourceRange;
// DLSS_TODO Figure out where to get those from if the textures are arrayed or mipped.
check(VulkanTexture->Surface.GetNumberOfArrayLevels() == 1);
check(VulkanTexture->Surface.GetNumMips() == 1);
NGXTexture.Resource.ImageViewInfo.SubresourceRange.baseMipLevel = 0;
NGXTexture.Resource.ImageViewInfo.SubresourceRange.baseArrayLayer = 0;
check(NGXTexture.Resource.ImageViewInfo.SubresourceRange.layerCount == 1);
check(NGXTexture.Resource.ImageViewInfo.SubresourceRange.levelCount == 1);
return NGXTexture;
};
@@ -334,15 +306,8 @@ void FNGXVulkanRHI::ExecuteDLSS(FRHICommandList& CmdList, const FRHIDLSSArgument
checkf(NVSDK_NGX_SUCCEED(ResultEvaluate), TEXT("NGX_Vulkan_EVALUATE_DLSS_EXT failed! (%u %s), %s"), ResultEvaluate, GetNGXResultAsString(ResultEvaluate), *InDLSSState->DLSSFeature->Desc.GetDebugDescription());
InDLSSState->DLSSFeature->Tick(FrameCounter);
if (FVulkanPlatform::RegisterGPUWork() && ImmediateContext.IsImmediate())
{
ImmediateContext.GetGPUProfiler().RegisterGPUWork(1);
}
ImmediateContext.GetPendingComputeState()->Reset();
ImmediateContext.GetPendingGfxState()->Reset();
VulkanRHI->RHIRegisterWork(1);
VulkanRHI->RHIFinishExternalComputeWork(VulkanCommandBuffer);
}
@@ -1,25 +1,15 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
using UnrealBuildTool;
using System.IO;
public class NGXVulkanRHIPreInit : ModuleRules
{
@@ -36,8 +26,6 @@ public class NGXVulkanRHIPreInit : ModuleRules
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDirectory,"Source/Runtime/VulkanRHI/Private"),
Path.Combine(EngineDirectory,"Source/Runtime/VulkanRHI/Private/Windows"),
}
);
@@ -61,10 +49,7 @@ public class NGXVulkanRHIPreInit : ModuleRules
"NGX",
}
);
if (ReadOnlyBuildVersion.Current.MajorVersion == 5)
{
PrivateDependencyModuleNames.Add("RHICore");
}
// those come from the VulkanRHI
AddEngineThirdPartyPrivateStaticDependencies(Target, "Vulkan");
}
@@ -1,27 +1,17 @@
/*
* Copyright (c) 2020 - 2021 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "NGXVulkanRHIPreInit.h"
#include "VulkanRHIPrivate.h"
#include "VulkanRHIBridge.h"
#include "IVulkanDynamicRHI.h"
#include "DynamicRHI.h"
@@ -57,11 +47,11 @@ void FNGXVulkanRHIPreInitModule::StartupModule()
const NVSDK_NGX_Result ResultRequiredExtensions = NVSDK_NGX_VULKAN_RequiredExtensions(&NumInstanceExtensions, &InstanceExtensions, &NumDeviceExtensions, &DeviceExtensions);
UE_LOG(LogDLSSNGXVulkanRHIPreInit, Log, TEXT("NVSDK_NGX_VULKAN_RequiredExtensions -> (%u %s)"), ResultRequiredExtensions, GetNGXResultAsString(ResultRequiredExtensions));
const TArray<const ANSICHAR*> RHIBridgeInstanceExtensions(InstanceExtensions, NumInstanceExtensions);
VulkanRHIBridge::AddEnabledInstanceExtensionsAndLayers(RHIBridgeInstanceExtensions, TArray<const ANSICHAR*>());
const TArrayView<const ANSICHAR* const> RHIBridgeInstanceExtensions(InstanceExtensions, NumInstanceExtensions);
IVulkanDynamicRHI::AddEnabledInstanceExtensionsAndLayers(RHIBridgeInstanceExtensions, TArrayView<const ANSICHAR* const>());
const TArray<const ANSICHAR*> RHIBridgeDeviceExtensions(DeviceExtensions, NumDeviceExtensions);
VulkanRHIBridge::AddEnabledDeviceExtensionsAndLayers(RHIBridgeDeviceExtensions, TArray<const ANSICHAR*>());
const TArrayView<const ANSICHAR* const> RHIBridgeDeviceExtensions(DeviceExtensions, NumDeviceExtensions);
IVulkanDynamicRHI::AddEnabledDeviceExtensionsAndLayers(RHIBridgeDeviceExtensions, TArrayView<const ANSICHAR* const>());
UE_LOG(LogDLSSNGXVulkanRHIPreInit, Log, TEXT("Preregistered the required NGX DLSS Vulkan device extensions (%u) and instance extensions (%u) via the VulkanRHIBridge"), NumDeviceExtensions, NumInstanceExtensions);
}
+6 -4
View File
@@ -32,8 +32,8 @@
* need to update drivers. Please note that application Id is provided
* by NVIDIA so if you do not have one please contact us.
*
* 2) Call NVSDK_NGX_D3D11/D3D12/CUDA_GetParameters to obtain pointer to
* interface used to pass parameters to SDK. Interface instance is
* 2) Call NVSDK_NGX_D3D11/D3D12/CUDA_GetCapabilityParameters to obtain pointer
* to interface used to pass parameters to SDK. Interface instance is
* allocated and released by SDK so there is no need to do any memory
* management on client side.
*
@@ -200,6 +200,7 @@ NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_D3D12_Shutdown(void);
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_D3D12_Shutdown1(ID3D12Device *InDevice);
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_CUDA_Shutdown(void);
#ifdef NGX_ENABLE_DEPRECATED_GET_PARAMETERS
////////////////////////////////////////////////////////////////////////////////////////////////////
// NVSDK_NGX_GetParameters
// ----------------------------------------------------------
@@ -218,15 +219,16 @@ NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_CUDA_Shutdown(void);
// Unlike with NVSDK_NGX_AllocateParameters, parameter maps output by NVSDK_NGX_GetParameters
// have their lifetimes managed by NGX, and must not
// be destroyed by the app using NVSDK_NGX_DestroyParameters.
// NVSDK_NGX_GetParameters is soon to be deprecated and apps should move to using
// NVSDK_NGX_GetParameters is deprecated and apps should move to using
// NVSDK_NGX_AllocateParameters and NVSDK_NGX_GetCapabilityParameters when possible.
// Nevertheless, due to the possibility that the user will be using an older driver version,
// NVSDK_NGX_GetParameters should still be used as a fallback if NVSDK_NGX_AllocateParameters
// NVSDK_NGX_GetParameters may still be used as a fallback if NVSDK_NGX_AllocateParameters
// or NVSDK_NGX_GetCapabilityParameters return NVSDK_NGX_Result_FAIL_OutOfDate.
//
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_D3D11_GetParameters(NVSDK_NGX_Parameter **OutParameters);
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_D3D12_GetParameters(NVSDK_NGX_Parameter **OutParameters);
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_CUDA_GetParameters(NVSDK_NGX_Parameter **OutParameters);
#endif // NGX_ENABLE_DEPRECATED_GET_PARAMETERS
////////////////////////////////////////////////////////////////////////////////////////////////////
// NVSDK_NGX_AllocateParameters
+16 -3
View File
@@ -218,7 +218,6 @@ typedef enum NSDK_NGX_GPU_Arch
NVSDK_NGX_GPU_Arch_Unknown = 0x7FFFFFF
} NVSDK_NGX_GPU_Arch;
typedef enum NVSDK_NGX_DLSS_Feature_Flags
{
NVSDK_NGX_DLSS_Feature_Flags_IsInvalid = 1 << 31,
@@ -252,6 +251,10 @@ typedef enum NVSDK_NGX_GBufferType
NVSDK_NGX_GBUFFER_NORMALS,
NVSDK_NGX_GBUFFER_SHADINGMODELID, /* unique identifier for drawn object or how the object is drawn */
NVSDK_NGX_GBUFFER_MATERIALID, /* unique identifier for material */
NVSDK_NGX_GBUFFER_SPECULAR_ALBEDO,
NVSDK_NGX_GBUFFER_INDIRECT_ALBEDO,
NVSDK_NGX_GBUFFER_SPECULAR_MVEC,
NVSDK_NGX_GBUFFER_DISOCCL_MASK,
NVSDK_NGX_GBUFFERTYPE_NUM = 16
} NVSDK_NGX_GBufferType;
@@ -269,7 +272,11 @@ typedef struct NVSDK_NGX_Dimensions
typedef struct NVSDK_NGX_PathListInfo
{
#ifdef NV_WINDOWS
wchar_t **Path;
#else //NV_WINDOWS
char **Path;
#endif //NV_WINDOWS
// Path-list length
unsigned int Length;
} NVSDK_NGX_PathListInfo;
@@ -346,7 +353,7 @@ typedef enum NVSDK_NGX_EngineType
NVSDK_NGX_ENGINE_TYPE_UNREAL,
NVSDK_NGX_ENGINE_TYPE_UNITY,
NVSDK_NGX_ENGINE_TYPE_OMNIVERSE,
NVSDK_NGX_ENGINE_COUNT
NVSDK_NGX_ENGINE_COUNT
} NVSDK_NGX_EngineType;
// Read-only parameters provided by NGX
@@ -373,7 +380,7 @@ typedef enum NVSDK_NGX_EngineType
#define NVSDK_NGX_EParameter_Sharpness "#\x14"
#define NVSDK_NGX_EParameter_Scratch "#\x15"
#define NVSDK_NGX_EParameter_Scratch_SizeInBytes "#\x16"
#define NVSDK_NGX_EParameter_Deprecated_17 "#\x17"
#define NVSDK_NGX_EParameter_EvaluationNode "#\x17" // valid since API 0x13 (replaced a deprecated param)
#define NVSDK_NGX_EParameter_Input1 "#\x18"
#define NVSDK_NGX_EParameter_Input1_Format "#\x19"
#define NVSDK_NGX_EParameter_Input1_SizeInBytes "#\x1a"
@@ -538,8 +545,14 @@ typedef enum NVSDK_NGX_EngineType
#define NVSDK_NGX_Parameter_ExposureTexture "ExposureTexture" // a 1x1 texture containing the final exposure scale
#define NVSDK_NGX_Parameter_DLSS_Feature_Create_Flags "DLSS.Feature.Create.Flags"
#define NVSDK_NGX_Parameter_DLSS_Checkerboard_Jitter_Hack "DLSS.Checkerboard.Jitter.Hack"
#define NVSDK_NGX_Parameter_GBuffer_Normals "GBuffer.Normals"
#define NVSDK_NGX_Parameter_GBuffer_Albedo "GBuffer.Albedo"
#define NVSDK_NGX_Parameter_GBuffer_Roughness "GBuffer.Roughness"
#define NVSDK_NGX_Parameter_GBuffer_DiffuseAlbedo "GBuffer.DiffuseAlbedo"
#define NVSDK_NGX_Parameter_GBuffer_SpecularAlbedo "GBuffer.SpecularAlbedo"
#define NVSDK_NGX_Parameter_GBuffer_IndirectAlbedo "GBuffer.IndirectAlbedo"
#define NVSDK_NGX_Parameter_GBuffer_SpecularMvec "GBuffer.SpecularMvec"
#define NVSDK_NGX_Parameter_GBuffer_DisocclusionMask "GBuffer.DisocclusionMask"
#define NVSDK_NGX_Parameter_GBuffer_Metallic "GBuffer.Metallic"
#define NVSDK_NGX_Parameter_GBuffer_Specular "GBuffer.Specular"
#define NVSDK_NGX_Parameter_GBuffer_Subsurface "GBuffer.Subsurface"
@@ -169,6 +169,7 @@ typedef struct NVSDK_NGX_D3D11_DLSS_Eval_Params
NVSDK_NGX_Coordinates InBiasCurrentColorSubrectBase;
NVSDK_NGX_Coordinates InOutputSubrectBase;
float InPreExposure;
float InExposureScale;
int InIndicatorInvertXAxis;
int InIndicatorInvertYAxis;
/*** OPTIONAL - only for research purposes ***/
@@ -282,13 +283,13 @@ static inline NVSDK_NGX_Result NGX_D3D11_EVALUATE_DLSS_EXT(
NVSDK_NGX_Parameter_SetUI(pInParams, NVSDK_NGX_Parameter_DLSS_Render_Subrect_Dimensions_Width , pInDlssEvalParams->InRenderSubrectDimensions.Width);
NVSDK_NGX_Parameter_SetUI(pInParams, NVSDK_NGX_Parameter_DLSS_Render_Subrect_Dimensions_Height, pInDlssEvalParams->InRenderSubrectDimensions.Height);
NVSDK_NGX_Parameter_SetF(pInParams, NVSDK_NGX_Parameter_DLSS_Pre_Exposure, pInDlssEvalParams->InPreExposure == 0.0f ? 1.0f : pInDlssEvalParams->InPreExposure);
NVSDK_NGX_Parameter_SetF(pInParams, NVSDK_NGX_Parameter_DLSS_Exposure_Scale, pInDlssEvalParams->InExposureScale == 0.0f ? 1.0f : pInDlssEvalParams->InExposureScale);
NVSDK_NGX_Parameter_SetI(pInParams, NVSDK_NGX_Parameter_DLSS_Indicator_Invert_X_Axis, pInDlssEvalParams->InIndicatorInvertXAxis);
NVSDK_NGX_Parameter_SetI(pInParams, NVSDK_NGX_Parameter_DLSS_Indicator_Invert_Y_Axis, pInDlssEvalParams->InIndicatorInvertYAxis);
return NVSDK_NGX_D3D11_EvaluateFeature_C(pInCtx, pInHandle, pInParams, NULL);
}
static inline NVSDK_NGX_Result NGX_D3D11_CREATE_DLISP_EXT(
ID3D11DeviceContext *pInCtx,
NVSDK_NGX_Handle **ppOutHandle,
@@ -432,6 +433,7 @@ typedef struct NVSDK_NGX_D3D12_DLSS_Eval_Params
NVSDK_NGX_Coordinates InBiasCurrentColorSubrectBase;
NVSDK_NGX_Coordinates InOutputSubrectBase;
float InPreExposure;
float InExposureScale;
int InIndicatorInvertXAxis;
int InIndicatorInvertYAxis;
/*** OPTIONAL - only for research purposes ***/
@@ -538,13 +540,13 @@ static inline NVSDK_NGX_Result NGX_D3D12_EVALUATE_DLSS_EXT(
NVSDK_NGX_Parameter_SetUI(pInParams, NVSDK_NGX_Parameter_DLSS_Render_Subrect_Dimensions_Width , pInDlssEvalParams->InRenderSubrectDimensions.Width);
NVSDK_NGX_Parameter_SetUI(pInParams, NVSDK_NGX_Parameter_DLSS_Render_Subrect_Dimensions_Height, pInDlssEvalParams->InRenderSubrectDimensions.Height);
NVSDK_NGX_Parameter_SetF(pInParams, NVSDK_NGX_Parameter_DLSS_Pre_Exposure, pInDlssEvalParams->InPreExposure == 0.0f ? 1.0f : pInDlssEvalParams->InPreExposure);
NVSDK_NGX_Parameter_SetF(pInParams, NVSDK_NGX_Parameter_DLSS_Exposure_Scale, pInDlssEvalParams->InExposureScale == 0.0f ? 1.0f : pInDlssEvalParams->InExposureScale);
NVSDK_NGX_Parameter_SetI(pInParams, NVSDK_NGX_Parameter_DLSS_Indicator_Invert_X_Axis, pInDlssEvalParams->InIndicatorInvertXAxis);
NVSDK_NGX_Parameter_SetI(pInParams, NVSDK_NGX_Parameter_DLSS_Indicator_Invert_Y_Axis, pInDlssEvalParams->InIndicatorInvertYAxis);
return NVSDK_NGX_D3D12_EvaluateFeature_C(pInCmdList, pInHandle, pInParams, NULL);
}
static inline NVSDK_NGX_Result NGX_D3D12_CREATE_DLISP_EXT(
ID3D12GraphicsCommandList *InCmdList,
unsigned int InCreationNodeMask,
@@ -590,7 +592,6 @@ static inline NVSDK_NGX_Result NGX_D3D12_EVALUATE_DLISP_EXT(
return NVSDK_NGX_D3D12_EvaluateFeature_C(pInCmdList, pInHandle, pInParams, NULL);
}
static inline NVSDK_NGX_Result NGX_D3D12_CREATE_DLRESOLVE_EXT(
ID3D12GraphicsCommandList *pInCmdList,
unsigned int InCreationNodeMask,
@@ -91,6 +91,7 @@ typedef struct NVSDK_NGX_VK_DLSS_Eval_Params
NVSDK_NGX_Coordinates InBiasCurrentColorSubrectBase;
NVSDK_NGX_Coordinates InOutputSubrectBase;
float InPreExposure;
float InExposureScale;
int InIndicatorInvertXAxis;
int InIndicatorInvertYAxis;
/*** OPTIONAL - only for research purposes ***/
@@ -229,13 +230,13 @@ static inline NVSDK_NGX_Result NGX_VULKAN_EVALUATE_DLSS_EXT(
NVSDK_NGX_Parameter_SetUI(pInParams, NVSDK_NGX_Parameter_DLSS_Render_Subrect_Dimensions_Width , pInDlssEvalParams->InRenderSubrectDimensions.Width);
NVSDK_NGX_Parameter_SetUI(pInParams, NVSDK_NGX_Parameter_DLSS_Render_Subrect_Dimensions_Height, pInDlssEvalParams->InRenderSubrectDimensions.Height);
NVSDK_NGX_Parameter_SetF(pInParams, NVSDK_NGX_Parameter_DLSS_Pre_Exposure, pInDlssEvalParams->InPreExposure == 0.0f ? 1.0f : pInDlssEvalParams->InPreExposure);
NVSDK_NGX_Parameter_SetF(pInParams, NVSDK_NGX_Parameter_DLSS_Exposure_Scale, pInDlssEvalParams->InExposureScale == 0.0f ? 1.0f : pInDlssEvalParams->InExposureScale);
NVSDK_NGX_Parameter_SetI(pInParams, NVSDK_NGX_Parameter_DLSS_Indicator_Invert_X_Axis, pInDlssEvalParams->InIndicatorInvertXAxis);
NVSDK_NGX_Parameter_SetI(pInParams, NVSDK_NGX_Parameter_DLSS_Indicator_Invert_Y_Axis, pInDlssEvalParams->InIndicatorInvertYAxis);
return NVSDK_NGX_VULKAN_EvaluateFeature_C(InCmdList, pInHandle, pInParams, NULL);
}
static inline NVSDK_NGX_Result NGX_VULKAN_CREATE_DLISP_EXT(
VkCommandBuffer InCmdList,
unsigned int InCreationNodeMask,
@@ -50,6 +50,13 @@ typedef struct NVSDK_NGX_DLSS_Create_Params
bool InEnableOutputSubrects;
} NVSDK_NGX_DLSS_Create_Params;
typedef struct NVSDK_NGX_DLDenoise_Create_Params
{
NVSDK_NGX_Feature_Create_Params Feature;
/*** OPTIONAL ***/
int InFeatureCreateFlags;
} NVSDK_NGX_DLDenoise_Create_Params;
#ifdef __cplusplus
typedef struct NVSDK_NGX_Parameter
{
+4 -2
View File
@@ -245,6 +245,7 @@ NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_VULKAN_Init_with_ProjectID(const char *In
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_VULKAN_Shutdown(void);
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_VULKAN_Shutdown1(VkDevice InDevice);
#ifdef NGX_ENABLE_DEPRECATED_GET_PARAMETERS
////////////////////////////////////////////////////////////////////////////////////////////////////
// NVSDK_NGX_GetParameters
// ----------------------------------------------------------
@@ -263,13 +264,14 @@ NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_VULKAN_Shutdown1(VkDevice In
// Unlike with NVSDK_NGX_AllocateParameters, parameter maps output by NVSDK_NGX_GetParameters
// have their lifetimes managed by NGX, and must not
// be destroyed by the app using NVSDK_NGX_DestroyParameters.
// NVSDK_NGX_GetParameters is soon to be deprecated and apps should move to using
// NVSDK_NGX_GetParameters is deprecated and apps should move to using
// NVSDK_NGX_AllocateParameters and NVSDK_NGX_GetCapabilityParameters when possible.
// Nevertheless, due to the possibility that the user will be using an older driver version,
// NVSDK_NGX_GetParameters should still be used as a fallback if NVSDK_NGX_AllocateParameters
// NVSDK_NGX_GetParameters may still be used as a fallback if NVSDK_NGX_AllocateParameters
// or NVSDK_NGX_GetCapabilityParameters return NVSDK_NGX_Result_FAIL_OutOfDate.
//
NVSDK_NGX_API NVSDK_NGX_Result NVSDK_CONV NVSDK_NGX_VULKAN_GetParameters(NVSDK_NGX_Parameter **OutParameters);
#endif // NGX_ENABLE_DEPRECATED_GET_PARAMETERS
////////////////////////////////////////////////////////////////////////////////////////////////////
// NVSDK_NGX_AllocateParameters
+9 -21
View File
@@ -1,29 +1,15 @@
/*
* Copyright (c) 2020-2021 NVIDIA CORPORATION. All rights reserved.
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#if UE_5_0_OR_LATER
using EpicGames.Core;
#else
using Tools.DotNETCommon;
#endif
using UnrealBuildTool;
using System.IO;
@@ -76,6 +62,8 @@ public class NGX : ModuleRules
};
PublicDefinitions.Add("NGX_DLSS_BINARY_NAME=TEXT(\"" + NGXSnippetDLLs[0] + "\")");
// work around missing definition in NGX headers
PublicDefinitions.Add("NV_WINDOWS=1");
foreach (string NGXSnippetDLL in NGXSnippetDLLs)
{
@@ -0,0 +1,30 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "1.0.1",
"FriendlyName": "EasyXMLParser",
"Description": "Parse xml easily",
"Category": "Programming",
"CreatedBy": "ayumax",
"CreatedByURL": "https://github.com/ayumax",
"DocsURL": "https://github.com/ayumax/EasyXMLParserSample",
"MarketplaceURL": "com.epicgames.launcher://ue/marketplace/content/af98110080a4411a8eaf3b8e931b8655",
"SupportURL": "",
"EngineVersion": "5.1.0",
"CanContainContent": false,
"Installed": true,
"Modules": [
{
"Name": "EasyXMLParser",
"Type": "Runtime",
"LoadingPhase": "Default",
"WhitelistPlatforms": [
"Android",
"Win64",
"Win32",
"Mac",
"IOS"
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -0,0 +1,53 @@
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class EasyXMLParser : ModuleRules
{
public EasyXMLParser(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"CoreUObject",
"Engine",
"Slate",
"SlateCore",
"XmlParser"
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
@@ -0,0 +1,52 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "EasyXMLAsyncLoadFromFile.h"
#include "Engine/World.h"
#include "TimerManager.h"
#include "Async/Async.h"
#include "Utils/CustomXMLParser.h"
#include "EasyXMLParseManager.h"
UEasyXMLAsyncLoadFromFile::UEasyXMLAsyncLoadFromFile(const FObjectInitializer& ObjectInitializer)
:Super(ObjectInitializer)
{
}
UEasyXMLAsyncLoadFromFile* UEasyXMLAsyncLoadFromFile::AsyncLoadFromFile(UObject* WorldContextObject, const FString& FilePath, bool IsAblolute)
{
auto Action = NewObject<UEasyXMLAsyncLoadFromFile>();
Action->RegisterWithGameInstance(WorldContextObject);
Action->_XMLFile = FilePath;
Action->_IsAblolute = IsAblolute;
return Action;
}
void UEasyXMLAsyncLoadFromFile::Activate()
{
AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [this]()
{
auto manager = NewObject<UEasyXMLParseManager>();
FString _errorMessage;
EEasyXMLParserErrorCode _isSuccessed;
auto rootElement = manager->LoadFromFile(_XMLFile, _IsAblolute, _isSuccessed, _errorMessage);
if (_isSuccessed == EEasyXMLParserErrorCode::Successed)
{
AsyncTask(ENamedThreads::GameThread, [this, rootElement]()
{
Successed.Broadcast(rootElement, TEXT(""));
SetReadyToDestroy();
});
}
else
{
AsyncTask(ENamedThreads::GameThread, [this, _errorMessage]()
{
Failed.Broadcast(nullptr, _errorMessage);
SetReadyToDestroy();
});
}
});
}
@@ -0,0 +1,50 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "EasyXMLAsyncLoadFromString.h"
#include "Engine/World.h"
#include "TimerManager.h"
#include "Async/Async.h"
#include "Utils/CustomXMLParser.h"
UEasyXMLAsyncLoadFromString::UEasyXMLAsyncLoadFromString(const FObjectInitializer& ObjectInitializer)
:Super(ObjectInitializer)
{
}
UEasyXMLAsyncLoadFromString* UEasyXMLAsyncLoadFromString::AsyncLoadFromString(UObject* WorldContextObject, const FString& XMLString)
{
auto Action = NewObject<UEasyXMLAsyncLoadFromString>();
Action->RegisterWithGameInstance(WorldContextObject);
Action->_XMLString = XMLString;
return Action;
}
void UEasyXMLAsyncLoadFromString::Activate()
{
AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [this]()
{
CustomXMLParser parser;
FString _errorMessage;
auto rootElement = parser.Parse(_XMLString, _errorMessage);
if (rootElement != nullptr)
{
AsyncTask(ENamedThreads::GameThread, [this, rootElement]()
{
Successed.Broadcast(rootElement, TEXT(""));
SetReadyToDestroy();
});
}
else
{
AsyncTask(ENamedThreads::GameThread, [this, _errorMessage]()
{
Failed.Broadcast(nullptr, _errorMessage);
SetReadyToDestroy();
});
}
});
}
@@ -0,0 +1,13 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "EasyXMLAttribute.h"
#include "EasyXMLElement.h"
UEasyXMLAttribute* UEasyXMLAttribute::CreateAttribute(UEasyXMLElement* ParentObject, FString _Name, FString _Value)
{
auto newAttribute = NewObject<UEasyXMLAttribute>(ParentObject == nullptr ? (UObject*)GetTransientPackage() : ParentObject);
newAttribute->Parent = ParentObject;
newAttribute->Name = _Name;
newAttribute->Value = _Value.TrimStartAndEnd();
return newAttribute;
}
@@ -0,0 +1,223 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "EasyXMLElement.h"
#include "EasyXMLAttribute.h"
#include "Internationalization/Regex.h"
UEasyXMLElement* UEasyXMLElement::CreateElement(UEasyXMLObject* ParentObject, FString Tag, FString Content, int32 _LineNumber)
{
auto newElement = NewObject<UEasyXMLElement>(ParentObject == nullptr ? (UObject*)GetTransientPackage() : ParentObject);
newElement->Parent = ParentObject;
newElement->Name = Tag;
newElement->Value = Content.TrimStartAndEnd();
newElement->LineNumber = _LineNumber;
return newElement;
}
int32 UEasyXMLElement::ReadInt(const FString& AccessString, int32 DefaultValue)
{
auto foundElement = ReadEasyXMLObject(AccessString);
if (!foundElement) return DefaultValue;
return foundElement->GetIntValue(DefaultValue);
}
float UEasyXMLElement::ReadFloat(const FString& AccessString, float DefaultValue)
{
auto foundElement = ReadEasyXMLObject(AccessString);
if (!foundElement) return DefaultValue;
return foundElement->GetFloatValue(DefaultValue);
}
FString UEasyXMLElement::ReadString(const FString& AccessString, const FString& DefaultValue)
{
auto foundElement = ReadEasyXMLObject(AccessString);
if (!foundElement) return DefaultValue;
return foundElement->GetStringValue(DefaultValue);
}
bool UEasyXMLElement::ReadBool(const FString& AccessString, bool DefaultValue)
{
auto foundElement = ReadEasyXMLObject(AccessString);
if (!foundElement) return DefaultValue;
return foundElement->GetBoolValue(DefaultValue);
}
UEasyXMLElement* UEasyXMLElement::ReadElement(const FString& AccessString, EEasyXMLParserFound& Result)
{
auto filterArray = ReadElements(AccessString, Result);
return filterArray.Num() > 0 ? filterArray[0] : nullptr;
}
TArray<UEasyXMLElement*> UEasyXMLElement::ReadElements(const FString& AccessString, EEasyXMLParserFound& Result)
{
TArray<UEasyXMLElement*> foundElements;
TArray<FString> Accessers;
AccessString.ParseIntoArray(Accessers, TEXT("."), true);
Result = EEasyXMLParserFound::NotFound;
auto parentNode = this;
for (int i = 0; i < Accessers.Num(); ++i)
{
auto accesseName = Accessers[i];
if (accesseName.IsEmpty()) return foundElements;
if (accesseName[0] == TEXT('@'))
{
return foundElements;
}
FString elementName;
int32 arrayIndex = 0;
bool IsArrayAccess = IsAccessAsArray(accesseName, elementName, arrayIndex);
auto filterNodes = parentNode->GetElementsByTagName(elementName);
if (i == (Accessers.Num() - 1))
{
if (IsArrayAccess)
{
if (filterNodes.Num() > arrayIndex)
{
foundElements.Emplace(filterNodes[arrayIndex]);
}
}
else
{
foundElements = filterNodes;
}
}
else
{
if (filterNodes.Num() > arrayIndex)
{
parentNode = filterNodes[arrayIndex];
}
if (!parentNode) return foundElements;
}
}
Result = EEasyXMLParserFound::Found;
return foundElements;
}
UEasyXMLObject* UEasyXMLElement::ReadEasyXMLObject(const FString& AccessString)
{
TArray<FString> Accessers;
AccessString.ParseIntoArray(Accessers, TEXT("."), true);
auto parentNode = this;
for (auto accesseName : Accessers)
{
if (!parentNode) return nullptr;
if (accesseName.IsEmpty()) return nullptr;
if (accesseName[0] == TEXT('@'))
{
EEasyXMLParserFound retFound;
return parentNode->GetAttribute(accesseName.Mid(1), retFound);
}
FString elementName;
int32 arrayIndex = 0;
IsAccessAsArray(accesseName, elementName, arrayIndex);
auto filterNodes = parentNode->GetElementsByTagName(elementName);
if (filterNodes.Num() > arrayIndex)
{
parentNode = filterNodes[arrayIndex];
}
else
{
return nullptr;
}
}
return parentNode;
}
TArray<UEasyXMLElement*> UEasyXMLElement::GetElementsByTagName(const FString& TagName)
{
TArray<UEasyXMLElement*> foundElements = Children.FilterByPredicate(
[TagName](UEasyXMLElement* child)
{
return child->Name.Equals(TagName, ESearchCase::IgnoreCase);
});
return foundElements;
}
UEasyXMLAttribute* UEasyXMLElement::GetAttribute(const FString& AtrributeName, EEasyXMLParserFound& Result)
{
if (Attributes.Contains(AtrributeName))
{
Result = EEasyXMLParserFound::Found;
return Attributes[AtrributeName];
}
Result = EEasyXMLParserFound::NotFound;
return nullptr;
}
bool UEasyXMLElement::IsAccessAsArray(const FString& AccessName, FString& ElementName, int32& ArrayIndex)
{
const FRegexPattern pattern = FRegexPattern(FString(TEXT("(.*)\\[([0-9]+)\\]$")));
FRegexMatcher matcher(pattern, AccessName);
while (matcher.FindNext())
{
ElementName = matcher.GetCaptureGroup(1);
FString numStr = matcher.GetCaptureGroup(2);
if (numStr.IsNumeric())
{
ArrayIndex = (FCString::Atoi(*numStr));
}
return true;
}
ElementName = AccessName;
ArrayIndex = 0;
return false;
}
bool UEasyXMLElement::IsContainAttributeKeys(const TArray<FString>& Keys, TArray<FString>& FoundAttributeKeys)
{
TArray<FString> attributeKeys;
Attributes.GetKeys(attributeKeys);
for (auto key : Keys)
{
bool found = false;
for (auto attributeKey : attributeKeys)
{
if (key.Equals(attributeKey, ESearchCase::IgnoreCase))
{
found = true;
FoundAttributeKeys.Emplace(attributeKey);
}
}
if (!found) return false;
}
return true;
}
@@ -0,0 +1,49 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "EasyXMLObject.h"
#include "Utils/CustomXMLParser.h"
int32 UEasyXMLObject::GetIntValue(int32 DefaultValue)
{
if (Value.IsEmpty()) return DefaultValue;
int32 _index = 0;
if (Value.IsNumeric() && !Value.FindChar(TEXT('.'), _index))
{
return FCString::Atoi(*Value);
}
return DefaultValue;
}
float UEasyXMLObject::GetFloatValue(float DefaultValue)
{
if (Value.IsEmpty()) return DefaultValue;
auto isSuccess = Value.IsNumeric();
return isSuccess ? FCString::Atof(*Value) : DefaultValue;
}
FString UEasyXMLObject::GetStringValue(FString DefaultValue)
{
if (Value.IsEmpty()) return DefaultValue;
return Value;
}
bool UEasyXMLObject::GetBoolValue(bool DefaultValue)
{
if (Value.IsEmpty()) return DefaultValue;
if (Value.Equals(TEXT("true"), ESearchCase::IgnoreCase))
{
return true;
}
else if (Value.Equals(TEXT("false"), ESearchCase::IgnoreCase))
{
return false;
}
return DefaultValue;
}
@@ -0,0 +1,37 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "EasyXMLParseManager.h"
#include "Misc/Paths.h"
#include "Misc/FileHelper.h"
#include "EasyXMLElement.h"
#include "Utils/CustomXMLParser.h"
UEasyXMLElement* UEasyXMLParseManager::LoadFromString(const FString& XMLString, EEasyXMLParserErrorCode& Result, FString& ErrorMessage)
{
CustomXMLParser parser;
FString _errorMessage;
auto rootElement = parser.Parse(XMLString, _errorMessage);
Result = rootElement != nullptr ? EEasyXMLParserErrorCode::Successed : EEasyXMLParserErrorCode::Failed;
ErrorMessage = _errorMessage;
return rootElement;
}
UEasyXMLElement* UEasyXMLParseManager::LoadFromFile(const FString& FilePath, bool IsAblolute, EEasyXMLParserErrorCode& Result, FString& ErrorMessage)
{
auto readPath = FilePath;
if (!IsAblolute)
{
readPath = FPaths::Combine(FPaths::ProjectContentDir(), FilePath);
}
if (!FPaths::FileExists(readPath)) return nullptr;
FString xmlString;
FFileHelper::LoadFileToString(xmlString, *readPath);
return LoadFromString(xmlString, Result, ErrorMessage);
}
@@ -0,0 +1,20 @@
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "EasyXMLParser.h"
#define LOCTEXT_NAMESPACE "FEasyXMLParserModule"
void FEasyXMLParserModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
}
void FEasyXMLParserModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FEasyXMLParserModule, EasyXMLParser)
@@ -0,0 +1,270 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "Misc/AutomationTest.h"
#include "EasyXMLParseManager.h"
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FNodeAccessTest, "EasyXMLParser.NodeAccessTest", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::SmokeFilter)
bool FNodeAccessTest::RunTest(const FString& Parameters)
{
{
FString xmlString = TEXT("<root>\r")
TEXT("<!-- comment desu -->\r")
TEXT("<abc attr1=\"10\" attr2=\"false\">\r")
TEXT("123\r")
TEXT("</abc>\r")
TEXT("<abc/>\r")
TEXT("<abc>40</abc>\r")
TEXT("<abc>ZZZZ</abc>\r")
TEXT("<bbb>\r")
TEXT("bbbChild\r")
TEXT("</bbb>\r")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc")), TEXT("123"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc[0]")), TEXT("123"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc[1]")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc[2]")), TEXT("40"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc[3]")), TEXT("ZZZZ"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.bbb")), TEXT("bbbChild"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc[0].@attr1")), TEXT("10"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("root.abc[0].@attr2")), TEXT("false"));
}
return true;
}
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FNodeAccessTest2, "EasyXMLParser.NodeAccessTest2", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::SmokeFilter)
bool FNodeAccessTest2::RunTest(const FString& Parameters)
{
FString XMLSource =
TEXT("<PurchaseOrder PurchaseOrderNumber=\"99503\" OrderDate=\"1999-10-20\">\r")
TEXT("<Address Type=\"Shipping\">\r")
TEXT("<Name>Ellen Adams</Name>\r")
TEXT("<Street>123 Maple Street</Street>\r")
TEXT("<City>Mill Valley</City>\r")
TEXT("<State>CA</State>\r")
TEXT("<Zip>10999</Zip>\r")
TEXT("<Country>USA</Country>\r")
TEXT("</Address>\r")
TEXT("<Address Type=\"Billing\">\r")
TEXT("<Name>Tai Yee</Name>\r")
TEXT("<Street>8 Oak Avenue</Street>\r")
TEXT("<City>Old Town</City>\r")
TEXT("<State>PA</State>\r")
TEXT("<Zip>95819</Zip>\r")
TEXT("<Country>USA</Country>\r")
TEXT("</Address>\r")
TEXT("<DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>\r")
TEXT("<Items>\r")
TEXT("<Item PartNumber=\"872-AA\">\r")
TEXT("<ProductName>Lawnmower</ProductName>\r")
TEXT("<Quantity>1</Quantity>\r")
TEXT("<USPrice>148.95</USPrice>\r")
TEXT("<Comment>Confirm this is electric</Comment>\r")
TEXT("</Item>\r")
TEXT("<Item PartNumber=\"926-AA\">\r")
TEXT("<ProductName>Baby Monitor</ProductName>\r")
TEXT("<Quantity>2</Quantity>\r")
TEXT("<USPrice>39.98</USPrice>\r")
TEXT("<ShipDate>1999-05-21</ShipDate>\r")
TEXT("</Item>\r")
TEXT("</Items>\r")
TEXT("</PurchaseOrder>\r");
{
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(XMLSource, result, errorMessage);
TestEqual(TEXT("success read"), rootNode->ReadInt(TEXT("PurchaseOrder.@PurchaseOrderNumber")), 99503);
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.@OrderDate")), TEXT("1999-10-20"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].@Type")), TEXT("Shipping"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].Name")), TEXT("Ellen Adams"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].Street")), TEXT("123 Maple Street"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].City")), TEXT("Mill Valley"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].State")), TEXT("CA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].Zip")), TEXT("10999"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].Country")), TEXT("USA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].@Type")), TEXT("Billing"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].Name")), TEXT("Tai Yee"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].Street")), TEXT("8 Oak Avenue"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].City")), TEXT("Old Town"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].State")), TEXT("PA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].Zip")), TEXT("95819"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].Country")), TEXT("USA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.DeliveryNotes")), TEXT("Please leave packages in shed by driveway."));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0].@PartNumber")), TEXT("872-AA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0].ProductName")), TEXT("Lawnmower"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0].Quantity")), TEXT("1"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0].USPrice")), TEXT("148.95"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0].Comment")), TEXT("Confirm this is electric"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[1].@PartNumber")), TEXT("926-AA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[1].ProductName")), TEXT("Baby Monitor"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[1].Quantity")), TEXT("2"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[1].USPrice")), TEXT("39.98"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[1].ShipDate")), TEXT("1999-05-21"));
}
{
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(XMLSource, result, errorMessage);
EEasyXMLParserFound retFound;
auto Address0Node = rootNode->ReadElement(TEXT("PurchaseOrder.Address[0]"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
auto Address1Node = rootNode->ReadElement(TEXT("PurchaseOrder.Address[1]"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
auto Item0Node = rootNode->ReadElement(TEXT("PurchaseOrder.Items.Item[0]"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
auto Item1Node = rootNode->ReadElement(TEXT("PurchaseOrder.Items.Item[1]"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
TestEqual(TEXT("success read"), rootNode->ReadInt(TEXT("PurchaseOrder.@PurchaseOrderNumber")), 99503);
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.@OrderDate")), TEXT("1999-10-20"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("@Type")), TEXT("Shipping"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("Name")), TEXT("Ellen Adams"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("Street")), TEXT("123 Maple Street"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("City")), TEXT("Mill Valley"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("State")), TEXT("CA"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("Zip")), TEXT("10999"));
TestEqual(TEXT("success read"), Address0Node->ReadString(TEXT("Country")), TEXT("USA"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("@Type")), TEXT("Billing"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("Name")), TEXT("Tai Yee"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("Street")), TEXT("8 Oak Avenue"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("City")), TEXT("Old Town"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("State")), TEXT("PA"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("Zip")), TEXT("95819"));
TestEqual(TEXT("success read"), Address1Node->ReadString(TEXT("Country")), TEXT("USA"));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.DeliveryNotes")), TEXT("Please leave packages in shed by driveway."));
TestEqual(TEXT("success read"), Item0Node->ReadString(TEXT("@PartNumber")), TEXT("872-AA"));
TestEqual(TEXT("success read"), Item0Node->ReadString(TEXT("ProductName")), TEXT("Lawnmower"));
TestEqual(TEXT("success read"), Item0Node->ReadString(TEXT("Quantity")), TEXT("1"));
TestEqual(TEXT("success read"), Item0Node->ReadString(TEXT("USPrice")), TEXT("148.95"));
TestEqual(TEXT("success read"), Item0Node->ReadString(TEXT("Comment")), TEXT("Confirm this is electric"));
TestEqual(TEXT("success read"), Item1Node->ReadString(TEXT("@PartNumber")), TEXT("926-AA"));
TestEqual(TEXT("success read"), Item1Node->ReadString(TEXT("ProductName")), TEXT("Baby Monitor"));
TestEqual(TEXT("success read"), Item1Node->ReadString(TEXT("Quantity")), TEXT("2"));
TestEqual(TEXT("success read"), Item1Node->ReadString(TEXT("USPrice")), TEXT("39.98"));
TestEqual(TEXT("success read"), Item1Node->ReadString(TEXT("ShipDate")), TEXT("1999-05-21"));
}
{
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(XMLSource, result, errorMessage);
EEasyXMLParserFound retFound;
auto AddressNodes = rootNode->ReadElements(TEXT("PurchaseOrder.Address"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
auto ItemNodes = rootNode->ReadElements(TEXT("PurchaseOrder.Items.Item"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("@Type")), TEXT("Shipping"));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Name")), TEXT("Ellen Adams"));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Street")), TEXT("123 Maple Street"));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("City")), TEXT("Mill Valley"));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("State")), TEXT("CA"));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Zip")), TEXT("10999"));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Country")), TEXT("USA"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("@Type")), TEXT("Billing"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Name")), TEXT("Tai Yee"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Street")), TEXT("8 Oak Avenue"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("City")), TEXT("Old Town"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("State")), TEXT("PA"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Zip")), TEXT("95819"));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Country")), TEXT("USA"));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("@PartNumber")), TEXT("872-AA"));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("ProductName")), TEXT("Lawnmower"));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("Quantity")), TEXT("1"));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("USPrice")), TEXT("148.95"));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("Comment")), TEXT("Confirm this is electric"));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("@PartNumber")), TEXT("926-AA"));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("ProductName")), TEXT("Baby Monitor"));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("Quantity")), TEXT("2"));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("USPrice")), TEXT("39.98"));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("ShipDate")), TEXT("1999-05-21"));
}
{
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(XMLSource, result, errorMessage);
TestEqual(TEXT("success read"), rootNode->ReadInt(TEXT("PurchaseOrder.PurchaseOrderNumber")), 0);
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.OrderDate")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].Type")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].Name-")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrde-r.Address[0].Street")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address-[0].City")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0].State-")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder-.Address[0].Zip")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[0]-.Country")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1]-.@Type")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder-.Address[1].Name")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].Stree-t")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1]-.City")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder-.Address[1].State")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1].Zip-")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Address[1]-.Country")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder-.DeliveryNotes")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0].@PartNumber-")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[0]-.ProductName")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items-.Item[0].Quantity")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[4].USPrice")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[-1].Comment")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[8].@PartNumber")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[99].ProductName")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[7].Quantity")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[555].USPrice")), TEXT(""));
TestEqual(TEXT("success read"), rootNode->ReadString(TEXT("PurchaseOrder.Items.Item[9999].ShipDate")), TEXT(""));
}
{
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(XMLSource, result, errorMessage);
EEasyXMLParserFound retFound;
auto AddressNodes = rootNode->ReadElements(TEXT("PurchaseOrder.Address"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
auto ItemNodes = rootNode->ReadElements(TEXT("PurchaseOrder.Items.Item"), retFound);
TestTrue(TEXT("success read"), retFound == EEasyXMLParserFound::Found);
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("@Type-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Name-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Street-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("City-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("State-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Zip-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[0]->ReadString(TEXT("Country-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("@Type-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Name-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Street-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("City-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("State-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Zip-")), TEXT(""));
TestEqual(TEXT("success read"), AddressNodes[1]->ReadString(TEXT("Country-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("@PartNumber-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("ProductName-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("Quantity-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("USPrice-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[0]->ReadString(TEXT("Comment-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("@PartNumber-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("ProductName-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("Quantity-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("USPrice-")), TEXT(""));
TestEqual(TEXT("success read"), ItemNodes[1]->ReadString(TEXT("ShipDate-")), TEXT(""));
}
return true;
}
@@ -0,0 +1,428 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "Misc/AutomationTest.h"
#include "EasyXMLParseManager.h"
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FReadValueTest_Int, "EasyXMLParser.ReadValueTest.Int", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::SmokeFilter)
bool FReadValueTest_Int::RunTest(const FString& Parameters)
{
// parse success
{
FString xmlString = TEXT("<root>\r")
TEXT("<!-- comment desu -->\r")
TEXT("<abc attr1=\"10\" attr2=\"false\">\r")
TEXT("123\r")
TEXT("</abc>\r")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read int"), rootNode->ReadInt(TEXT("root.abc"), 0), 123);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("-123")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read int"), rootNode->ReadInt(TEXT("root.abc"), 0), -123);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("123456789")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read int"), rootNode->ReadInt(TEXT("root.abc"), 0), 123456789);
}
// parse ng(string)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("text")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read int(string)"), rootNode->ReadInt(TEXT("root.abc"), 0), 0);
}
// parse ng(float)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("3.14")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read int(float)"), rootNode->ReadInt(TEXT("root.abc"), 0), 0);
}
// parse ng(xml)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("<def>")
TEXT("123")
TEXT("</def>")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read int(xml)"), rootNode->ReadInt(TEXT("root.abc"), 0), 0);
}
return true;
}
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FReadValueTest_Float, "EasyXMLParser.ReadValueTest.Float", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::SmokeFilter)
bool FReadValueTest_Float::RunTest(const FString& Parameters)
{
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("1.23")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read float"), rootNode->ReadFloat(TEXT("root.abc"), 0), 1.23f);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("-1.23")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read float"), rootNode->ReadFloat(TEXT("root.abc"), 0), -1.23f);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("123.456789")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read float"), rootNode->ReadFloat(TEXT("root.abc"), 0), 123.456789f);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("123")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read float"), rootNode->ReadFloat(TEXT("root.abc"), 0), 123.0f);
}
// parse ng(string)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("text")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read float(string)"), rootNode->ReadFloat(TEXT("root.abc"), 0), 0.0f);
}
// parse ng(xml)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("<def>")
TEXT("1.23")
TEXT("</def>")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read float(xml)"), rootNode->ReadFloat(TEXT("root.abc"), 0), 0.0f);
}
return true;
}
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FReadValueTest_Bool, "EasyXMLParser.ReadValueTest.Bool", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::SmokeFilter)
bool FReadValueTest_Bool::RunTest(const FString& Parameters)
{
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("True")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read bool"), rootNode->ReadBool(TEXT("root.abc"), false), true);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("tRue")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read bool"), rootNode->ReadBool(TEXT("root.abc"), false), true);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("False")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read bool"), rootNode->ReadBool(TEXT("root.abc"), true), false);
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("fAlse")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read bool"), rootNode->ReadBool(TEXT("root.abc"), true), false);
}
// parse ng(string)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("text")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read bool(string)"), rootNode->ReadBool(TEXT("root.abc"), false), false);
}
// parse ng(xml)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("<def>")
TEXT("true")
TEXT("</def>")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("ng read bool(xml)"), rootNode->ReadBool(TEXT("root.abc"), false), false);
}
return true;
}
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FReadValueTest_String, "EasyXMLParser.ReadValueTest.String", EAutomationTestFlags::ApplicationContextMask | EAutomationTestFlags::SmokeFilter)
bool FReadValueTest_String::RunTest(const FString& Parameters)
{
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("text")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read string"), rootNode->ReadString(TEXT("root.abc"), TEXT("")), TEXT("text"));
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("123")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read string"), rootNode->ReadString(TEXT("root.abc"), TEXT("")), TEXT("123"));
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("1.23")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read string"), rootNode->ReadString(TEXT("root.abc"), TEXT("")), TEXT("1.23"));
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("true")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read string"), rootNode->ReadString(TEXT("root.abc"), TEXT("")), TEXT("true"));
}
// parse success
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("false")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read string"), rootNode->ReadString(TEXT("root.abc"), TEXT("")), TEXT("false"));
}
// parse ng(xml)
{
FString xmlString = TEXT("<root>")
TEXT("<abc>")
TEXT("<def>")
TEXT("text")
TEXT("</def>")
TEXT("</abc>")
TEXT("</root>");
EEasyXMLParserErrorCode result;
FString errorMessage;
auto rootNode = UEasyXMLParseManager::LoadFromString(xmlString, result, errorMessage);
TestEqual(TEXT("success read string"), rootNode->ReadString(TEXT("root.abc"), TEXT("")), TEXT(""));
}
return true;
}
@@ -0,0 +1,83 @@
// Copyright 2019 ayumax. All Rights Reserved.
#include "CustomXMLParser.h"
#include "Misc/FeedbackContext.h"
#include "EasyXMLElement.h"
#include "EasyXMLAttribute.h"
CustomXMLParser::CustomXMLParser()
{
}
CustomXMLParser::~CustomXMLParser()
{
}
UEasyXMLElement *CustomXMLParser::Parse(FString xmlString, FString &ErrorMessage)
{
RootElement = NewObject<UEasyXMLElement>();
XMLObjectStack.Emplace(RootElement);
FText _errorMessage;
int32 _errorMessageNumber;
if (!FFastXml::ParseXmlFile(this, TEXT(""), &xmlString[0], nullptr, false, false, _errorMessage, _errorMessageNumber))
{
ErrorMessage = FString::Printf(TEXT("line=%d, %s"), _errorMessageNumber, *_errorMessage.ToString());
return nullptr;
}
return RootElement;
}
bool CustomXMLParser::ProcessXmlDeclaration(const TCHAR *ElementData, int32 XmlFileLineNumber)
{
return true;
}
bool CustomXMLParser::ProcessElement(const TCHAR *ElementName, const TCHAR *ElementData, int32 XmlFileLineNumber)
{
auto currentNode = XMLObjectStack.Num() > 0 ? XMLObjectStack.Last() : nullptr;
auto newNode = UEasyXMLElement::CreateElement(currentNode, ElementName, ElementData, XmlFileLineNumber);
if (currentNode)
{
currentNode->Children.Emplace(newNode);
}
XMLObjectStack.Emplace(newNode);
return true;
}
bool CustomXMLParser::ProcessAttribute(const TCHAR *AttributeName, const TCHAR *AttributeValue)
{
auto currentNode = XMLObjectStack.Last();
if (!currentNode) return false;
if (currentNode->Attributes.Contains(AttributeName)) return false;
auto newAttribute = UEasyXMLAttribute::CreateAttribute(currentNode, AttributeName, AttributeValue);
currentNode->Attributes.Add(AttributeName, newAttribute);
return true;
}
bool CustomXMLParser::ProcessClose(const TCHAR *Element)
{
if (XMLObjectStack.Num() == 0) return false;
XMLObjectStack.RemoveAt(XMLObjectStack.Num() - 1);
return true;
}
bool CustomXMLParser::ProcessComment(const TCHAR *Comment)
{
if (XMLObjectStack.Num() == 0) return false;
XMLObjectStack.Last()->Comments.Emplace(Comment);
return true;
}
@@ -0,0 +1,68 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "FastXml.h"
class UEasyXMLElement;
class CustomXMLParser : public IFastXmlCallback
{
public:
CustomXMLParser();
virtual ~CustomXMLParser();
UEasyXMLElement* Parse(FString xmlString, FString& ErrorMessage);
/**
* Called after the XML's header is parsed. This is usually the first call that you'll get back.
*
* @param ElementData Optional data for this element, nullptr if none
* @param XmlFileLineNumber Line number in the XML file we're on
*
* @return You should return true to continue processing the file, or false to stop processing immediately.
*/
virtual bool ProcessXmlDeclaration(const TCHAR* ElementData, int32 XmlFileLineNumber) override;
/**
* Called when a new XML element is encountered, starting a new scope. You'll receive a call to ProcessClose()
* when this element's scope has ended.
*
* @param ElementName The name of the element
* @param ElementData Optional data for this element, nullptr if none
* @param XmlFileLineNumber The line number in the XML file we're on
*
* @return You should return true to continue processing the file, or false to stop processing immediately.
*/
virtual bool ProcessElement(const TCHAR* ElementName, const TCHAR* ElementData, int32 XmlFileLineNumber) override;
/**
* Called when an XML attribute is encountered for the current scope's element.
*
* @param AttributeName The name of the attribute
* @param AttributeValue The value of the attribute
*
* @return You should return true to continue processing the file, or false to stop processing immediately.
*/
virtual bool ProcessAttribute(const TCHAR* AttributeName, const TCHAR* AttributeValue) override;
/**
* Called when an element's scope ends in the XML file
*
* @param ElementName Name of the element whose scope closed
*
* @return You should return true to continue processing the file, or false to stop processing immediately.
*/
virtual bool ProcessClose(const TCHAR* Element) override;
/**
* Called when a comment is encountered. This can happen pretty much anywhere in the file.
*
* @param Comment The comment text
*/
virtual bool ProcessComment(const TCHAR* Comment) override;
private:
TArray<UEasyXMLElement*> XMLObjectStack;
UEasyXMLElement* RootElement;
};
@@ -0,0 +1,40 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "UObject/NoExportTypes.h"
#include "EasyXMLElement.h"
#include "EasyXMLAsyncLoadFromFile.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FEasyXMLAsyncLoadFromFile_Result, UEasyXMLElement*, XMLObject, FString, ErrorMessage);
UCLASS()
class EASYXMLPARSER_API UEasyXMLAsyncLoadFromFile : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FEasyXMLAsyncLoadFromFile_Result Successed;
UPROPERTY(BlueprintAssignable)
FEasyXMLAsyncLoadFromFile_Result Failed;
private:
UPROPERTY(Transient)
FString _XMLFile;
UPROPERTY(Transient)
bool _IsAblolute;
public:
UEasyXMLAsyncLoadFromFile(const FObjectInitializer& ObjectInitializer);
UFUNCTION(BlueprintCallable, Category = "EasyXMLParser", meta = (WorldContext = "WorldContextObject", BlueprintInternalUseOnly = "true"))
static UEasyXMLAsyncLoadFromFile * AsyncLoadFromFile(UObject * WorldContextObject, const FString& FilePath, bool IsAblolute);
virtual void Activate() override;
};
@@ -0,0 +1,38 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "UObject/NoExportTypes.h"
#include "EasyXMLElement.h"
#include "EasyXMLAsyncLoadFromString.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FEasyXMLAsyncLoadFromString_Result, UEasyXMLElement*, XMLObject, FString, ErrorMessage);
UCLASS()
class EASYXMLPARSER_API UEasyXMLAsyncLoadFromString : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FEasyXMLAsyncLoadFromString_Result Successed;
UPROPERTY(BlueprintAssignable)
FEasyXMLAsyncLoadFromString_Result Failed;
private:
UPROPERTY(Transient)
FString _XMLString;
public:
UEasyXMLAsyncLoadFromString(const FObjectInitializer& ObjectInitializer);
UFUNCTION(BlueprintCallable, Category = "EasyXMLParser", meta = (WorldContext = "WorldContextObject", BlueprintInternalUseOnly = "true"))
static UEasyXMLAsyncLoadFromString* AsyncLoadFromString(UObject * WorldContextObject, const FString& XMLString);
virtual void Activate() override;
};
@@ -0,0 +1,18 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "EasyXMLObject.h"
#include "EasyXMLAttribute.generated.h"
class UEasyXMLElement;
UCLASS(BlueprintType, Blueprintable)
class EASYXMLPARSER_API UEasyXMLAttribute : public UEasyXMLObject
{
GENERATED_BODY()
public:
static UEasyXMLAttribute* CreateAttribute(UEasyXMLElement* ParentObject, FString Name, FString Value);
};
@@ -0,0 +1,62 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "EasyXMLObject.h"
#include "EasyXMLParserEnums.h"
#include "EasyXMLElement.generated.h"
class UEasyXMLAttribute;
UCLASS(BlueprintType, Blueprintable)
class EASYXMLPARSER_API UEasyXMLElement : public UEasyXMLObject
{
GENERATED_BODY()
public:
static UEasyXMLElement* CreateElement(UEasyXMLObject* ParentObject, FString Tag, FString Content, int32 LineNumber);
public:
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|ReadValue")
int32 ReadInt(const FString& AccessString, int32 DefaultValue = 0);
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|ReadValue")
float ReadFloat(const FString& AccessString, float DefaultValue = 0.0f);
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|ReadValue")
FString ReadString(const FString& AccessString, const FString& DefaultValue = TEXT(""));
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|ReadValue")
bool ReadBool(const FString& AccessString, bool DefaultValue = false);
UFUNCTION(BlueprintCallable, Category = "EasyXMLParser|ReadValue", meta = (ExpandEnumAsExecs = "Result"))
UEasyXMLElement* ReadElement(const FString& AccessString, EEasyXMLParserFound& Result);
UFUNCTION(BlueprintCallable, Category = "EasyXMLParser|ReadValue", meta = (ExpandEnumAsExecs = "Result"))
TArray<UEasyXMLElement*> ReadElements(const FString& AccessString, EEasyXMLParserFound& Result);
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|Object", meta = (ExpandEnumAsExecs = "Result"))
UEasyXMLAttribute* GetAttribute(const FString& AtrributeName, EEasyXMLParserFound& Result);
public:
UEasyXMLObject* ReadEasyXMLObject(const FString& AccessString);
TArray<UEasyXMLElement*> GetElementsByTagName(const FString& TagName);
bool IsContainAttributeKeys(const TArray<FString>& Keys, TArray<FString>& FoundAttributeKeys);
private:
bool IsAccessAsArray(const FString& AccessName, FString& ElementName, int32& ArrayIndex);
public:
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
int32 LineNumber = 0;
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
TArray<UEasyXMLElement*> Children;
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
TMap<FString, UEasyXMLAttribute*> Attributes;
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
TArray<FString> Comments;
};
@@ -0,0 +1,37 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "EasyXMLObject.generated.h"
UCLASS(BlueprintType, Blueprintable)
class EASYXMLPARSER_API UEasyXMLObject : public UObject
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|GetValue")
int32 GetIntValue(int32 DefaultValue = 0);
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|GetValue")
float GetFloatValue(float DefaultValue = 0.0f);
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|GetValue")
FString GetStringValue(FString DefaultValue = TEXT(""));
UFUNCTION(BlueprintPure, Category = "EasyXMLParser|GetValue")
bool GetBoolValue(bool DefaultValue = false);
public:
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
FString Name = TEXT("");
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
FString Value = TEXT("");
UPROPERTY(BlueprintReadOnly, Category = "EasyXMLParser|Object")
UEasyXMLObject* Parent = nullptr;
};
@@ -0,0 +1,36 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "EasyXMLElement.h"
#include "EasyXMLParserEnums.h"
#include "EasyXMLParseManager.generated.h"
/**
*
*/
UCLASS(BlueprintType, Blueprintable)
class EASYXMLPARSER_API UEasyXMLParseManager : public UObject
{
GENERATED_BODY()
public:
/**
* load xml file
* @param FilePath - xml file path
* @param IsAblolute - true:FilePath is absolute path, false:Relative path from "Content"
* @return xml object
*/
UFUNCTION(BlueprintCallable, Category = "EasyXMLParser", meta = (ExpandEnumAsExecs = "Result"))
static UEasyXMLElement* LoadFromFile(const FString& FilePath, bool IsAblolute, EEasyXMLParserErrorCode& Result, FString& ErrorMessage);
/**
* load xml string
* @param XMLString - xml file path
* @return xml object
*/
UFUNCTION(BlueprintCallable, Category = "EasyXMLParser", meta = (ExpandEnumAsExecs = "Result"))
static UEasyXMLElement* LoadFromString(const FString& XMLString, EEasyXMLParserErrorCode& Result, FString& ErrorMessage);
};
@@ -0,0 +1,15 @@
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleManager.h"
class FEasyXMLParserModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
@@ -0,0 +1,19 @@
// Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
UENUM(BlueprintType)
enum class EEasyXMLParserErrorCode : uint8
{
Successed,
Failed
};
UENUM(BlueprintType)
enum class EEasyXMLParserFound : uint8
{
Found,
NotFound
};

Some files were not shown because too many files have changed in this diff Show More