Files
UnrealEngineUWP/Engine/Shaders/BasePassPixelShader.usf
Chris Bunner ab9d8e35b1 Copying //UE4/Dev-Rendering to //UE4/Dev-Main (Source: //UE4/Dev-Rendering @ 3388261)
#lockdown Nick.Penwarden
#rb None

==========================
MAJOR FEATURES + CHANGES
==========================

Change 3358140 on 2017/03/22 by Rolando.Caloca

	DR - Fix copy to cube face
	- Compile fix when using dump layer
	- Add new error enum

Change 3358301 on 2017/03/22 by Mitchell.Wilson

	Initial check in of LODs in InfiltratorForward. First pass on optimization in level. Adding a visibility track for SceneCapture2D in tunnel section.

Change 3358477 on 2017/03/22 by Mitchell.Wilson

	Updating Skeletal Mesh DPW_Robot_Export to resolve screen size being too low for LOD1. Cleaned up LOD1 which was showing some visible popping when transitioning.

Change 3358529 on 2017/03/22 by Mark.Satterthwaite

	Globally disable clang's "constant-logical-operand" warning when running under Distcc - it is much easier and less invasive than constantly fixing the code.

Change 3358745 on 2017/03/22 by Mark.Satterthwaite

	Disable another warning (parentheses-equality) under Distcc because again the separation of preprocessing from compilation means it turns up where it isn't expected.

Change 3358837 on 2017/03/22 by Joe.Graf

	Merge of pull request #3214 for the RenderDocPlugin

	#CodeReview: matt.kuhlenschmidt, marcus.wassmer
	#rb: marcus.wassmer

Change 3359112 on 2017/03/22 by Ben.Salem

	Update perf monitor to include frame time by default. Also, use only  game/PIE world timers when in editor, instead of all worlds combined.

	#tests Ran several Showdown test runs with plugin!

Change 3359363 on 2017/03/22 by Joe.Graf

	First pass at non-unity & no pch compilation

Change 3359449 on 2017/03/22 by Joe.Graf

	Added missing null check when exporting a EXR on Linux (UE-40268)

	#CodeReview: dmitry.rekman
	#rb: n/a

Change 3360349 on 2017/03/23 by Guillaume.Abadie

	Fixes TAA's AA_FORCE_ALPHA_CLAMP causing DOF layouts.

	#jira UE-42920

Change 3360405 on 2017/03/23 by Marcus.Wassmer

	Better method for detecting Kepler

Change 3360718 on 2017/03/23 by Daniel.Wright

	Planar reflections handle views smaller than the render target in a general way
	* Fixes planar reflections with adaptive pixel density (ViewFamily size larger than actual views combined)
	* Planar reflections are now supported in splitscreen

Change 3360758 on 2017/03/23 by Daniel.Wright

	[Copy] Added new light property bCastVolumetricShadow, which defaults to true for directional and sky lights, but false for point / spot lights as supporting volumetric fog shadowing has significant GPU overhead

Change 3360762 on 2017/03/23 by Daniel.Wright

	[Copy] Texture flags are now properly routed to RHICreateTexture3D from the render target pool

Change 3360768 on 2017/03/23 by Daniel.Wright

	[Copy] Disabled GPUProfiler histogram by default, controlled by r.ProfileGPU.ShowEventHistogram

Change 3360770 on 2017/03/23 by Daniel.Wright

	[Copy] Disabled fast clears on CustomDepth, saves .2ms on xbox

Change 3360771 on 2017/03/23 by Daniel.Wright

	[Copy] Particle lights no longer force tiled deferred lighting.  Tiled deferred lighting is only used if enough unshadowed lights + particle lights are on screen.  Saves 1.5ms Xbox with one particle light.

Change 3360774 on 2017/03/23 by Daniel.Wright

	[Copy] Distance field cvar comments

Change 3360782 on 2017/03/23 by Daniel.Wright

	[Copy] Disabled selection color on Volume materials

Change 3360795 on 2017/03/23 by Daniel.Wright

	[Copy] Volume materials now specify Albedo and Extinction, which is more intuitive than Scattering and Absorption.  Albedo is [0-1] reflectance, while Extinction is a world space density.

Change 3360799 on 2017/03/23 by Daniel.Wright

	[Copy] Cinematic scalability levels get 2x volumetric fog resolution in x and y

Change 3360806 on 2017/03/23 by Daniel.Wright

	[Copy] Fixed volumetric fog being offset when viewport min is not 0

Change 3360809 on 2017/03/23 by Daniel.Wright

	[Copy] Volumetric fog now adds a bias to the inverse squared light falloff denominator, prevents extreme aliasing from the hotspot.  Can be controlled with r.VolumetricFog.InverseSquaredLightDistanceBiasScale.

Change 3361651 on 2017/03/23 by Brian.Karis

	Higher quality sharp SSR at quality 4

Change 3361678 on 2017/03/23 by Brian.Karis

	Fresnel darkens diffuse for clearcoat.

Change 3361683 on 2017/03/23 by Brian.Karis

	Fixed SSR artifact

Change 3361691 on 2017/03/23 by Brian.Karis

	Chagned min roughness limit

Change 3361707 on 2017/03/23 by Brian.Karis

	Added inverse film tone map

Change 3361726 on 2017/03/23 by Brian.Karis

	Better precision inverse

Change 3361758 on 2017/03/23 by Brian.Karis

	Material flag normal curvature to roughness is no longer forward only.

Change 3361765 on 2017/03/23 by Brian.Karis

	Update ACES

Change 3361774 on 2017/03/23 by Brian.Karis

	Cleaned up alpha support and disabled screen edge clipping.

Change 3362478 on 2017/03/24 by Guillaume.Abadie

	Cherry pick 3316084's PostProcessing.cpp: Fixes a bug in Circle DOF where the apply pass was no longer using the downres DOF's TAA output.

	#author Brian.Karis

	#jira UE-42920

Change 3362738 on 2017/03/24 by Rolando.Caloca

	DR - Hide scene capture on IF

Change 3362890 on 2017/03/24 by Guillaume.Abadie

	Renames r.SceneAlpha to r.PostProcessing.PropagateAlpha

Change 3363665 on 2017/03/24 by Mark.Satterthwaite

	PR #3414: Add command line option "-noheartbeatthread" to disable heart beat thread (Contributed by JeffRous)

Change 3363866 on 2017/03/24 by Arne.Schober

	DR - Updated NVAPI
	#RB Marcus.Wassmer

Change 3364300 on 2017/03/24 by Brian.Karis

	SSR use dynamic velocity

Change 3364372 on 2017/03/24 by Brian.Karis

	Fix changing off axis projection velocities.

Change 3364373 on 2017/03/24 by Brian.Karis

	Enabled velocity drawing in scene captures

Change 3365531 on 2017/03/27 by Guillaume.Abadie

	Computes the material's screen position material expression directly from the pixel shader SvPosition

Change 3365764 on 2017/03/27 by Chris.Bunner

	Lowering severity of crash for missing values in scalability.ini.

	#jira UE-41331

Change 3365916 on 2017/03/27 by Guillaume.Abadie

	Exposes the viewport offset within the view property material expression

Change 3365979 on 2017/03/27 by Brian.Karis

	Fixed skylight intensity from double applying

Change 3365987 on 2017/03/27 by Brian.Karis

	Stopped post process indirect lighting intensity from scaling skylight reflections

Change 3365991 on 2017/03/27 by Brian.Karis

	Fix for static analysis

Change 3366028 on 2017/03/27 by Daniel.Wright

	Volumetric fog supports static shadowing from Stationary lights
	* Using bilinear on static shadowmap depths + 1 PCF to smooth out results

Change 3366029 on 2017/03/27 by Daniel.Wright

	Static shadow depth maps for Stationary point and spot lights are 2x higher res by default (4x more texels), which is more appropriate for volumetric fog

Change 3366055 on 2017/03/27 by Guillaume.Abadie

	Cherry picks 3251469: Implements scene capture component's CaptureSortPriority to control GPU execution order in order to manage inter dependencies.

Change 3366447 on 2017/03/27 by Simon.Tourangeau

	Fix IES light profile importer.
	- Bug in the LM-63-1986 format importer.

Change 3366836 on 2017/03/27 by Brian.Karis

	ClearUAV now supports int types

Change 3367435 on 2017/03/28 by Benjamin.Hyder

	Submitting Decal Automation map for initial approval

Change 3367572 on 2017/03/28 by Chris.Bunner

	Changed ClampedPow {max(abs(x),0.00001)} to PositiveClampedPow {max(x,0)} to give more expected results to Power node in material graphs.

	#jira UE-42989

Change 3367756 on 2017/03/28 by Olaf.Piesche

	Niagara material usage flags

Change 3367835 on 2017/03/28 by Marcus.Wassmer

	Fix crash when TileRenderer runs before anything else.  Make explicit behavior when rendering at a time when there is no valid scene.

Change 3367837 on 2017/03/28 by Marcus.Wassmer

	Missed a file.

Change 3367838 on 2017/03/28 by Richard.Wallis

	Updated items from original shelved version by Mark Satt:

	- Added MetalBackend.cpp to change main function string to have an initial crc + code length zero's

	**Description below taken from Mark Satt's original verison of this in CL3343280**

	Updated for Dev-Rendering's PSOs & integrates Richard's work on RHI shader libraries.

	Replace the FShaderCache's cook-time binary shader cache with Dmitriy Dyomin's standalone FShaderCodeLibrary that saves all shader byte-code arrays to files named by the FSHAHash. This de-duplicates shaders so we only ever store the byte code once. Includes optional support for generating a platform specific library file - which Metal implements to provide a single Metal library. The platform-native implementation can perform more de-duplication and in the case of Metal has lower file overheads and will compress more efficiently.

	- All of the support code for the FShaderCache's cook caching is gone, which affects all platforms. The FShaderCodeLibrary is currently  supported by Cook-By-The-Book but can be used with iterate or child cookers - only DLC cooking requires further work.
	- With further modifications it should be possible to support Cook-on-the-Fly as well (output directories would be needed in FShaderCodeLibrary::InitForCooking) and the file-access pattern should be changed to use async. IO so that Material loading is not considered complete until all required byte-code arrays are loaded into the FShaderCodeLibrary.
	- For Metal archiving shaders this way will compile with debug information and the FShaderCodeLibrary, with some help from extensions to IShaderFormat, will save the debug information out into separate files during cooking - these can then be used to debug the game without having to locally recompile, recook & repackage but the shipped byte-code is stripped. Global shader caches are also subject to de-duplication in the library in order to support Metal's shader stripping.
	- File Move operations need to respect the 'Replace' flag - for FShaderCodeLibrary to work we need Move to be atomic.
	- This bumps the object version and will cause all content to recook.
	- Native library support is optional - only Metal currently implements one, but so could Vulkan and D3D12. For Metal the big advantages are further de-duplication where different materials generate the same MetalSL text but a different FSHAHash, that the single Metal library has lower overhead and that as a single file it all compresses far better (esp. with LZMA - 5x smaller).

Change 3367854 on 2017/03/28 by Mark.Satterthwaite

	Don't track or record draw call resources for non-OpenGL shader platforms in the shader-cache as it is unnecessary and makes it slower on the CPU than it needs to be.

Change 3367877 on 2017/03/28 by Brian.Karis

	Fixed linux build hopefully

Change 3368001 on 2017/03/28 by Mark.Satterthwaite

	Compile fixes from Richard's checkin caused by not having visibility to all platforms from my original shelves.

Change 3368019 on 2017/03/28 by Mark.Satterthwaite

	And another fix for Windows compilation of MetalShaderFormat.

Change 3368042 on 2017/03/28 by Mark.Satterthwaite

	And a couple of simpler MSVC errors.

Change 3368271 on 2017/03/28 by Mark.Satterthwaite

	Make SceneRenderTargets compile again.

Change 3368691 on 2017/03/28 by Daniel.Wright

	[Copy from BenW] Renamed r.Shadow.MaxCSMShadowResolution to r.Shadow.MaxCSMResolution to match scalability inis

Change 3369689 on 2017/03/29 by Marcus.Wassmer

	Fix non editor compile for now

Change 3369862 on 2017/03/29 by Marcus.Wassmer

	Get the rest of the things compiling again.

Change 3369896 on 2017/03/29 by Chris.Bunner

	Enabling AMD HDR support by default.

	#jira UE-42113

Change 3370535 on 2017/03/29 by Marcus.Wassmer

	DR - Fix template explicit instantiation for ClearUAV permutations
	#RB Brian.Karis, Arne.Schober

Change 3370704 on 2017/03/29 by Rolando.Caloca

	DR - Rewrote GPU Skin Cache
	- Per section buffers
	- Limited memory per non-editor worlds (control with r.SkinCache.SceneMemoryLimitInMB)
	Copied from 3370529

Change 3371389 on 2017/03/30 by Richard.Wallis

	Remove temp working directories after archive packages built.

Change 3371641 on 2017/03/30 by Rolando.Caloca

	DR - Copy 3371640 (fix mem leak)

Change 3372436 on 2017/03/30 by Uriel.Doyon

	Added flags in UPrimitiveComponent to keep track of its state in the streaming manager.
	This allows to avoid unnecessary callback and processing in begin destroy reattach and being destroy logic.

	Removed the limitation of only processing UMeshComponent when handling spawed primitive.
	This releases the level manager from having to manage dynamic primitives.
	This improves performance by not having to manage dynamic references in the level manager.

	Primitives managed as dynamic now have a callback when ever their proxy is udpated, handling
	many cases automatically where previously a manual callback to notify would have been required.

	Fixed an issue where primitives with no reference to streaming textures would loose they dynamic state
	because of lack of references in the streamer.

Change 3372740 on 2017/03/30 by Chris.Bunner

	[Experimental] Partial compute post process pipeline (r.PostProcess.PreferCompute).
	StencilSceneTexture added to deferred list.
	A few known issues to be fixed in a follow-up CL.

Change 3372765 on 2017/03/30 by Uriel.Doyon

	Disabled concurrent call to NotifyPrimitiveUpdated while we don't have a safe concurrent update

Change 3372979 on 2017/03/30 by Richard.Hinckley

	#jira UE-43501
	The stencil buffer can now use single-channel bitmasks that ignore depth. This makes it possible to detect overlaps between stencil objects.

Change 3373053 on 2017/03/30 by Simon.Tourangeau

	LPV Fade support
	- mostly integrated from CL 2959511

Change 3373272 on 2017/03/30 by Uriel.Doyon

	Added support for the concurrent update of dynamic primitives by the streaming manager.

Change 3373450 on 2017/03/30 by Rolando.Caloca

	DR - FNT - Fix bad data for odd texcoord channels used on skin cache passthrough factory
	Copy 3373364

	#jira UE-43492

Change 3373470 on 2017/03/30 by Marcus.Wassmer

	Nvidia Aftermath support

Change 3374187 on 2017/03/31 by Chris.Bunner

	Volume texture support for CombineLUTs/Tonemap compute pass.
	Refactored common param code to shared sub-class in CombineLUTs and Tonemap PS/CS.
	Skip compute post process out-of-bounds writes.
	Unsigned type conversion fixes.
	Trimmed compute post process shader inputs.

Change 3374233 on 2017/03/31 by Chris.Bunner

	Removed several redundant post process compute fences and resource transitions.
	Added testing CVar to force compute post processes to async (r.PostProcess.ForceAsyncDispatch).

Change 3374412 on 2017/03/31 by Rolando.Caloca

	DR - Fix static analysis

Change 3374544 on 2017/03/31 by Richard.Wallis

	FShaderCache Parallel-Context-Aware Merged with FShaderCache Single Library.

	Future Work
	- This was done before Engine PSO were in so this now needs a refector in the recording and playback on pipeline states instead an emulate PSO in OpenGL Driver.
	- Remove FShaderCacheState and replace the logic with FGraphicsPipelineStateInitializer which should be able to record from the RHI current pipeline state
	- This would reduce the Locking required as it's naturally per thread/context and only the final record would need a lock

Change 3374588 on 2017/03/31 by Richard.Wallis

	Windows Compile Fixes

Change 3374810 on 2017/03/31 by Benjamin.Hyder

	updating recommended GPU drivers

Change 3375207 on 2017/03/31 by Rolando.Caloca

	DR - vk - Fixed swapchain format selection for some Linux platforms

Change 3375248 on 2017/03/31 by Rolando.Caloca

	DR - vk - Prefer D32S8

Change 3375495 on 2017/03/31 by Rolando.Caloca

	DR - vk - Update to sdk 1.0.42.2

Change 3375496 on 2017/03/31 by Rolando.Caloca

	DR - Force compiling with updated Vulkan SDK

Change 3375636 on 2017/03/31 by Mark.Satterthwaite

	Copying Metal improvements from task stream, with some modifications:
	- Off-by-default implementations for MTLFence & MTLHeap, including some small changes to the RHI interface for parallel contexts.
	- Support for Apple's Instruments "Points of Interest" tool.
	- Consolidation of some Mac & iOS compiler, memory and thread handling code.
	- Fixes for Metal not having implicit buffer SRV typecasting for DistanceField effects.
	- Improvements to the internal FMetalDebug layer, still off by default.
	- Limited support for Xcode automatic code-signing for iOS/tvOS.
	- Minimisation of render-target changes in some rendering code, esp. SceneOcclusion, DBufferDecals.
	- Added RHISetResourceAliasability_RenderThread to FDynamicRHI for RHIs to implement simple render-target aliasing.
	- Added FApplePlatformObject, a custom block allocator for Objective-C types (with NSZombie support) which is now used in MetalRHI to decrease allocation costs of Objective-C types.
	- Smattering of lesser fixes.

Change 3375654 on 2017/03/31 by Mark.Satterthwaite

	Incremental Windows build fix.

Change 3375656 on 2017/04/01 by Mark.Satterthwaite

	Correct extern declaration, including the module export macro which Mac unhelpfully doesn't enforce (for now...).

Change 3375797 on 2017/04/01 by Mark.Satterthwaite

	Nullability qualifiers to fix Mac build-farm compilation: perversely this is not a problem for local builds...

Change 3375798 on 2017/04/01 by Mark.Satterthwaite

	Fix the first mis-merge in ParticleGpuSimulation - these changes clearly weren't properly resolved in the task-stream.

Change 3375835 on 2017/04/01 by Mark.Satterthwaite

	Try again with nullability and fix the occlusion changes as the PSO work wasn't merged correctly.

Change 3376143 on 2017/04/02 by Mark.Satterthwaite

	Switch back to flat dSYMs for Dev-Rendering - they don't work with Instruments etc. but they are required by our build system.

Change 3376324 on 2017/04/03 by Chris.Bunner

	Fixed cvar re-registration log spam and flagged a testing-only cvar as such.

Change 3376726 on 2017/04/03 by Benjamin.Hyder

	Submitting initial HDR test map (WIP)

Change 3376756 on 2017/04/03 by Guillaume.Abadie

	Fixes scene captures ordering's backward compatibility.

	Before, 2d scene captures were rendered before cube scene captures. The CaptureSortPriority broke backward compatibility by settings this new member to 0 in the USceneCaptureComponent's constructor. Since it is a higher come first policy, this CL set the default of this value to 1 in USceneCaptureComponent2D's constructor.

Change 3377378 on 2017/04/03 by Arne.Schober

	DR - Fix ShaderRecompiling over and over again
	#RB Chris.Bunner

Change 3377512 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed profilegpu in d3d12 - initialize FLongGPUTaskPS when it is safe to do so, and fixed FSlateRHIRenderer's incorrect usage of draw events

Change 3377518 on 2017/04/03 by Daniel.Wright

	[Copy] Distance field atlas coalesces updates to reduce RHIUpdateTexture3D memory overhead on d3d12

Change 3377526 on 2017/04/03 by Daniel.Wright

	[Copy] "Ran out of GPU queries!" log only happens once

Change 3377535 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed unreferenced local variable

Change 3377539 on 2017/04/03 by Daniel.Wright

	[Copy] Xbox One RHIGetResourceInfo takes ESRAM into account - fixes render target pool 'VRamInKB request failed' messages

Change 3377546 on 2017/04/03 by Daniel.Wright

	[Copy] Added r.LightMaxDrawDistanceScale for local light scalability

Change 3377553 on 2017/04/03 by Daniel.Wright

	[Copy] Removed NEW_ESRAM_ALLOCATOR define and old unused path

Change 3377560 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed two d3d12 refcounting bugs causing -norhithread crashes

Change 3377565 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed Xbox One deleting GPU resources before the GPU is done reading from them (GRHINeedsExtraDeletionLatency was false)

Change 3377572 on 2017/04/03 by Daniel.Wright

	[Copy] Disabled point / spot lights with MaxDrawDistance on LowPC

Change 3377586 on 2017/04/03 by Daniel.Wright

	Fixed compile error

Change 3377699 on 2017/04/03 by David.Hill

	FFT Code.  Moved over from raven and refactored

	#review-3374589 @guillaume.abadie

Change 3377910 on 2017/04/03 by David.Hill

	GPU FFT: Fix Linux Build
	adding a missing template<> to an IMPLEMENT_SHADER_TYPE

Change 3378751 on 2017/04/04 by Marcus.Wassmer

	HQ particle lights now spawn attached to the same socket as their parent module.

Change 3378819 on 2017/04/04 by Richard.Wallis

	Should be no need to protect shader cache against RHI thread now.

Change 3378823 on 2017/04/04 by Richard.Wallis

	FRHIShaderLibrary Opaque Type

	- Base FRHIShaderLibrary has no Create*Shader functions and is passed to Overloaded RHICreate*Shader functions instead of creation directly through the library.
	- Assumed that only Native libraries will end up in the RHICreate*Shader functions.
	- ShaderCache and ShaderCode Libraries now inherit from a common factory interface.

Change 3378883 on 2017/04/04 by Arne.Schober

	DR - Fix DCC build

Change 3378885 on 2017/04/04 by Richard.Wallis

	Metal resource cast compile fix post merge.

Change 3378946 on 2017/04/04 by Chris.Bunner

	SM4 assert fix.

Change 3378953 on 2017/04/04 by Chris.Bunner

	Fixed type-correctness on legacy BreakMA material nodes and set more flexible formats to global attributes which should result in much more forgiving graphs for users.
	Allowed material nodes to opt out of mask-based pin coloration.
	#tests Compiled most Paragon materials + QAGame test maps.

	#jira UE-39885

Change 3379189 on 2017/04/04 by Arne.Schober

	DR - Fix aftermath staging

Change 3379229 on 2017/04/04 by Arne.Schober

	DR - Fix missing include

Change 3379374 on 2017/04/04 by Mark.Satterthwaite

	Revert an accidentally merged change in MacPlatformProcess that relies on further changes from the Metal task stream.

Change 3379505 on 2017/04/04 by Rolando.Caloca

	DR - Fix mismatched interpolators

Change 3379539 on 2017/04/04 by Mark.Satterthwaite

	No FFT for any hlslcc platform - the IR for one or more RWTexture2D isn't quite right...

	#jira UE-43626

Change 3379561 on 2017/04/04 by Rolando.Caloca

	DR - Fix root signature issues on D3D12 PC

Change 3379590 on 2017/04/04 by Mark.Satterthwaite

	Back out changelist 3379539 & change the shader slightly instead, the HLSLCC library generates bogus IR when you have an inout RWTexture.

	#jira UE-43626

Change 3379917 on 2017/04/04 by Uriel.Doyon

	Fix to input mismatch

Change 3380578 on 2017/04/05 by Chris.Bunner

	Shader type fixes.

	#jira UE-43652

Change 3380639 on 2017/04/05 by Rolando.Caloca

	DR - Expose GetOrCreate PSO and document

Change 3380821 on 2017/04/05 by Guillaume.Abadie

	Fixes a crash in USceneCaptureComponent::UpdateDeferredCaptures()

	#jira UE-43642

Change 3381092 on 2017/04/05 by Guillaume.Abadie

	Cherry pick 3362517: Implements TAA's scene color unpremultiplication from alpha channel to reduce DOF alpha channel temporal ghosting.

	This CL take the oportunity to transform AA_ALPHA to an compile time enumeration, and add a basic TAA compile time configuration validation to improve readability of the different TAA passes' configurations.

Change 3381300 on 2017/04/05 by Mark.Satterthwaite

	Quick fix for changes to MetalRHI's render-thread safe texture creation not correctly handling AVFoundation video player handing us an IOSurface.

	#jira UE-43597

Change 3381359 on 2017/04/05 by Guillaume.Abadie

	Back out changelist 3381092

Change 3381421 on 2017/04/05 by Mark.Satterthwaite

	Amended CL #3380995 from Richard Wallis to address crash in the Material Editor under the validation layer - when there are no textures bound the default pass descriptor assigns store actions, which means we can't override them with our deferred store actions.

	#jira UE-43689

Change 3381422 on 2017/04/05 by Mark.Satterthwaite

	Absolute time queries can't be batched in Metal but I also can't rely on them being started with a call to BeginQuery - only EndQuery.

	#jira UE-43691

Change 3381503 on 2017/04/05 by Daniel.Wright

	More intuitive controls for Volumetric Fog
	* Removed ScatteringScale / AbsorptionScale on Exponential Height Fog and added Albedo / Extinction
	* InscatteringColorCubemap is now supported by Volumetric Fog
	* Particle lights have a default VolumetricScatteringIntensity of 0 to avoid trailing
	* Tweaked GVolumetricFogDepthDistributionScale better for nearby details
	* Volume Materials have twice the interpolators available

Change 3381527 on 2017/04/05 by Mark.Satterthwaite

	Disable Private GPU storage for PVRTC texture formats on iOS Metal - these require more changes to the blit-encoder usage as PVRTC has strange requirements.

Change 3381671 on 2017/04/05 by Mark.Satterthwaite

	Better error message for failure to compile shaders remotely from PC for Metal.

Change 3381769 on 2017/04/05 by Rolando.Caloca

	DR - Added lock texture array 2d on Vulkan

Change 3382003 on 2017/04/05 by Mark.Satterthwaite

	Remove the automatic Metal aliasing/re-use when releasing some resource types as it doesn't work as intended.

Change 3382030 on 2017/04/05 by Zachary.Wilson

	Fix compiling Metal text shaders from PC broken in merge from task stream.
	#submitter mark.satterthwaite

	#jira UE-43652

Change 3382880 on 2017/04/06 by Mark.Satterthwaite

	Michael Trepka's CL #3379927:
	VolumetricFogVoxelization implementation for Mac

Change 3383315 on 2017/04/06 by Mark.Satterthwaite

	Partially revert CL #3382003 - the emulated Metal heaps require invoking makeAliasable in order to reclaim memory.

	#jira UE-43739

Change 3384639 on 2017/04/07 by Marcus.Wassmer

	Move ShaderResource version bump to RenderingObjectVersion

Change 3384704 on 2017/04/07 by Mark.Satterthwaite

	Compile fix for merge.

Change 3384933 on 2017/04/07 by Rolando.Caloca

	DR - Fix skin cache crash with BP (copy 3384714)

Change 3385104 on 2017/04/07 by Mark.Satterthwaite

	Fix MetalRHI's abs(int2) handling - it can't be translated to fabs(int2) as that won't compile. Also rebuild hlslcc for my sanity.

	#jira UE-43783

Change 3385105 on 2017/04/07 by Mark.Satterthwaite

	Force a shader rebuild to ensure that everybody picks up the fix for #jira UE-43783

	#jira UE-43783

Change 3385118 on 2017/04/07 by Arne.Schober

	DR - [OR-37359] - Fix disapearing Decals when StencilLod Fade is enabled
	#RB none

Change 3385149 on 2017/04/07 by Marcus.Wassmer

	Fix skincache motion blur

Change 3385189 on 2017/04/07 by Rolando.Caloca

	DR - Fix swapchain format for editor on Vulkan

Change 3385287 on 2017/04/07 by Mark.Satterthwaite

	Enable SM5 on Intel as of 10.12.4 and later.

Change 3385347 on 2017/04/07 by Rolando.Caloca

	DR - Temp fix for GL4 corruption on editor
	#jira UE-43785

Change 3385363 on 2017/04/07 by Rolando.Caloca

	DR - Actually fix all win platforms for GL bug
	#jira UE-43785

Change 3385557 on 2017/04/07 by Arne.Schober

	DR - [UE-43205] - Fix mesh paint
	#RB none

Change 3385608 on 2017/04/07 by Daniel.Wright

	Fixed SampleCmp being used on a non-depth texture, causing a d3d error

Change 3385980 on 2017/04/10 by Rolando.Caloca

	DR - Remove transition functions RHIClearColor* RHIClearDepthStencilTexture

Change 3386042 on 2017/04/10 by Rolando.Caloca

	DR - Fix metal merge issue

Change 3386157 on 2017/04/10 by Rolando.Caloca

	DR - Remove VS2013 libs generation off hlslcc & glslang (to match main)

Change 3386356 on 2017/04/10 by Chris.Bunner

	Resolving merge errors.

Change 3386414 on 2017/04/10 by Chris.Bunner

	Resolved merge issue in RendererScene.cpp.

Change 3386700 on 2017/04/10 by Mark.Satterthwaite

	Silence documentation warnings.

Change 3387178 on 2017/04/10 by Chris.Bunner

	Removed invalid mask correction on MakeMA material nodes.

Change 3388177 on 2017/04/11 by Marcus.Wassmer

	Disable ensure that is no longer relevant now that we bind clear colors on texture creation

Change 3388261 on 2017/04/11 by Chris.Bunner

	Static analysis fix.

[CL 3388266 by Chris Bunner in Main branch]
2017-04-11 10:32:07 -04:00

1103 lines
45 KiB
Plaintext

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
BasePassPixelShader.usf: Base pass pixel shader
=============================================================================*/
#include "Common.usf"
#include "SHCommon.usf"
#include "Material.usf"
#include "BasePassCommon.usf"
#include "VertexFactory.usf"
#include "LightmapCommon.usf"
#include "ReflectionEnvironmentShared.usf"
#include "PlanarReflectionShared.usf"
#include "BRDF.usf"
#include "Random.usf"
#include "LightAccumulator.usf"
#include "DeferredShadingCommon.usf"
#include "VelocityCommon.usf"
#define PREV_FRAME_COLOR 1
#include "ScreenSpaceRayCast.usf"
#if NEEDS_BASEPASS_PIXEL_FOGGING
#include "HeightFogCommon.usf"
#endif
float NormalCurvatureToRoughness(float3 WorldNormal)
{
float3 dNdx = ddx(WorldNormal);
float3 dNdy = ddy(WorldNormal);
float x = dot(dNdx, dNdx);
float y = dot(dNdy, dNdy);
float CurvatureApprox = pow(max(x, y), View.NormalCurvatureToRoughnessScaleBias.z);
return saturate(CurvatureApprox * View.NormalCurvatureToRoughnessScaleBias.x + View.NormalCurvatureToRoughnessScaleBias.y);
}
#if TRANSLUCENT_SELF_SHADOWING
#include "ShadowProjectionCommon.usf"
float4x4 WorldToShadowMatrix;
float4 ShadowUVMinMax;
float3 DirectionalLightDirection;
float4 DirectionalLightColor;
#endif
#if MATERIAL_SHADINGMODEL_HAIR || SIMPLE_FORWARD_DIRECTIONAL_LIGHT
#include "ShadingModels.usf"
#endif
Texture2D HZBTexture;
SamplerState HZBSampler;
Texture2D PrevSceneColor;
SamplerState PrevSceneColorSampler;
#if PLATFORM_SUPPORTS_RENDERTARGET_WRITE_MASK && USE_DBUFFER && MATERIALDECALRESPONSEMASK && !MATERIALBLENDING_ANY_TRANSLUCENT
Texture2D<uint> DBufferMask;
#endif
#ifndef COMPILER_GLSL
#define COMPILER_GLSL 0
#endif
#define FORCE_FULLY_ROUGH (SIMPLE_FORWARD_SHADING || MATERIAL_FULLY_ROUGH)
#define EDITOR_ALPHA2COVERAGE (USE_EDITOR_COMPOSITING && SUPPORTS_PIXEL_COVERAGE)
// Optimization: if opacity is 0 then revert to default shading model
#define SUBSURFACE_PROFILE_OPACITY_THRESHOLD 1
#if TRANSLUCENCY_LIGHTING_SURFACE_LIGHTINGVOLUME || TRANSLUCENCY_LIGHTING_SURFACE_FORWARDSHADING || FORWARD_SHADING
#include "ForwardLightingCommon.usf"
#endif
#if !FORWARD_SHADING
void GetVolumeLightingNonDirectional(float4 AmbientLightingVector, float3 DiffuseColor, inout float3 InterpolatedLighting, out float4 VolumeLighting)
{
// Normal is not taken into account with non directional lighting, and only the ambient term of the SH coefficients are needed
FOneBandSHVectorRGB TranslucentLighting;
TranslucentLighting.R.V.x = AmbientLightingVector.r;
TranslucentLighting.G.V.x = AmbientLightingVector.g;
TranslucentLighting.B.V.x = AmbientLightingVector.b;
FOneBandSHVector DiffuseTransferSH = CalcDiffuseTransferSH1(1);
VolumeLighting = float4(DotSH1(TranslucentLighting, DiffuseTransferSH), AmbientLightingVector.a);
InterpolatedLighting = DiffuseColor * VolumeLighting.rgb;
}
void GetVolumeLightingDirectional(float4 AmbientLightingVector, float3 DirectionalLightingVector, float3 WorldNormal, float3 DiffuseColor, inout float3 InterpolatedLighting, out float4 VolumeLighting)
{
float DirectionalLightingIntensity = GetMaterialTranslucencyDirectionalLightingIntensity();
AmbientLightingVector.rgb /= DirectionalLightingIntensity;
DirectionalLightingVector.rgb *= DirectionalLightingIntensity;
// Reconstruct the SH coefficients based on what was encoded
FTwoBandSHVectorRGB TranslucentLighting;
TranslucentLighting.R.V.x = AmbientLightingVector.r;
TranslucentLighting.G.V.x = AmbientLightingVector.g;
TranslucentLighting.B.V.x = AmbientLightingVector.b;
float3 NormalizedAmbientColor = AmbientLightingVector.rgb / Luminance( AmbientLightingVector.rgb );
// Scale the monocrome directional coefficients with the normalzed ambient color as an approximation to the uncompressed values
TranslucentLighting.R.V.yzw = DirectionalLightingVector.rgb * NormalizedAmbientColor.r;
TranslucentLighting.G.V.yzw = DirectionalLightingVector.rgb * NormalizedAmbientColor.g;
TranslucentLighting.B.V.yzw = DirectionalLightingVector.rgb * NormalizedAmbientColor.b;
// Compute diffuse lighting which takes the normal into account
FTwoBandSHVector DiffuseTransferSH = CalcDiffuseTransferSH(WorldNormal, 1);
VolumeLighting = float4(max(half3(0,0,0), DotSH(TranslucentLighting, DiffuseTransferSH)), AmbientLightingVector.a);
InterpolatedLighting += DiffuseColor * VolumeLighting.rgb;
}
/** Calculates lighting for translucency. */
float3 GetTranslucencyVolumeLighting(
FMaterialPixelParameters MaterialParameters,
FPixelMaterialInputs PixelMaterialInputs,
FBasePassInterpolantsVSToPS BasePassInterpolants,
FGBufferData GBuffer,
float IndirectIrradiance)
{
float4 VolumeLighting;
float3 InterpolatedLighting = 0;
float3 InnerVolumeUVs;
float3 OuterVolumeUVs;
float FinalLerpFactor;
ComputeVolumeUVs(MaterialParameters.AbsoluteWorldPosition, MaterialParameters.LightingPositionOffset, InnerVolumeUVs, OuterVolumeUVs, FinalLerpFactor);
#if TRANSLUCENCY_LIGHTING_VOLUMETRIC_PERVERTEX_DIRECTIONAL
GetVolumeLightingDirectional(float4(BasePassInterpolants.AmbientLightingVector, 1), BasePassInterpolants.DirectionalLightingVector, MaterialParameters.WorldNormal, GBuffer.DiffuseColor, InterpolatedLighting, VolumeLighting);
#elif TRANSLUCENCY_LIGHTING_VOLUMETRIC_PERVERTEX_NONDIRECTIONAL
GetVolumeLightingNonDirectional(float4(BasePassInterpolants.AmbientLightingVector, 1), GBuffer.DiffuseColor, InterpolatedLighting, VolumeLighting);
#elif TRANSLUCENCY_LIGHTING_VOLUMETRIC_DIRECTIONAL || TRANSLUCENCY_LIGHTING_SURFACE_LIGHTINGVOLUME
float4 AmbientLightingVector = GetAmbientLightingVectorFromTranslucentLightingVolume(InnerVolumeUVs, OuterVolumeUVs, FinalLerpFactor);
float3 DirectionalLightingVector = GetDirectionalLightingVectorFromTranslucentLightingVolume(InnerVolumeUVs, OuterVolumeUVs, FinalLerpFactor);
GetVolumeLightingDirectional(AmbientLightingVector, DirectionalLightingVector, MaterialParameters.WorldNormal, GBuffer.DiffuseColor, InterpolatedLighting, VolumeLighting);
#elif TRANSLUCENCY_LIGHTING_VOLUMETRIC_NONDIRECTIONAL
float4 AmbientLightingVector = GetAmbientLightingVectorFromTranslucentLightingVolume(InnerVolumeUVs, OuterVolumeUVs, FinalLerpFactor);
GetVolumeLightingNonDirectional(AmbientLightingVector, GBuffer.DiffuseColor, InterpolatedLighting, VolumeLighting);
#endif
#if (TRANSLUCENCY_LIGHTING_VOLUMETRIC_DIRECTIONAL || TRANSLUCENCY_LIGHTING_VOLUMETRIC_NONDIRECTIONAL || TRANSLUCENCY_LIGHTING_SURFACE_LIGHTINGVOLUME) && TRANSLUCENT_SELF_SHADOWING
// Only apply self shadowing if the shadow hasn't faded out completely
if (DirectionalLightColor.a > 0)
{
// Determine the shadow space position
// Apply a stable offset to the world position used for shadowing, which blurs out high frequency details in the shadowmap with many layers
float4 HomogeneousShadowPosition = mul(float4(MaterialParameters.AbsoluteWorldPosition + MaterialParameters.LightingPositionOffset, 1), WorldToShadowMatrix);
float2 ShadowUVs = HomogeneousShadowPosition.xy / HomogeneousShadowPosition.w;
// Lookup the shadow density at the point being shaded
float3 ShadowDensity = CalculateTranslucencyShadowingDensity(ShadowUVs, HomogeneousShadowPosition.z) / GetMaterialTranslucentMultipleScatteringExtinction();
// Compute colored transmission based on the density that the light ray passed through
float3 SelfShadowing = saturate(exp(-ShadowDensity * GetMaterialTranslucentSelfShadowDensityScale()));
// Compute a second shadow gradient to add interesting information in the shadowed area of the first
// This is a stop gap for not having self shadowing from other light sources
float3 SelfShadowing2 = lerp(float3(1, 1, 1), saturate(exp(-ShadowDensity * GetMaterialTranslucentSelfShadowSecondDensityScale())), GetMaterialTranslucentSelfShadowSecondOpacity());
SelfShadowing = SelfShadowing * SelfShadowing2;
// Force unshadowed if we read outside the valid area of the shadowmap atlas
// This can happen if the particle system's bounds don't match its visible area
FLATTEN
if (any(ShadowUVs < ShadowUVMinMax.xy || ShadowUVs > ShadowUVMinMax.zw))
{
SelfShadowing = 1;
}
float3 BackscatteredLighting = 0;
#if MATERIAL_SHADINGMODEL_SUBSURFACE
float InScatterPower = GetMaterialTranslucentBackscatteringExponent();
// Setup a pow lobe to approximate anisotropic in-scattering near to the light direction
float InScattering = pow(saturate(dot(DirectionalLightDirection, MaterialParameters.CameraVector)), InScatterPower);
float4 SSData = GetMaterialSubsurfaceData(MaterialParameters);
float3 SubsurfaceColor = SSData.rgb;
BackscatteredLighting =
SubsurfaceColor
* InScattering
* DirectionalLightColor.rgb
// Energy normalization, tighter lobes should be brighter
* (InScatterPower + 2.0f) / 8.0f
// Mask by shadowing, exaggerated
* SelfShadowing * SelfShadowing
* VolumeLighting.a;
#endif
// The volume lighting already contains the contribution of the directional light,
// So calculate the amount of light to remove from the volume lighting in order to apply per-pixel self shadowing
// VolumeLighting.a stores all attenuation and opaque shadow factors
float3 SelfShadowingCorrection = DirectionalLightColor.rgb * VolumeLighting.a * (1 - SelfShadowing);
// Combine backscattering and directional light self shadowing
InterpolatedLighting = (BackscatteredLighting + GBuffer.DiffuseColor * max(VolumeLighting.rgb - SelfShadowingCorrection, 0));
}
#endif
return InterpolatedLighting;
}
#endif
#if SIMPLE_FORWARD_SHADING
#define GetEffectiveSkySHDiffuse GetSkySHDiffuseSimple
#else
#define GetEffectiveSkySHDiffuse GetSkySHDiffuse
#endif
/** Computes sky diffuse lighting, including precomputed shadowing. */
void GetSkyLighting(float3 WorldNormal, float2 LightmapUV, out float3 OutDiffuseLighting, out float3 OutSubsurfaceLighting)
{
OutDiffuseLighting = 0;
OutSubsurfaceLighting = 0;
#if ENABLE_SKY_LIGHT
float SkyVisibility = 1;
float GeometryTerm = 1;
float3 SkyLightingNormal = WorldNormal;
#if HQ_TEXTURE_LIGHTMAP || CACHED_POINT_INDIRECT_LIGHTING || CACHED_VOLUME_INDIRECT_LIGHTING
BRANCH
if (View.SkyLightParameters.x > 0)
{
#if HQ_TEXTURE_LIGHTMAP
// Bent normal from precomputed texture
float4 WorldSkyBentNormalAndOcclusion = GetSkyBentNormalAndOcclusion(LightmapUV * float2(1, 2));
// Renormalize as vector was quantized and compressed
float3 NormalizedBentNormal = normalize(WorldSkyBentNormalAndOcclusion.xyz);
SkyVisibility = WorldSkyBentNormalAndOcclusion.w;
#elif CACHED_POINT_INDIRECT_LIGHTING || CACHED_VOLUME_INDIRECT_LIGHTING
// Bent normal from the indirect lighting cache - one value for the whole object
float3 NormalizedBentNormal = PrecomputedLightingBuffer.PointSkyBentNormal.xyz;
SkyVisibility = PrecomputedLightingBuffer.PointSkyBentNormal.w;
#endif
#if (MATERIALBLENDING_TRANSLUCENT || MATERIALBLENDING_ADDITIVE) && (TRANSLUCENCY_LIGHTING_VOLUMETRIC_NONDIRECTIONAL || TRANSLUCENCY_LIGHTING_VOLUMETRIC_PERVERTEX_NONDIRECTIONAL)
// NonDirectional lighting can't depend on the normal
SkyLightingNormal = NormalizedBentNormal;
#else
// Weight toward the material normal to increase directionality
float BentNormalWeightFactor = 1 - (1 - SkyVisibility) * (1 - SkyVisibility);
// We are lerping between the inputs of two lighting scenarios based on occlusion
// In the mostly unoccluded case, evaluate sky lighting with the material normal, because it has higher detail
// In the mostly occluded case, evaluate sky lighting with the bent normal, because it is a better representation of the incoming lighting
// Then treat the lighting evaluated along the bent normal as an area light, so we must apply the lambert term
SkyLightingNormal = lerp(NormalizedBentNormal, WorldNormal, BentNormalWeightFactor);
float DotProductFactor = lerp(saturate(dot(NormalizedBentNormal, WorldNormal)), 1, BentNormalWeightFactor);
// Account for darkening due to the geometry term
GeometryTerm = DotProductFactor;
#endif
}
#endif
// Compute the preconvolved incoming lighting with the bent normal direction
float3 DiffuseLookup = GetEffectiveSkySHDiffuse(SkyLightingNormal) * ResolvedView.SkyLightColor.rgb;
// Apply AO to the sky diffuse
OutDiffuseLighting += DiffuseLookup * (SkyVisibility * GeometryTerm);
#if MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE
float3 BackfaceDiffuseLookup = GetEffectiveSkySHDiffuse(-WorldNormal) * ResolvedView.SkyLightColor.rgb;
OutSubsurfaceLighting += BackfaceDiffuseLookup * SkyVisibility;
#endif
#endif
}
#if SUPPORTS_INDEPENDENT_SAMPLERS
#define ILCSharedSampler1 PrecomputedLightingBuffer.IndirectLightingCacheTextureSampler0
#define ILCSharedSampler2 PrecomputedLightingBuffer.IndirectLightingCacheTextureSampler0
#else
#define ILCSharedSampler1 PrecomputedLightingBuffer.IndirectLightingCacheTextureSampler1
#define ILCSharedSampler2 PrecomputedLightingBuffer.IndirectLightingCacheTextureSampler2
#endif
/** Calculates indirect lighting contribution on this object from precomputed data. */
void GetPrecomputedIndirectLightingAndSkyLight(
FMaterialPixelParameters MaterialParameters,
FVertexFactoryInterpolantsVSToPS Interpolants,
FBasePassInterpolantsVSToPS BasePassInterpolants,
float3 DiffuseDir,
out float3 OutDiffuseLighting,
out float3 OutSubsurfaceLighting,
out float OutIndirectIrradiance)
{
OutIndirectIrradiance = 0;
OutDiffuseLighting = 0;
OutSubsurfaceLighting = 0;
float2 SkyOcclusionUV = 0;
// Method for movable components which want to use a volume texture of interpolated SH samples
#if CACHED_VOLUME_INDIRECT_LIGHTING
// Compute volume texture UVs from world position
float3 VolumeUVs = MaterialParameters.AbsoluteWorldPosition * PrecomputedLightingBuffer.IndirectLightingCachePrimitiveScale + PrecomputedLightingBuffer.IndirectLightingCachePrimitiveAdd;
// Clamp UV to be within the valid region
// Pixels outside of the object's bounding box would read garbage otherwise
VolumeUVs = clamp(VolumeUVs, PrecomputedLightingBuffer.IndirectLightingCacheMinUV, PrecomputedLightingBuffer.IndirectLightingCacheMaxUV);
float4 Vector0 = Texture3DSample(PrecomputedLightingBuffer.IndirectLightingCacheTexture0, PrecomputedLightingBuffer.IndirectLightingCacheTextureSampler0, VolumeUVs);
// For debugging
#define AMBIENTONLY 0
#if AMBIENTONLY
OutDiffuseLighting = Vector0.rgb / SHAmbientFunction() / PI;
#else
float4 Vector1 = Texture3DSample(PrecomputedLightingBuffer.IndirectLightingCacheTexture1, ILCSharedSampler1, VolumeUVs);
float4 Vector2 = Texture3DSample(PrecomputedLightingBuffer.IndirectLightingCacheTexture2, ILCSharedSampler2, VolumeUVs);
// Construct the SH environment
FTwoBandSHVectorRGB CachedSH;
CachedSH.R.V = float4(Vector0.x, Vector1.x, Vector2.x, Vector0.w);
CachedSH.G.V = float4(Vector0.y, Vector1.y, Vector2.y, Vector1.w);
CachedSH.B.V = float4(Vector0.z, Vector1.z, Vector2.z, Vector2.w);
// Diffuse convolution
FTwoBandSHVector DiffuseTransferSH = CalcDiffuseTransferSH(DiffuseDir, 1);
OutDiffuseLighting = max(half3(0,0,0), DotSH(CachedSH, DiffuseTransferSH)) / PI;
#if MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE
FTwoBandSHVector SubsurfaceTransferSH = CalcDiffuseTransferSH(-DiffuseDir, 1);
OutSubsurfaceLighting += max(half3(0,0,0), DotSH(CachedSH, SubsurfaceTransferSH)) / PI;
#endif
#endif
// Method for movable components which want to use a single interpolated SH sample
#elif CACHED_POINT_INDIRECT_LIGHTING
#if TRANSLUCENCY_LIGHTING_VOLUMETRIC_NONDIRECTIONAL
FOneBandSHVectorRGB PointIndirectLighting;
PointIndirectLighting.R.V = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[0].x;
PointIndirectLighting.G.V = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[1].x;
PointIndirectLighting.B.V = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[2].x;
FOneBandSHVector DiffuseTransferSH = CalcDiffuseTransferSH1(1);
OutDiffuseLighting = DotSH1(PointIndirectLighting, DiffuseTransferSH);
#if MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE
FOneBandSHVector SubsurfaceTransferSH = CalcDiffuseTransferSH1(1);
OutSubsurfaceLighting += DotSH1(PointIndirectLighting, SubsurfaceTransferSH);
#endif
#else
FThreeBandSHVectorRGB PointIndirectLighting;
PointIndirectLighting.R.V0 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[0];
PointIndirectLighting.R.V1 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients1[0];
PointIndirectLighting.R.V2 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients2[0];
PointIndirectLighting.G.V0 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[1];
PointIndirectLighting.G.V1 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients1[1];
PointIndirectLighting.G.V2 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients2[1];
PointIndirectLighting.B.V0 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[2];
PointIndirectLighting.B.V1 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients1[2];
PointIndirectLighting.B.V2 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients2[2];
FThreeBandSHVector DiffuseTransferSH = CalcDiffuseTransferSH3(DiffuseDir, 1);
// Compute diffuse lighting which takes the normal into account
OutDiffuseLighting = max(half3(0,0,0), DotSH3(PointIndirectLighting, DiffuseTransferSH));
#if MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE
FThreeBandSHVector SubsurfaceTransferSH = CalcDiffuseTransferSH3(-DiffuseDir, 1);
OutSubsurfaceLighting += max(half3(0,0,0), DotSH3(PointIndirectLighting, SubsurfaceTransferSH));
#endif
#endif
// High quality texture lightmaps
#elif HQ_TEXTURE_LIGHTMAP
float2 LightmapUV0, LightmapUV1;
GetLightMapCoordinates(Interpolants, LightmapUV0, LightmapUV1);
SkyOcclusionUV = LightmapUV0;
GetLightMapColorHQ(LightmapUV0, LightmapUV1, DiffuseDir, OutDiffuseLighting, OutSubsurfaceLighting);
// Low quality texture lightmaps
#elif LQ_TEXTURE_LIGHTMAP
float2 LightmapUV0, LightmapUV1;
GetLightMapCoordinates(Interpolants, LightmapUV0, LightmapUV1);
OutDiffuseLighting = GetLightMapColorLQ(LightmapUV0, LightmapUV1, DiffuseDir).rgb;
#endif
// Apply indirect lighting scale while we have only accumulated lightmaps
OutDiffuseLighting *= View.IndirectLightingColorScale;
float3 SkyDiffuseLighting;
float3 SkySubsurfaceLighting;
GetSkyLighting(DiffuseDir, SkyOcclusionUV, SkyDiffuseLighting, SkySubsurfaceLighting);
OutSubsurfaceLighting += SkySubsurfaceLighting;
// Sky lighting must contribute to IndirectIrradiance for ReflectionEnvironment lightmap mixing
OutDiffuseLighting += SkyDiffuseLighting;
#if HQ_TEXTURE_LIGHTMAP || LQ_TEXTURE_LIGHTMAP || CACHED_VOLUME_INDIRECT_LIGHTING || CACHED_POINT_INDIRECT_LIGHTING
OutIndirectIrradiance = Luminance(OutDiffuseLighting);
#endif
}
#if SIMPLE_FORWARD_DIRECTIONAL_LIGHT
float3 GetSimpleForwardLightingDirectionalLight(FGBufferData GBuffer, float3 DiffuseColor, float3 SpecularColor, float Roughness, float3 WorldNormal, float3 CameraVector)
{
float3 V = -CameraVector;
float3 N = WorldNormal;
float3 L = ResolvedView.DirectionalLightDirection;
float NoL = saturate( dot( N, L ) );
float3 LightColor = ResolvedView.DirectionalLightColor.rgb * PI;
// Not computing specular, material was forced fully rough
float3 DiffuseLighting = Diffuse_Lambert( DiffuseColor );
float3 SubsurfaceLighting = SubsurfaceShading(GBuffer, L, V, N, 1.0f, uint2(0, 0));
return LightColor * NoL * (DiffuseLighting + SubsurfaceLighting);
}
#endif
#if USE_EDITOR_COMPOSITING
bool bEnableEditorPrimitiveDepthTest;
int MSAASampleCount;
// depth in the red channel in DeviceZ
Texture2D FilteredSceneDepthTexture;
SamplerState FilteredSceneDepthTextureSampler;
#endif
// @return 0:translucent..1:opaque
float ClipForEditorPrimitives(FMaterialPixelParameters MaterialParameters)
{
float Ret = 1;
#if USE_EDITOR_COMPOSITING && (FEATURE_LEVEL >= FEATURE_LEVEL_SM4 || MOBILE_EMULATION)
// Depth test manually if compositing editor primitives since the depth buffer is different (MSAA only)
BRANCH
if (bEnableEditorPrimitiveDepthTest)
{
#if HAS_INVERTED_Z_BUFFER
//@todo-briank
bool bIsPerspective = (ResolvedView.ViewToClip._m33 < 1.0f);
#endif // HAS_INVERTED_Z_BUFFER
// dejitter the sample position and make a filtered lookup - for planes this allows to reconstruct a much less jittery depth comparison function, it however doesn't fix silhuetes
float DeviceZ = Texture2DSampleLevel(FilteredSceneDepthTexture, FilteredSceneDepthTextureSampler, (MaterialParameters.SvPosition.xy - View.TemporalAAParams.zw) * ResolvedView.BufferSizeAndInvSize.zw, 0).r;
float PixelDeviceZ = MaterialParameters.SvPosition.z;
// Soft Bias with DeviceZ for best quality
const float DeviceDepthFade = 0.00005f;
// 0.5f is to bias around the actual value, 1 or 0 are another option
Ret = saturate(0.5f - (DeviceZ - PixelDeviceZ) / DeviceDepthFade);
}
#endif // USE_EDITOR_COMPOSITING && (FEATURE_LEVEL >= FEATURE_LEVEL_SM4 || MOBILE_EMULATION)
// Note: multiple returns cause strange HLSL compiler error for CV_Coverage in later code
return Ret;
}
#if EDITOR_ALPHA2COVERAGE != 0
uint CustomAlpha2Coverage(inout float4 InOutColor)
{
uint MaskedCoverage = 0xff;
MaskedCoverage = 0;
uint EnabledSampleCount = 1;
// todo: support non 4xMSAA as well
// conservatively on but can be 0 if the opacity is too low
if(InOutColor.a > 0.01f) { MaskedCoverage |= 0x1; }
if(InOutColor.a > 0.25f) { MaskedCoverage |= 0x2; ++EnabledSampleCount; }
if(InOutColor.a > 0.50f) { MaskedCoverage |= 0x4; ++EnabledSampleCount; }
if(InOutColor.a > 0.75f) { MaskedCoverage |= 0x8; ++EnabledSampleCount; }
// renormalize to make this sample the correct weight
InOutColor *= (float)MSAASampleCount / EnabledSampleCount;
return MaskedCoverage;
}
#endif
void ApplyPixelDepthOffsetForBasePass(inout FMaterialPixelParameters MaterialParameters, FPixelMaterialInputs PixelMaterialInputs, inout FBasePassInterpolantsVSToPS BasePassInterpolants, out float OutDepth)
{
float PixelDepthOffset = ApplyPixelDepthOffsetToMaterialParameters(MaterialParameters, PixelMaterialInputs, OutDepth);
#if WRITES_VELOCITY_TO_GBUFFER
BasePassInterpolants.VelocityPrevScreenPosition.w += PixelDepthOffset;
#if WRITES_VELOCITY_TO_GBUFFER_USE_POS_INTERPOLATOR
BasePassInterpolants.VelocityScreenPosition.w += PixelDepthOffset;
#endif
#endif
}
#if USES_GBUFFER
// The selective output mask can only depend on defines, since the shadow will not export the data.
uint GetSelectiveOutputMask()
{
uint Mask = 0;
#if !WRITES_CUSTOMDATA_TO_GBUFFER
Mask |= SKIP_CUSTOMDATA_MASK;
#endif
#if !GBUFFER_HAS_PRECSHADOWFACTOR
Mask |= SKIP_PRECSHADOW_MASK;
#endif
#if (GBUFFER_HAS_PRECSHADOWFACTOR && WRITES_PRECSHADOWFACTOR_ZERO)
Mask |= ZERO_PRECSHADOW_MASK;
#endif
#if !WRITES_VELOCITY_TO_GBUFFER
Mask |= SKIP_VELOCITY_MASK;
#endif
return Mask;
}
#endif // USES_GBUFFER
// is called in MainPS() from PixelShaderOutputCommon.usf
void FPixelShaderInOut_MainPS(
FVertexFactoryInterpolantsVSToPS Interpolants,
FBasePassInterpolantsVSToPS BasePassInterpolants,
in FPixelShaderIn In,
inout FPixelShaderOut Out)
{
#if INSTANCED_STEREO
ResolvedView = ResolveView(GetEyeIndex(Interpolants.PackedEyeIndex));
#else
ResolvedView = ResolveView();
#endif
// Velocity
float4 OutVelocity = 0;
// CustomData
float4 OutGBufferD = 0;
// PreShadowFactor
float4 OutGBufferE = 0;
FMaterialPixelParameters MaterialParameters = GetMaterialPixelParameters(Interpolants, In.SvPosition);
FPixelMaterialInputs PixelMaterialInputs;
#if HQ_TEXTURE_LIGHTMAP && USES_AO_MATERIAL_MASK && !MATERIAL_SHADINGMODEL_UNLIT
float2 LightmapUV0, LightmapUV1;
GetLightMapCoordinates(Interpolants, LightmapUV0, LightmapUV1);
// Must be computed before BaseColor, Normal, etc are evaluated
MaterialParameters.AOMaterialMask = GetAOMaterialMask(LightmapUV0 * float2(1, 2));
#endif
#if USE_WORLD_POSITION_EXCLUDING_SHADER_OFFSETS
{
float4 ScreenPosition = SvPositionToResolvedScreenPosition(In.SvPosition);
float3 TranslatedWorldPosition = SvPositionToResolvedTranslatedWorld(In.SvPosition);
CalcMaterialParametersEx(MaterialParameters, PixelMaterialInputs, In.SvPosition, ScreenPosition, In.bIsFrontFace, TranslatedWorldPosition, BasePassInterpolants.PixelPositionExcludingWPO);
}
#else
{
float4 ScreenPosition = SvPositionToResolvedScreenPosition(In.SvPosition);
float3 TranslatedWorldPosition = SvPositionToResolvedTranslatedWorld(In.SvPosition);
CalcMaterialParametersEx(MaterialParameters, PixelMaterialInputs, In.SvPosition, ScreenPosition, In.bIsFrontFace, TranslatedWorldPosition, TranslatedWorldPosition);
}
#endif
#if USE_EDITOR_COMPOSITING && (FEATURE_LEVEL >= FEATURE_LEVEL_SM4 || MOBILE_EMULATION)
const bool bEditorWeightedZBuffering = true;
#else
const bool bEditorWeightedZBuffering = false;
#endif
#if OUTPUT_PIXEL_DEPTH_OFFSET
ApplyPixelDepthOffsetForBasePass(MaterialParameters, PixelMaterialInputs, BasePassInterpolants, Out.Depth);
#endif
//Clip if the blend mode requires it.
#if !EARLY_Z_PASS_ONLY_MATERIAL_MASKING
if(!bEditorWeightedZBuffering)
{
#if MATERIALBLENDING_MASKED_USING_COVERAGE
Out.Coverage = DiscardMaterialWithPixelCoverage(MaterialParameters, PixelMaterialInputs);
#else
GetMaterialCoverageAndClipping(MaterialParameters, PixelMaterialInputs);
#endif
}
#endif
// Store the results in local variables and reuse instead of calling the functions multiple times.
half3 BaseColor = GetMaterialBaseColor(PixelMaterialInputs);
half Metallic = GetMaterialMetallic(PixelMaterialInputs);
half Specular = GetMaterialSpecular(PixelMaterialInputs);
float MaterialAO = GetMaterialAmbientOcclusion(PixelMaterialInputs);
float Roughness = GetMaterialRoughness(PixelMaterialInputs);
// 0..1, SubsurfaceProfileId = int(x * 255)
float SubsurfaceProfile = 0;
// If we don't use this shading model the color should be black (don't generate shader code for unused data, don't do indirectlighting cache lighting with this color).
float3 SubsurfaceColor = 0;
#if MATERIAL_SHADINGMODEL_SUBSURFACE || MATERIAL_SHADINGMODEL_PREINTEGRATED_SKIN || MATERIAL_SHADINGMODEL_SUBSURFACE_PROFILE || MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE || MATERIAL_SHADINGMODEL_CLOTH
{
float4 SubsurfaceData = GetMaterialSubsurfaceData(MaterialParameters);
#if MATERIAL_SHADINGMODEL_SUBSURFACE || MATERIAL_SHADINGMODEL_PREINTEGRATED_SKIN || MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE
SubsurfaceColor = SubsurfaceData.rgb * View.DiffuseOverrideParameter.w + View.DiffuseOverrideParameter.xyz;
#elif MATERIAL_SHADINGMODEL_CLOTH
SubsurfaceColor = SubsurfaceData.rgb;
#endif
SubsurfaceProfile = SubsurfaceData.a;
}
#endif
#if USE_DBUFFER && MATERIALDECALRESPONSEMASK && !MATERIALBLENDING_ANY_TRANSLUCENT
// apply decals from the DBuffer
#if SM5_PROFILE
//Temporary workaround to avoid crashes on AMD, revert back to BRANCH
FLATTEN
#else
BRANCH
#endif
if(Primitive.DecalReceiverMask > 0 && View.ShowDecalsMask > 0)
{
#if PLATFORM_SUPPORTS_RENDERTARGET_WRITE_MASK
uint RTWriteMaskBit = DecodeRTWriteMaskTexture(In.SvPosition.xy, DBufferMask);
if(RTWriteMaskBit)
#endif
{
float2 NDC = MaterialParameters.ScreenPosition.xy / MaterialParameters.ScreenPosition.w;
float2 ScreenUV = NDC * ResolvedView.ScreenPositionScaleBias.xy + ResolvedView.ScreenPositionScaleBias.wz;
FDBufferData DBufferData = GetDBufferData(ScreenUV);
// the material can disable the DBuffer effects for better performance or control
if((MATERIALDECALRESPONSEMASK & 0x1) == 0) { DBufferData.PreMulColor = 0; DBufferData.ColorOpacity = 1; }
if((MATERIALDECALRESPONSEMASK & 0x2) == 0) { DBufferData.PreMulWorldNormal = 0; DBufferData.NormalOpacity = 1; }
if((MATERIALDECALRESPONSEMASK & 0x4) == 0) { DBufferData.PreMulRoughness = 0; DBufferData.RoughnessOpacity = 1; }
ApplyDBufferData(DBufferData, MaterialParameters.WorldNormal, SubsurfaceColor, Roughness, BaseColor, Metallic, Specular);
}
}
#endif
float3 LocalBaseColor = BaseColor;
float LocalSpecular = Specular;
half Opacity = GetMaterialOpacity(PixelMaterialInputs);
FGBufferData GBuffer = (FGBufferData)0;
GBuffer.WorldNormal = MaterialParameters.WorldNormal;
GBuffer.BaseColor = BaseColor;
GBuffer.Metallic = Metallic;
GBuffer.Specular = Specular;
GBuffer.Roughness = Roughness;
GBuffer.GBufferAO = MaterialAO;
GBuffer.PerObjectGBufferData = Primitive.PerObjectGBufferData;
GBuffer.Depth = MaterialParameters.ScreenPosition.w;
GBuffer.PrecomputedShadowFactors = GetPrecomputedShadowMasks(Interpolants);
#if MATERIAL_SHADINGMODEL_UNLIT
GBuffer.ShadingModelID = SHADINGMODELID_UNLIT;
#elif MATERIAL_SHADINGMODEL_DEFAULT_LIT
GBuffer.ShadingModelID = SHADINGMODELID_DEFAULT_LIT;
#elif MATERIAL_SHADINGMODEL_SUBSURFACE
GBuffer.ShadingModelID = SHADINGMODELID_SUBSURFACE;
GBuffer.CustomData.rgb = EncodeSubsurfaceColor(SubsurfaceColor);
GBuffer.CustomData.a = Opacity;
#elif MATERIAL_SHADINGMODEL_PREINTEGRATED_SKIN
GBuffer.ShadingModelID = SHADINGMODELID_PREINTEGRATED_SKIN;
GBuffer.CustomData.rgb = EncodeSubsurfaceColor(SubsurfaceColor);
GBuffer.CustomData.a = Opacity;
#elif MATERIAL_SHADINGMODEL_SUBSURFACE_PROFILE
// Optimization: if opacity is 0 then revert to default shading model
#if SUBSURFACE_PROFILE_OPACITY_THRESHOLD
if (Opacity > 0.0)
#endif
{
GBuffer.ShadingModelID = SHADINGMODELID_SUBSURFACE_PROFILE;
GBuffer.CustomData.rgb = EncodeSubsurfaceProfile(SubsurfaceProfile);
GBuffer.CustomData.a = Opacity;
}
#if SUBSURFACE_PROFILE_OPACITY_THRESHOLD
else
{
GBuffer.ShadingModelID = SHADINGMODELID_DEFAULT_LIT;
GBuffer.CustomData = 0;
}
#endif
#elif MATERIAL_SHADINGMODEL_CLEAR_COAT
{
GBuffer.ShadingModelID = SHADINGMODELID_CLEAR_COAT;
float ClearCoat = saturate( GetMaterialCustomData0(MaterialParameters) );
float ClearCoatRoughness = saturate( GetMaterialCustomData1(MaterialParameters) );
float MetalSpec = 0.9;
float NoV = saturate( dot( MaterialParameters.WorldNormal, MaterialParameters.CameraVector ) );
// Approximation of refraction's effect on EnvBRDF
float RefractionScale = ( (NoV * 0.5 + 0.5) * NoV - 1 ) * saturate( 1.25 - 1.25 * Roughness ) + 1;
// Approximation of absorption integral, tuned for Roughness=0.4
float3 AbsorptionColor = BaseColor * (1 / MetalSpec);
float3 Absorption = AbsorptionColor * ( (NoV - 1) * 0.85 * ( 1 - lerp( AbsorptionColor, Square(AbsorptionColor), -0.78 ) ) + 1 );
float F0 = 0.04;
float Fc = Pow5( 1 - NoV );
float F = Fc + (1 - Fc) * F0;
float LayerAttenuation = lerp( 1, (1 - F), ClearCoat );
BaseColor *= LayerAttenuation;
GBuffer.BaseColor = lerp( BaseColor, MetalSpec * Absorption * RefractionScale, Metallic * ClearCoat );
GBuffer.Specular *= lerp( 1, RefractionScale, ClearCoat );
GBuffer.CustomData.x = ClearCoat;
GBuffer.CustomData.y = ClearCoatRoughness;
#if CLEAR_COAT_BOTTOM_NORMAL
{
float2 oct2 = UnitVectorToOctahedron(GBuffer.WorldNormal);
#if NUM_MATERIAL_OUTPUTS_CLEARCOATBOTTOMNORMAL > 0
#if MATERIAL_TANGENTSPACENORMAL
float3 tempnormal = normalize(TransformTangentVectorToWorld( MaterialParameters.TangentToWorld, ClearCoatBottomNormal0(MaterialParameters) ));
#else
float3 tempnormal = ClearCoatBottomNormal0(MaterialParameters);
#endif
float2 oct1 = UnitVectorToOctahedron(tempnormal);
float2 oct3 = ( (oct1 - oct2) * 0.5 ) + (128.0/255.0);
GBuffer.CustomData.a = oct3.x;
GBuffer.CustomData.z = oct3.y;
#else
GBuffer.CustomData.a = 128.0/255.0;
GBuffer.CustomData.z = 128.0/255.0;
#endif
}
#endif
}
#elif MATERIAL_SHADINGMODEL_TWOSIDED_FOLIAGE
GBuffer.ShadingModelID = SHADINGMODELID_TWOSIDED_FOLIAGE;
GBuffer.CustomData.rgb = EncodeSubsurfaceColor(SubsurfaceColor);
GBuffer.CustomData.a = Opacity;
#elif MATERIAL_SHADINGMODEL_HAIR
GBuffer.ShadingModelID = SHADINGMODELID_HAIR;
GBuffer.CustomData.xy = UnitVectorToOctahedron( MaterialParameters.WorldNormal ) * 0.5 + 0.5;
GBuffer.CustomData.z = saturate( GetMaterialCustomData0(MaterialParameters) ); // Backlit
#elif MATERIAL_SHADINGMODEL_CLOTH
GBuffer.ShadingModelID = SHADINGMODELID_CLOTH;
GBuffer.CustomData.rgb = SubsurfaceColor;
GBuffer.CustomData.a = saturate( GetMaterialCustomData0(MaterialParameters) ); // Cloth
GBuffer.IndirectIrradiance *= 1 - GBuffer.CustomData.a;
#elif MATERIAL_SHADINGMODEL_EYE
GBuffer.ShadingModelID = SHADINGMODELID_EYE;
#if NUM_MATERIAL_OUTPUTS_GETTANGENTOUTPUT > 0
float3 Tangent = GetTangentOutput0(MaterialParameters);
GBuffer.CustomData.xy = UnitVectorToOctahedron( normalize(Tangent) ) * 0.5 + 0.5;
#endif
GBuffer.CustomData.z = saturate( GetMaterialCustomData0(MaterialParameters) ); // Iris Mask
GBuffer.CustomData.w = saturate( GetMaterialCustomData1(MaterialParameters) ); // Iris Distance
#else
// missing shading model, compiler should report ShadingModelID is not set
#endif
#if USES_GBUFFER
GBuffer.SelectiveOutputMask = GetSelectiveOutputMask();
#if WRITES_VELOCITY_TO_GBUFFER
{
// 2d velocity, includes camera an object motion
#if WRITES_VELOCITY_TO_GBUFFER_USE_POS_INTERPOLATOR
float2 Velocity = Calculate2DVelocity(BasePassInterpolants.VelocityScreenPosition, BasePassInterpolants.VelocityPrevScreenPosition);
#else
float2 Velocity = Calculate2DVelocity(MaterialParameters.ScreenPosition, BasePassInterpolants.VelocityPrevScreenPosition);
#endif
// Make sure not to touch 0,0 which is clear color
GBuffer.Velocity = float4(EncodeVelocityToTexture(Velocity), 0, 0) * BasePassInterpolants.VelocityPrevScreenPosition.z;
}
#else
GBuffer.Velocity = 0;
#endif
#endif
// So that the following code can still use DiffuseColor and SpecularColor.
GBuffer.SpecularColor = lerp(0.08 * LocalSpecular.xxx, LocalBaseColor, Metallic.xxx);
#if MATERIAL_NORMAL_CURVATURE_TO_ROUGHNESS
float GeometricAARoughness = NormalCurvatureToRoughness(MaterialParameters.WorldNormal);
GBuffer.Roughness = max(GBuffer.Roughness, GeometricAARoughness);
#if MATERIAL_SHADINGMODEL_CLEAR_COAT
GBuffer.CustomData.y = max(GBuffer.CustomData.y, GeometricAARoughness);
#endif
#endif
#if MATERIAL_SHADINGMODEL_SUBSURFACE_PROFILE && USES_GBUFFER
// SubsurfaceProfile applies the BaseColor in a later pass. Any lighting output in the base pass needs
// to separate specualar and diffuse lighting in a checkerboard pattern
bool bChecker = CheckerFromPixelPos(MaterialParameters.SvPosition.xy);
if ( GBuffer.ShadingModelID == SHADINGMODELID_SUBSURFACE_PROFILE )
{
AdjustBaseColorAndSpecularColorForSubsurfaceProfileLighting(LocalBaseColor, GBuffer.SpecularColor, LocalSpecular, bChecker);
}
#endif
GBuffer.DiffuseColor = LocalBaseColor - LocalBaseColor * Metallic;
#if USE_DEVELOPMENT_SHADERS
{
// this feature is only needed for development/editor - we can compile it out for a shipping build (see r.CompileShadersForDevelopment cvar help)
GBuffer.DiffuseColor = GBuffer.DiffuseColor * View.DiffuseOverrideParameter.w + View.DiffuseOverrideParameter.xyz;
GBuffer.SpecularColor = GBuffer.SpecularColor * View.SpecularOverrideParameter.w + View.SpecularOverrideParameter.xyz;
}
#endif
#if FORCE_FULLY_ROUGH
// Factors derived from EnvBRDFApprox( SpecularColor, 1, 1 ) == SpecularColor * 0.4524 - 0.0024
GBuffer.DiffuseColor += GBuffer.SpecularColor * 0.45;
GBuffer.SpecularColor = 0;
GBuffer.Roughness = 1;
#endif
half3 DiffuseColor = 0;
half3 Color = 0;
float IndirectIrradiance = 0;
#if !MATERIAL_SHADINGMODEL_UNLIT
float3 DiffuseDir = MaterialParameters.WorldNormal;
float3 DiffuseColorForIndirect = GBuffer.DiffuseColor;
#if MATERIAL_SHADINGMODEL_SUBSURFACE || MATERIAL_SHADINGMODEL_PREINTEGRATED_SKIN
// Add subsurface energy to diffuse
//@todo - better subsurface handling for these shading models with skylight and precomputed GI
DiffuseColorForIndirect += SubsurfaceColor;
#endif
#if MATERIAL_SHADINGMODEL_CLOTH
DiffuseColorForIndirect += SubsurfaceColor * saturate( GetMaterialCustomData0(MaterialParameters) );
#endif
#if MATERIAL_SHADINGMODEL_HAIR
{
float3 N = MaterialParameters.WorldNormal;
float3 V = MaterialParameters.CameraVector;
float3 L = normalize( V - N * dot(V,N) );
DiffuseDir = L;
DiffuseColorForIndirect = 2*PI * HairShading( GBuffer, L, V, N, 1, 0, 0.2, uint2(0,0) );
}
#endif
float3 DiffuseIndirectLighting;
float3 SubsurfaceIndirectLighting;
GetPrecomputedIndirectLightingAndSkyLight(MaterialParameters, Interpolants, BasePassInterpolants, DiffuseDir, DiffuseIndirectLighting, SubsurfaceIndirectLighting, IndirectIrradiance);
float IndirectOcclusion = 1.0f;
float2 NearestResolvedDepthScreenUV = 0;
#if FORWARD_SHADING && (MATERIALBLENDING_SOLID || MATERIALBLENDING_MASKED)
float2 NDC = MaterialParameters.ScreenPosition.xy / MaterialParameters.ScreenPosition.w;
float2 ScreenUV = NDC * ResolvedView.ScreenPositionScaleBias.xy + ResolvedView.ScreenPositionScaleBias.wz;
NearestResolvedDepthScreenUV = CalculateNearestResolvedDepthScreenUV(ScreenUV, MaterialParameters.ScreenPosition.w);
IndirectOcclusion = GetIndirectOcclusion(NearestResolvedDepthScreenUV, GBuffer);
DiffuseIndirectLighting *= IndirectOcclusion;
SubsurfaceIndirectLighting *= IndirectOcclusion;
IndirectIrradiance *= IndirectOcclusion;
#endif
DiffuseColor += (DiffuseIndirectLighting * DiffuseColorForIndirect + SubsurfaceIndirectLighting * SubsurfaceColor) * MaterialAO;
#if TRANSLUCENCY_PERVERTEX_FORWARD_SHADING
Color += BasePassInterpolants.VertexDiffuseLighting * GBuffer.DiffuseColor;
#elif FORWARD_SHADING || TRANSLUCENCY_LIGHTING_SURFACE_FORWARDSHADING || TRANSLUCENCY_LIGHTING_SURFACE_LIGHTINGVOLUME
uint GridIndex = 0;
#if INSTANCED_STEREO
const uint EyeIndex = GetEyeIndex(Interpolants.PackedEyeIndex);
#else
const uint EyeIndex = 0;
#endif
#if FEATURE_LEVEL >= FEATURE_LEVEL_SM5
GridIndex = ComputeLightGridCellIndex((uint2)(MaterialParameters.SvPosition.xy - ResolvedView.ViewRectMin.xy), MaterialParameters.SvPosition.w, EyeIndex);
#if FORWARD_SHADING || TRANSLUCENCY_LIGHTING_SURFACE_FORWARDSHADING
Color += GetForwardDirectLighting(GridIndex, MaterialParameters.AbsoluteWorldPosition, MaterialParameters.CameraVector, GBuffer, NearestResolvedDepthScreenUV, EyeIndex);
#endif
#endif
Color += GetImageBasedReflectionLighting(MaterialParameters, GBuffer.Roughness, GBuffer.SpecularColor, IndirectIrradiance, GridIndex, EyeIndex) * IndirectOcclusion;
#endif
#if SIMPLE_FORWARD_DIRECTIONAL_LIGHT
float3 DirectionalLighting = GetSimpleForwardLightingDirectionalLight(
GBuffer,
DiffuseColorForIndirect,
GBuffer.SpecularColor,
GBuffer.Roughness,
MaterialParameters.WorldNormal,
MaterialParameters.CameraVector);
#if STATICLIGHTING_SIGNEDDISTANCEFIELD
DirectionalLighting *= GBuffer.PrecomputedShadowFactors.x;
#elif CACHED_POINT_INDIRECT_LIGHTING
DirectionalLighting *= PrecomputedLightingBuffer.DirectionalLightShadowing;
#endif
Color += DirectionalLighting;
#endif
#endif
#if NEEDS_BASEPASS_VERTEX_FOGGING
float4 Fogging = BasePassInterpolants.VertexFog;
#elif NEEDS_BASEPASS_PIXEL_FOGGING
float4 Fogging = CalculateHeightFog(MaterialParameters.WorldPosition_CamRelative);
#else
float4 Fogging = float4(0,0,0,1);
#endif
// Volume lighting for lit translucency
#if (MATERIAL_SHADINGMODEL_DEFAULT_LIT || MATERIAL_SHADINGMODEL_SUBSURFACE) && (MATERIALBLENDING_TRANSLUCENT || MATERIALBLENDING_ADDITIVE) && !SIMPLE_FORWARD_SHADING && !FORWARD_SHADING
Color += GetTranslucencyVolumeLighting(MaterialParameters, PixelMaterialInputs, BasePassInterpolants, GBuffer, IndirectIrradiance);
#endif
#if !MATERIAL_SHADINGMODEL_UNLIT && USE_DEVELOPMENT_SHADERS
Color = lerp(Color, GBuffer.DiffuseColor + GBuffer.SpecularColor * 0.45, View.UnlitViewmodeMask);
#endif
half3 Emissive = GetMaterialEmissive(PixelMaterialInputs);
#if USE_DEVELOPMENT_SHADERS
// this feature is only needed for development/editor - we can compile it out for a shipping build (see r.CompileShadersForDevelopment cvar help)
#if METAL_SM5_PROFILE || SM5_PROFILE || SM4_PROFILE || METAL_SM4_PROFILE || VULKAN_PROFILE_SM4 || VULKAN_PROFILE_SM5
BRANCH
if (View.OutOfBoundsMask > 0)
{
if (any(abs(MaterialParameters.AbsoluteWorldPosition - Primitive.ObjectWorldPositionAndRadius.xyz) > Primitive.ObjectBounds + 1))
{
float Gradient = frac(dot(MaterialParameters.AbsoluteWorldPosition, float3(.577f, .577f, .577f)) / 500.0f);
Emissive = lerp(float3(1,1,0), float3(0,1,1), Gradient.xxx > .5f);
Opacity = 1;
}
}
#endif
#endif
#if !(MATERIAL_SHADINGMODEL_SUBSURFACE_PROFILE && USES_GBUFFER)
// For non-skin, we just add diffuse and non-diffuse color together, otherwise we need to keep them separate
Color += DiffuseColor;
#endif
Color += Emissive;
#if MATERIALBLENDING_ALPHACOMPOSITE
Out.MRT[0] = half4(Color * Fogging.a + Fogging.rgb * Opacity, Opacity);
Out.MRT[0] = RETURN_COLOR(Out.MRT[0]);
#elif MATERIALBLENDING_TRANSLUCENT
Out.MRT[0] = half4(Color * Fogging.a + Fogging.rgb, Opacity);
Out.MRT[0] = RETURN_COLOR(Out.MRT[0]);
#elif MATERIALBLENDING_ADDITIVE
Out.MRT[0] = half4(Color * Fogging.a * Opacity, 0.0f);
Out.MRT[0] = RETURN_COLOR(Out.MRT[0]);
#elif MATERIALBLENDING_MODULATE
// RETURN_COLOR not needed with modulative blending
half3 FoggedColor = lerp(float3(1, 1, 1), Color, Fogging.aaa * Fogging.aaa);
Out.MRT[0] = half4(FoggedColor, Opacity);
#else
{
FLightAccumulator LightAccumulator = (FLightAccumulator)0;
// Apply vertex fog
Color = Color * Fogging.a + Fogging.rgb;
#if MATERIAL_SHADINGMODEL_SUBSURFACE_PROFILE && USES_GBUFFER
// Apply vertex fog to diffuse color
DiffuseColor = DiffuseColor * Fogging.a + Fogging.rgb;
if (GBuffer.ShadingModelID == SHADINGMODELID_SUBSURFACE_PROFILE &&
View.bSubsurfacePostprocessEnabled > 0 && View.bCheckerboardSubsurfaceProfileRendering > 0 )
{
// Adjust for checkerboard. only apply non-diffuse lighting (including emissive)
// to the specular component, otherwise lighting is applied twice
Color *= !bChecker;
}
LightAccumulator_Add(LightAccumulator, Color + DiffuseColor, DiffuseColor, 1.0f, GBuffer.ShadingModelID == SHADINGMODELID_SUBSURFACE_PROFILE);
#else
LightAccumulator_Add(LightAccumulator, Color, 0, 1.0f, false);
#endif
Out.MRT[0] = RETURN_COLOR(LightAccumulator_GetResult(LightAccumulator));
#if !USES_GBUFFER
// Without deferred shading the SSS pass will not be run to reset scene color alpha for opaque / masked to 0
// Scene color alpha is used by scene captures and planar reflections
Out.MRT[0].a = 0;
#endif
}
#endif
#if USES_GBUFFER
GBuffer.IndirectIrradiance = IndirectIrradiance;
// -0.5 .. 0.5, could be optimzed as lower quality noise would be sufficient
float QuantizationBias = PseudoRandom( MaterialParameters.SvPosition.xy ) - 0.5f;
EncodeGBuffer(GBuffer, Out.MRT[1], Out.MRT[2], Out.MRT[3], OutGBufferD, OutGBufferE, OutVelocity, QuantizationBias);
#endif
if(bEditorWeightedZBuffering)
{
Out.MRT[0].a = 1;
#if MATERIALBLENDING_MASKED
// some material might have a opacity value
Out.MRT[0].a = GetMaterialMaskInputRaw(PixelMaterialInputs);
#endif
// we output premultiplied alpha to we have to darken all 4 channels
Out.MRT[0] *= ClipForEditorPrimitives(MaterialParameters);
#if EDITOR_ALPHA2COVERAGE != 0
// per MSAA sample
if(MSAASampleCount > 1)
{
Out.Coverage = In.Coverage & CustomAlpha2Coverage(Out.MRT[0]);
}
else
{
// no MSAA is handle like per pixel
clip(Out.MRT[0].a - GetMaterialOpacityMaskClipValue());
}
#else
// per pixel
clip(Out.MRT[0].a - GetMaterialOpacityMaskClipValue());
#endif
}
#if USES_GBUFFER
#if GBUFFER_HAS_VELOCITY
Out.MRT[4] = OutVelocity;
#endif
Out.MRT[GBUFFER_HAS_VELOCITY ? 5 : 4] = OutGBufferD;
#if GBUFFER_HAS_PRECSHADOWFACTOR
Out.MRT[GBUFFER_HAS_VELOCITY ? 6 : 5] = OutGBufferE;
#endif
#endif
}
// the following needs to match to the code in FSceneRenderTargets::GetGBufferRenderTargets()
#define PIXELSHADEROUTPUT_BASEPASS 1
#define PIXELSHADEROUTPUT_MRT0 (!USES_GBUFFER || !SELECTIVE_BASEPASS_OUTPUTS || NEEDS_BASEPASS_VERTEX_FOGGING || USES_EMISSIVE_COLOR || ALLOW_STATIC_LIGHTING)
#define PIXELSHADEROUTPUT_MRT1 (USES_GBUFFER && (!SELECTIVE_BASEPASS_OUTPUTS || !MATERIAL_SHADINGMODEL_UNLIT))
#define PIXELSHADEROUTPUT_MRT2 (USES_GBUFFER && (!SELECTIVE_BASEPASS_OUTPUTS || !MATERIAL_SHADINGMODEL_UNLIT))
#define PIXELSHADEROUTPUT_MRT3 (USES_GBUFFER && (!SELECTIVE_BASEPASS_OUTPUTS || !MATERIAL_SHADINGMODEL_UNLIT))
#define PIXELSHADEROUTPUT_A2C ((EDITOR_ALPHA2COVERAGE) != 0)
#define PIXELSHADEROUTPUT_COVERAGE (MATERIALBLENDING_MASKED_USING_COVERAGE)
#if GBUFFER_HAS_VELOCITY
#define PIXELSHADEROUTPUT_MRT4 WRITES_VELOCITY_TO_GBUFFER
#define PIXELSHADEROUTPUT_MRT5 (USES_GBUFFER && (!SELECTIVE_BASEPASS_OUTPUTS || WRITES_CUSTOMDATA_TO_GBUFFER))
#define PIXELSHADEROUTPUT_MRT6 (GBUFFER_HAS_PRECSHADOWFACTOR && (!SELECTIVE_BASEPASS_OUTPUTS || WRITES_PRECSHADOWFACTOR_TO_GBUFFER && !MATERIAL_SHADINGMODEL_UNLIT))
#else //WRITES_VELOCITY_TO_GBUFFER
#define PIXELSHADEROUTPUT_MRT4 (USES_GBUFFER && (!SELECTIVE_BASEPASS_OUTPUTS || WRITES_CUSTOMDATA_TO_GBUFFER))
#define PIXELSHADEROUTPUT_MRT5 (GBUFFER_HAS_PRECSHADOWFACTOR && (!SELECTIVE_BASEPASS_OUTPUTS || WRITES_PRECSHADOWFACTOR_TO_GBUFFER && !MATERIAL_SHADINGMODEL_UNLIT))
#endif //WRITES_VELOCITY_TO_GBUFFER
// all PIXELSHADEROUTPUT_ and "void FPixelShaderInOut_MainPS()" need to be setup before this include
// this include generates the wrapper code to call MainPS(inout FPixelShaderOutput PixelShaderOutput)
#include "PixelShaderOutputCommon.usf"