Files
UnrealEngineUWP/Engine/Source/Runtime/OpenGLDrv/Private/OpenGLDevice.cpp
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

1610 lines
59 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
OpenGLDevice.cpp: OpenGL device RHI implementation.
=============================================================================*/
#include "CoreMinimal.h"
#include "Misc/CommandLine.h"
#include "Misc/ScopeLock.h"
#include "Stats/Stats.h"
#include "Serialization/MemoryWriter.h"
#include "Misc/ConfigCacheIni.h"
#include "HAL/IConsoleManager.h"
#include "RHI.h"
#include "Containers/List.h"
#include "RenderResource.h"
#include "ShaderCore.h"
#include "RenderUtils.h"
#include "ShaderCache.h"
#include "OpenGLDrv.h"
#include "OpenGLDrvPrivate.h"
#include "SceneUtils.h"
#include "HardwareInfo.h"
#ifndef GL_STEREO
#define GL_STEREO 0x0C33
#endif
extern GLint GMaxOpenGLColorSamples;
extern GLint GMaxOpenGLDepthSamples;
extern GLint GMaxOpenGLIntegerSamples;
extern GLint GMaxOpenGLTextureFilterAnisotropic;
extern GLint GMaxOpenGLDrawBuffers;
/** OpenGL texture format table. */
FOpenGLTextureFormat GOpenGLTextureFormats[PF_MAX];
/** Device is necessary for vertex buffers, so they can reach the global device on destruction, and tell it to reset vertex array caches */
static FOpenGLDynamicRHI* PrivateOpenGLDevicePtr = NULL;
/** true if we're not using UBOs. (ES2) */
bool GUseEmulatedUniformBuffers;
void OnQueryCreation( FOpenGLRenderQuery* Query )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->RegisterQuery( Query );
}
void OnQueryDeletion( FOpenGLRenderQuery* Query )
{
if(PrivateOpenGLDevicePtr)
{
PrivateOpenGLDevicePtr->UnregisterQuery( Query );
}
}
void OnQueryInvalidation( void )
{
if(PrivateOpenGLDevicePtr)
{
PrivateOpenGLDevicePtr->InvalidateQueries();
}
}
void OnProgramDeletion( GLint ProgramResource )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->OnProgramDeletion( ProgramResource );
}
void OnVertexBufferDeletion( GLuint VertexBufferResource )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->OnVertexBufferDeletion( VertexBufferResource );
}
void OnIndexBufferDeletion( GLuint IndexBufferResource )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->OnIndexBufferDeletion( IndexBufferResource );
}
void OnPixelBufferDeletion( GLuint PixelBufferResource )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->OnPixelBufferDeletion( PixelBufferResource );
}
void OnUniformBufferDeletion( GLuint UniformBufferResource, uint32 AllocatedSize, bool bStreamDraw, uint32 , uint8* )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->OnUniformBufferDeletion( UniformBufferResource, AllocatedSize, bStreamDraw );
}
void CachedBindArrayBuffer( GLuint Buffer )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->CachedBindArrayBuffer(PrivateOpenGLDevicePtr->GetContextStateForCurrentContext(),Buffer);
}
void CachedBindElementArrayBuffer( GLuint Buffer )
{
check(PrivateOpenGLDevicePtr);
PrivateOpenGLDevicePtr->CachedBindElementArrayBuffer(PrivateOpenGLDevicePtr->GetContextStateForCurrentContext(),Buffer);
}
void CachedBindPixelUnpackBuffer( GLuint Buffer )
{
check(PrivateOpenGLDevicePtr);
if ( FOpenGL::SupportsPixelBuffers() )
{
PrivateOpenGLDevicePtr->CachedBindPixelUnpackBuffer(PrivateOpenGLDevicePtr->GetContextStateForCurrentContext(),Buffer);
}
}
void CachedBindUniformBuffer( GLuint Buffer )
{
check(PrivateOpenGLDevicePtr);
if (FOpenGL::SupportsUniformBuffers())
{
PrivateOpenGLDevicePtr->CachedBindUniformBuffer(PrivateOpenGLDevicePtr->GetContextStateForCurrentContext(),Buffer);
}
}
bool IsUniformBufferBound( GLuint Buffer )
{
check(PrivateOpenGLDevicePtr);
return PrivateOpenGLDevicePtr->IsUniformBufferBound(PrivateOpenGLDevicePtr->GetContextStateForCurrentContext(),Buffer);
}
extern void BeginFrame_UniformBufferPoolCleanup();
extern void BeginFrame_VertexBufferCleanup();
FOpenGLContextState& FOpenGLDynamicRHI::GetContextStateForCurrentContext(bool bAssertIfInvalid)
{
int32 ContextType = (int32)PlatformOpenGLCurrentContext(PlatformDevice);
if (bAssertIfInvalid)
{
check(ContextType >= 0);
}
else if (ContextType < 0)
{
return InvalidContextState;
}
if (ContextType == CONTEXT_Rendering)
{
return RenderingContextState;
}
else
{
return SharedContextState;
}
}
void FOpenGLDynamicRHI::RHIBeginFrame()
{
RHIPrivateBeginFrame();
BeginFrame_UniformBufferPoolCleanup();
BeginFrame_VertexBufferCleanup();
GPUProfilingData.BeginFrame(this);
#if PLATFORM_ANDROID //adding #if since not sure if this is required for any other platform.
//we need to differential between 0 (backbuffer) and lastcolorRT.
FOpenGLContextState& ContextState = GetContextStateForCurrentContext();
ContextState.LastES2ColorRTResource = 0xFFFFFFFF;
PendingState.DepthStencil = 0 ;
#endif
}
void FOpenGLDynamicRHI::RHIEndFrame()
{
GPUProfilingData.EndFrame();
}
void FOpenGLDynamicRHI::RHIBeginScene()
{
// Increment the frame counter. INDEX_NONE is a special value meaning "uninitialized", so if
// we hit it just wrap around to zero.
SceneFrameCounter++;
if (SceneFrameCounter == INDEX_NONE)
{
SceneFrameCounter++;
}
static auto* ResourceTableCachingCvar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("rhi.ResourceTableCaching"));
if (ResourceTableCachingCvar == NULL || ResourceTableCachingCvar->GetValueOnAnyThread() == 1)
{
ResourceTableFrameCounter = SceneFrameCounter;
}
}
void FOpenGLDynamicRHI::RHIEndScene()
{
ResourceTableFrameCounter = INDEX_NONE;
}
bool GDisableOpenGLDebugOutput = false;
// workaround for HTML5.
#if PLATFORM_HTML5
#undef GL_ARB_debug_output
#undef GL_KHR_debug
#endif
#if defined(GL_ARB_debug_output) || defined(GL_KHR_debug)
/**
* Map GL_DEBUG_SOURCE_*_ARB to a human-readable string.
*/
static const TCHAR* GetOpenGLDebugSourceStringARB(GLenum Source)
{
static const TCHAR* SourceStrings[] =
{
TEXT("API"),
TEXT("System"),
TEXT("ShaderCompiler"),
TEXT("ThirdParty"),
TEXT("Application"),
TEXT("Other")
};
if (Source >= GL_DEBUG_SOURCE_API_ARB && Source <= GL_DEBUG_SOURCE_OTHER_ARB)
{
return SourceStrings[Source - GL_DEBUG_SOURCE_API_ARB];
}
return TEXT("Unknown");
}
/**
* Map GL_DEBUG_TYPE_*_ARB to a human-readable string.
*/
static const TCHAR* GetOpenGLDebugTypeStringARB(GLenum Type)
{
static const TCHAR* TypeStrings[] =
{
TEXT("Error"),
TEXT("Deprecated"),
TEXT("UndefinedBehavior"),
TEXT("Portability"),
TEXT("Performance"),
TEXT("Other")
};
if (Type >= GL_DEBUG_TYPE_ERROR_ARB && Type <= GL_DEBUG_TYPE_OTHER_ARB)
{
return TypeStrings[Type - GL_DEBUG_TYPE_ERROR_ARB];
}
#ifdef GL_KHR_debug
{
static const TCHAR* DebugTypeStrings[] =
{
TEXT("Marker"),
TEXT("PushGroup"),
TEXT("PopGroup"),
};
if (Type >= GL_DEBUG_TYPE_MARKER && Type <= GL_DEBUG_TYPE_POP_GROUP)
{
return DebugTypeStrings[Type - GL_DEBUG_TYPE_MARKER];
}
}
#endif
return TEXT("Unknown");
}
/**
* Map GL_DEBUG_SEVERITY_*_ARB to a human-readable string.
*/
static const TCHAR* GetOpenGLDebugSeverityStringARB(GLenum Severity)
{
static const TCHAR* SeverityStrings[] =
{
TEXT("High"),
TEXT("Medium"),
TEXT("Low")
};
if (Severity >= GL_DEBUG_SEVERITY_HIGH_ARB && Severity <= GL_DEBUG_SEVERITY_LOW_ARB)
{
return SeverityStrings[Severity - GL_DEBUG_SEVERITY_HIGH_ARB];
}
#ifdef GL_KHR_debug
if(Severity == GL_DEBUG_SEVERITY_NOTIFICATION)
return TEXT("Notification");
#endif
return TEXT("Unknown");
}
/**
* OpenGL debug message callback. Conforms to GLDEBUGPROCARB.
*/
#if PLATFORM_ANDROID || PLATFORM_HTML5
#ifndef GL_APIENTRY
#define GL_APIENTRY APIENTRY
#endif
static void GL_APIENTRY OpenGLDebugMessageCallbackARB(
#else
static void APIENTRY OpenGLDebugMessageCallbackARB(
#endif
GLenum Source,
GLenum Type,
GLuint Id,
GLenum Severity,
GLsizei Length,
const GLchar* Message,
GLvoid* UserParam)
{
if (GDisableOpenGLDebugOutput)
return;
#if !NO_LOGGING
const TCHAR* SourceStr = GetOpenGLDebugSourceStringARB(Source);
const TCHAR* TypeStr = GetOpenGLDebugTypeStringARB(Type);
const TCHAR* SeverityStr = GetOpenGLDebugSeverityStringARB(Severity);
ELogVerbosity::Type Verbosity = ELogVerbosity::Warning;
if (Type == GL_DEBUG_TYPE_ERROR_ARB && Severity == GL_DEBUG_SEVERITY_HIGH_ARB)
{
Verbosity = ELogVerbosity::Fatal;
}
if ((Verbosity & ELogVerbosity::VerbosityMask) <= FLogCategoryLogRHI::CompileTimeVerbosity)
{
if (!LogRHI.IsSuppressed(Verbosity))
{
FMsg::Logf(__FILE__, __LINE__, LogRHI.GetCategoryName(), Verbosity,
TEXT("[%s][%s][%s][%u] %s"),
SourceStr,
TypeStr,
SeverityStr,
Id,
ANSI_TO_TCHAR(Message)
);
}
// this is a debugging code to catch VIDEO->HOST copying
if (Id == 131186)
{
int A = 5;
}
}
#endif
}
#endif // GL_ARB_debug_output
#ifdef GL_AMD_debug_output
/**
* Map GL_DEBUG_CATEGORY_*_AMD to a human-readable string.
*/
static const TCHAR* GetOpenGLDebugCategoryStringAMD(GLenum Category)
{
static const TCHAR* CategoryStrings[] =
{
TEXT("API"),
TEXT("System"),
TEXT("Deprecation"),
TEXT("UndefinedBehavior"),
TEXT("Performance"),
TEXT("ShaderCompiler"),
TEXT("Application"),
TEXT("Other")
};
if (Category >= GL_DEBUG_CATEGORY_API_ERROR_AMD && Category <= GL_DEBUG_CATEGORY_OTHER_AMD)
{
return CategoryStrings[Category - GL_DEBUG_CATEGORY_API_ERROR_AMD];
}
return TEXT("Unknown");
}
/**
* Map GL_DEBUG_SEVERITY_*_AMD to a human-readable string.
*/
static const TCHAR* GetOpenGLDebugSeverityStringAMD(GLenum Severity)
{
static const TCHAR* SeverityStrings[] =
{
TEXT("High"),
TEXT("Medium"),
TEXT("Low")
};
if (Severity >= GL_DEBUG_SEVERITY_HIGH_AMD && Severity <= GL_DEBUG_SEVERITY_LOW_AMD)
{
return SeverityStrings[Severity - GL_DEBUG_SEVERITY_HIGH_AMD];
}
return TEXT("Unknown");
}
/**
* OpenGL debug message callback. Conforms to GLDEBUGPROCAMD.
*/
static void APIENTRY OpenGLDebugMessageCallbackAMD(
GLuint Id,
GLenum Category,
GLenum Severity,
GLsizei Length,
const GLchar* Message,
GLvoid* UserParam)
{
#if !NO_LOGGING
const TCHAR* CategoryStr = GetOpenGLDebugCategoryStringAMD(Category);
const TCHAR* SeverityStr = GetOpenGLDebugSeverityStringAMD(Severity);
ELogVerbosity::Type Verbosity = ELogVerbosity::Warning;
if (Severity == GL_DEBUG_SEVERITY_HIGH_AMD)
{
Verbosity = ELogVerbosity::Fatal;
}
if ((Verbosity & ELogVerbosity::VerbosityMask) <= FLogCategoryLogRHI::CompileTimeVerbosity)
{
if (!LogRHI.IsSuppressed(Verbosity))
{
FMsg::Logf(__FILE__, __LINE__, LogRHI.GetCategoryName(), Verbosity,
TEXT("[%s][%s][%u] %s"),
CategoryStr,
SeverityStr,
Id,
ANSI_TO_TCHAR(Message)
);
}
}
#endif
}
#endif // GL_AMD_debug_output
#if PLATFORM_WINDOWS
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT_ProcAddress = NULL;
#endif
static inline void SetupTextureFormat( EPixelFormat Format, const FOpenGLTextureFormat& GLFormat)
{
GOpenGLTextureFormats[Format] = GLFormat;
GPixelFormats[Format].Supported = (GLFormat.Format != GL_NONE && (GLFormat.InternalFormat[0] != GL_NONE || GLFormat.InternalFormat[1] != GL_NONE));
}
void InitDebugContext()
{
// Set the debug output callback if the driver supports it.
VERIFY_GL(__FUNCTION__);
bool bDebugOutputInitialized = false;
#if !ENABLE_VERIFY_GL
#if defined(GL_ARB_debug_output)
if (glDebugMessageCallbackARB)
{
// Synchronous output can slow things down, but we'll get better callstack if breaking in or crashing in the callback. This is debug only after all.
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallbackARB(GLDEBUGPROCARB(OpenGLDebugMessageCallbackARB), /*UserParam=*/ NULL);
bDebugOutputInitialized = (glGetError() == GL_NO_ERROR);
}
#elif defined(GL_KHR_debug)
// OpenGLES names the debug functions differently, but they behave the same
if (glDebugMessageCallbackKHR)
{
glDebugMessageCallbackKHR(GLDEBUGPROCKHR(OpenGLDebugMessageCallbackARB), /*UserParam=*/ NULL);
bDebugOutputInitialized = (glGetError() == GL_NO_ERROR);
}
#endif // GL_ARB_debug_output / GL_KHR_debug
#if defined(GL_AMD_debug_output)
if (glDebugMessageCallbackAMD && !bDebugOutputInitialized)
{
glDebugMessageCallbackAMD(OpenGLDebugMessageCallbackAMD, /*UserParam=*/ NULL);
bDebugOutputInitialized = (glGetError() == GL_NO_ERROR);
}
#endif // GL_AMD_debug_output
#endif // !ENABLE_VERIFY_GL
#if !PLATFORM_MAC
if (!bDebugOutputInitialized)
{
UE_LOG(LogRHI,Warning,TEXT("OpenGL debug output extension not supported!"));
}
#endif
// this is to suppress feeding back of the debug markers and groups to the log, since those originate in the app anyways...
#if ENABLE_OPENGL_DEBUG_GROUPS && defined(GL_ARB_debug_output) && GL_ARB_debug_output && GL_KHR_debug && !OPENGL_ESDEFERRED
if(glDebugMessageControlARB && bDebugOutputInitialized)
{
glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_MARKER, GL_DONT_CARE, 0, NULL, GL_FALSE);
glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_PUSH_GROUP, GL_DONT_CARE, 0, NULL, GL_FALSE);
glDebugMessageControlARB(GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_POP_GROUP, GL_DONT_CARE, 0, NULL, GL_FALSE);
#ifdef GL_KHR_debug
glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
#endif
UE_LOG(LogRHI,Verbose,TEXT("disabling reporting back of debug groups and markers to the OpenGL debug output callback"));
}
#elif ENABLE_OPENGL_DEBUG_GROUPS && !defined(GL_ARB_debug_output) && defined(GL_KHR_debug) && GL_KHR_debug
if(glDebugMessageControlKHR)
{
glDebugMessageControlKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, GL_DEBUG_TYPE_MARKER_KHR, GL_DONT_CARE, 0, NULL, GL_FALSE);
glDebugMessageControlKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, GL_DEBUG_TYPE_PUSH_GROUP_KHR, GL_DONT_CARE, 0, NULL, GL_FALSE);
glDebugMessageControlKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, GL_DEBUG_TYPE_POP_GROUP_KHR, GL_DONT_CARE, 0, NULL, GL_FALSE);
glDebugMessageControlKHR(GL_DEBUG_SOURCE_API_KHR, GL_DEBUG_TYPE_OTHER_KHR, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
UE_LOG(LogRHI,Verbose,TEXT("disabling reporting back of debug groups and markers to the OpenGL debug output callback"));
}
#endif
}
TAutoConsoleVariable<FString> CVarOpenGLStripExtensions(
TEXT("r.OpenGL.StripExtensions"),
TEXT(""),
TEXT("List of comma separated OpenGL extensions to strip from a driver reported extensions string"),
ECVF_ReadOnly);
TAutoConsoleVariable<FString> CVarOpenGLAddExtensions(
TEXT("r.OpenGL.AddExtensions"),
TEXT(""),
TEXT("List of comma separated OpenGL extensions to add to a driver reported extensions string"),
ECVF_ReadOnly);
void ApplyExtensionsOverrides(FString& ExtensionsString)
{
// Strip extensions
{
TArray<FString> ExtList;
FString ExtString = CVarOpenGLStripExtensions.GetValueOnAnyThread();
ExtString.ParseIntoArray(ExtList, TEXT(","), /*InCullEmpty=*/true);
for (FString& ExtName : ExtList)
{
ExtName = ExtName.Trim().TrimTrailing();
if (ExtensionsString.ReplaceInline(*ExtName, TEXT("")) > 0)
{
UE_LOG(LogRHI, Log, TEXT("Stripped extension: %s"), *ExtName);
}
}
}
// Add extensions
{
TArray<FString> ExtList;
FString ExtString = CVarOpenGLAddExtensions.GetValueOnAnyThread();
ExtString.ParseIntoArray(ExtList, TEXT(","), /*InCullEmpty=*/true);
for (FString& ExtName : ExtList)
{
ExtName = ExtName.Trim().TrimTrailing();
if (!ExtensionsString.Contains(ExtName))
{
ExtensionsString.Append(TEXT(" ")); // extensions delimiter
ExtensionsString.Append(ExtName);
UE_LOG(LogRHI, Log, TEXT("Added extension: %s"), *ExtName);
}
}
}
}
/**
* Initialize RHI capabilities for the current OpenGL context.
*/
static void InitRHICapabilitiesForGL()
{
VERIFY_GL_SCOPE();
GTexturePoolSize = 0;
GPoolSizeVRAMPercentage = 0;
#if PLATFORM_WINDOWS || PLATFORM_LINUX
GConfig->GetInt( TEXT( "TextureStreaming" ), TEXT( "PoolSizeVRAMPercentage" ), GPoolSizeVRAMPercentage, GEngineIni );
#endif
// GL vendor and version information.
#if !defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !(defined(_MSC_VER) && _MSC_VER >= 1900)
#define LOG_GL_STRING(StringEnum) UE_LOG(LogRHI, Log, TEXT(" ") ## TEXT(#StringEnum) ## TEXT(": %s"), ANSI_TO_TCHAR((const ANSICHAR*)glGetString(StringEnum)))
#else
#define LOG_GL_STRING(StringEnum) UE_LOG(LogRHI, Log, TEXT(" " #StringEnum ": %s"), ANSI_TO_TCHAR((const ANSICHAR*)glGetString(StringEnum)))
#endif
UE_LOG(LogRHI, Log, TEXT("Initializing OpenGL RHI"));
LOG_GL_STRING(GL_VENDOR);
LOG_GL_STRING(GL_RENDERER);
LOG_GL_STRING(GL_VERSION);
LOG_GL_STRING(GL_SHADING_LANGUAGE_VERSION);
#undef LOG_GL_STRING
GRHIAdapterName = FOpenGL::GetAdapterName();
GRHIAdapterInternalDriverVersion = ANSI_TO_TCHAR((const ANSICHAR*)glGetString(GL_VERSION));
// Log all supported extensions.
#if PLATFORM_WINDOWS
bool bWindowsSwapControlExtensionPresent = false;
#endif
{
extern void GetExtensionsString( FString& ExtensionsString);
FString ExtensionsString;
GetExtensionsString(ExtensionsString);
#if PLATFORM_WINDOWS
if (ExtensionsString.Contains(TEXT("WGL_EXT_swap_control")))
{
bWindowsSwapControlExtensionPresent = true;
}
#endif
// Log supported GL extensions
UE_LOG(LogRHI, Log, TEXT("OpenGL Extensions:"));
TArray<FString> GLExtensionArray;
ExtensionsString.ParseIntoArray(GLExtensionArray, TEXT(" "), true);
for (int ExtIndex = 0; ExtIndex < GLExtensionArray.Num(); ExtIndex++)
{
UE_LOG(LogRHI, Log, TEXT(" %s"), *GLExtensionArray[ExtIndex]);
}
ApplyExtensionsOverrides(ExtensionsString);
FOpenGL::ProcessExtensions(ExtensionsString);
}
#if PLATFORM_WINDOWS
#pragma warning(push)
#pragma warning(disable:4191)
if (!bWindowsSwapControlExtensionPresent)
{
// Disable warning C4191: 'type cast' : unsafe conversion from 'PROC' to 'XXX' while getting GL entry points.
PFNWGLGETEXTENSIONSSTRINGEXTPROC wglGetExtensionsStringEXT_ProcAddress =
(PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT");
if (strstr(wglGetExtensionsStringEXT_ProcAddress(), "WGL_EXT_swap_control") != NULL)
{
bWindowsSwapControlExtensionPresent = true;
}
}
if (bWindowsSwapControlExtensionPresent)
{
wglSwapIntervalEXT_ProcAddress = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
}
#pragma warning(pop)
#endif
// Set debug flag if context was setup with debugging
FOpenGL::InitDebugContext();
// Log and get various limits.
#if !defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !(defined(_MSC_VER) && _MSC_VER >= 1900)
#define LOG_AND_GET_GL_INT_TEMP(IntEnum,Default) GLint Value_##IntEnum = Default; if (IntEnum) {glGetIntegerv(IntEnum, &Value_##IntEnum); glGetError();} else {Value_##IntEnum = Default;} UE_LOG(LogRHI, Log, TEXT(" ") ## TEXT(#IntEnum) ## TEXT(": %d"), Value_##IntEnum)
#else
#define LOG_AND_GET_GL_INT_TEMP(IntEnum,Default) GLint Value_##IntEnum = Default; if (IntEnum) {glGetIntegerv(IntEnum, &Value_##IntEnum); glGetError();} else {Value_##IntEnum = Default;} UE_LOG(LogRHI, Log, TEXT(" " #IntEnum ": %d"), Value_##IntEnum)
#endif
LOG_AND_GET_GL_INT_TEMP(GL_MAX_TEXTURE_SIZE, 0);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 0);
#if defined(GL_MAX_ARRAY_TEXTURE_LAYERS) && GL_MAX_ARRAY_TEXTURE_LAYERS
LOG_AND_GET_GL_INT_TEMP(GL_MAX_ARRAY_TEXTURE_LAYERS, 0);
#endif
#if GL_MAX_3D_TEXTURE_SIZE
LOG_AND_GET_GL_INT_TEMP(GL_MAX_3D_TEXTURE_SIZE, 0);
#endif
LOG_AND_GET_GL_INT_TEMP(GL_MAX_RENDERBUFFER_SIZE, 0);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_TEXTURE_IMAGE_UNITS, 0);
if (FOpenGL::SupportsDrawBuffers())
{
LOG_AND_GET_GL_INT_TEMP(GL_MAX_DRAW_BUFFERS, 1);
GMaxOpenGLDrawBuffers = FMath::Min(Value_GL_MAX_DRAW_BUFFERS, (GLint)MaxSimultaneousRenderTargets);
}
LOG_AND_GET_GL_INT_TEMP(GL_MAX_COLOR_ATTACHMENTS, 1);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_SAMPLES, 1);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_COLOR_TEXTURE_SAMPLES, 1);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_DEPTH_TEXTURE_SAMPLES, 1);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_INTEGER_SAMPLES, 1);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 0);
LOG_AND_GET_GL_INT_TEMP(GL_MAX_VERTEX_ATTRIBS, 0);
if (FParse::Param(FCommandLine::Get(), TEXT("quad_buffer_stereo")))
{
GLboolean Result = GL_FALSE;
glGetBooleanv(GL_STEREO, &Result);
// Skip any errors if any were generated
glGetError();
GSupportsQuadBufferStereo = (Result == GL_TRUE);
}
if( FOpenGL::SupportsTextureFilterAnisotropic())
{
LOG_AND_GET_GL_INT_TEMP(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, 0);
GMaxOpenGLTextureFilterAnisotropic = Value_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT;
}
#undef LOG_AND_GET_GL_INT_TEMP
GMaxOpenGLColorSamples = Value_GL_MAX_COLOR_TEXTURE_SAMPLES;
GMaxOpenGLDepthSamples = Value_GL_MAX_DEPTH_TEXTURE_SAMPLES;
GMaxOpenGLIntegerSamples = Value_GL_MAX_INTEGER_SAMPLES;
// Verify some assumptions.
// Android seems like reports one color attachment even when it supports MRT
#if !PLATFORM_ANDROID
check(Value_GL_MAX_COLOR_ATTACHMENTS >= MaxSimultaneousRenderTargets || !FOpenGL::SupportsMultipleRenderTargets());
#endif
// We don't check for compressed formats right now because vendors have not
// done a great job reporting what is actually supported:
// OSX/NVIDIA doesn't claim to support SRGB DXT formats even though they work correctly.
// Windows/AMD sometimes claim to support no compressed formats even though they all work correctly.
#if 0
// Check compressed texture formats.
bool bSupportsCompressedTextures = true;
{
FString CompressedFormatsString = TEXT(" GL_COMPRESSED_TEXTURE_FORMATS:");
TArray<GLint> CompressedFormats;
GLint NumCompressedFormats = 0;
glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &NumCompressedFormats);
CompressedFormats.Empty(NumCompressedFormats);
CompressedFormats.AddZeroed(NumCompressedFormats);
glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, CompressedFormats.GetTypedData());
#define CHECK_COMPRESSED_FORMAT(GLName) if (CompressedFormats.Contains(GLName)) { CompressedFormatsString += TEXT(" ") TEXT(#GLName); } else { bSupportsCompressedTextures = false; }
CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT);
CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT);
CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT);
CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT);
CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT);
//CHECK_COMPRESSED_FORMAT(GL_COMPRESSED_RG_RGTC2);
#undef CHECK_COMPRESSED_FORMAT
// ATI does not report that it supports RGTC2, but the 3.2 core profile mandates it.
// For now assume it is supported and bring it up with ATI if it really isn't(?!)
CompressedFormatsString += TEXT(" GL_COMPRESSED_RG_RGTC2");
UE_LOG(LogRHI, Log, *CompressedFormatsString);
}
check(bSupportsCompressedTextures);
#endif
// Set capabilities.
const GLint MajorVersion = FOpenGL::GetMajorVersion();
const GLint MinorVersion = FOpenGL::GetMinorVersion();
// Shader platform & RHI feature level
GMaxRHIFeatureLevel = FOpenGL::GetFeatureLevel();
GMaxRHIShaderPlatform = FOpenGL::GetShaderPlatform();
// Emulate uniform buffers on ES2, unless we're on a desktop platform emulating ES2.
GUseEmulatedUniformBuffers = IsES2Platform(GMaxRHIShaderPlatform) && !IsPCPlatform(GMaxRHIShaderPlatform);
#if PLATFORM_HTML5
// On browser builds, ask the current browser we are running on whether it supports uniform buffers or not.
GUseEmulatedUniformBuffers = !FOpenGL::SupportsUniformBuffers();
#endif
if (!GUseEmulatedUniformBuffers && IsPCPlatform(GMaxRHIShaderPlatform))
{
static auto* CVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("OpenGL.UseEmulatedUBs"));
GUseEmulatedUniformBuffers = CVar && CVar->GetValueOnAnyThread() != 0;
}
FString FeatureLevelName;
GetFeatureLevelName(GMaxRHIFeatureLevel, FeatureLevelName);
FString ShaderPlatformName = LegacyShaderPlatformToShaderFormat(GMaxRHIShaderPlatform).ToString();
UE_LOG(LogRHI, Log, TEXT("OpenGL MajorVersion = %d, MinorVersion = %d, ShaderPlatform = %s, FeatureLevel = %s"), MajorVersion, MinorVersion, *ShaderPlatformName, *FeatureLevelName);
#if PLATFORM_ANDROIDESDEFERRED
UE_LOG(LogRHI, Log, TEXT("PLATFORM_ANDROIDESDEFERRED"));
#elif PLATFORM_ANDROID
UE_LOG(LogRHI, Log, TEXT("PLATFORM_ANDROID"));
#endif
GMaxTextureSamplers = Value_GL_MAX_TEXTURE_IMAGE_UNITS;
GMaxTextureMipCount = FMath::CeilLogTwo(Value_GL_MAX_TEXTURE_SIZE) + 1;
GMaxTextureMipCount = FMath::Min<int32>(MAX_TEXTURE_MIP_COUNT, GMaxTextureMipCount);
GMaxTextureDimensions = Value_GL_MAX_TEXTURE_SIZE;
GMaxCubeTextureDimensions = Value_GL_MAX_CUBE_MAP_TEXTURE_SIZE;
#if defined(GL_MAX_ARRAY_TEXTURE_LAYERS) && GL_MAX_ARRAY_TEXTURE_LAYERS
GMaxTextureArrayLayers = Value_GL_MAX_ARRAY_TEXTURE_LAYERS;
#endif
GSupportsVolumeTextureRendering = FOpenGL::SupportsVolumeTextureRendering();
GSupportsRenderDepthTargetableShaderResources = true;
GSupportsRenderTargetFormat_PF_G8 = true;
GSupportsSeparateRenderTargetBlendState = FOpenGL::SupportsSeparateAlphaBlend();
GSupportsDepthBoundsTest = FOpenGL::SupportsDepthBoundsTest();
GSupportsRenderTargetFormat_PF_FloatRGBA = FOpenGL::SupportsColorBufferHalfFloat();
GSupportsMultipleRenderTargets = FOpenGL::SupportsMultipleRenderTargets();
GSupportsWideMRT = FOpenGL::SupportsWideMRT();
GSupportsTexture3D = FOpenGL::SupportsTexture3D();
GSupportsMobileMultiView = FOpenGL::SupportsMobileMultiView();
GSupportsResourceView = FOpenGL::SupportsResourceView();
GSupportsShaderFramebufferFetch = FOpenGL::SupportsShaderFramebufferFetch();
GSupportsShaderDepthStencilFetch = FOpenGL::SupportsShaderDepthStencilFetch();
GMaxShadowDepthBufferSizeX = FMath::Min<int32>(Value_GL_MAX_RENDERBUFFER_SIZE, 4096); // Limit to the D3D11 max.
GMaxShadowDepthBufferSizeY = FMath::Min<int32>(Value_GL_MAX_RENDERBUFFER_SIZE, 4096);
GHardwareHiddenSurfaceRemoval = FOpenGL::HasHardwareHiddenSurfaceRemoval();
GRHISupportsInstancing = FOpenGL::SupportsInstancing(); // HTML5 supports it with ANGLE_instanced_arrays or WebGL 2.0+. Android supports it with OpenGL ES3.0+
GSupportsTimestampRenderQueries = FOpenGL::SupportsTimestampQueries();
GSupportsHDR32bppEncodeModeIntrinsic = FOpenGL::SupportsHDR32bppEncodeModeIntrinsic();
checkf(!IsMobileHDR32bpp() || GSupportsHDR32bppEncodeModeIntrinsic || IsPCPlatform(GMaxRHIShaderPlatform), TEXT("Current platform does not support 32bpp HDR but IsMobileHDR32bpp() returned true"));
GShaderPlatformForFeatureLevel[ERHIFeatureLevel::ES2] = (GMaxRHIFeatureLevel == ERHIFeatureLevel::ES2) ? GMaxRHIShaderPlatform : SP_OPENGL_PCES2;
GShaderPlatformForFeatureLevel[ERHIFeatureLevel::ES3_1] = (GMaxRHIFeatureLevel == ERHIFeatureLevel::ES3_1) ? GMaxRHIShaderPlatform : SP_OPENGL_PCES3_1;
GShaderPlatformForFeatureLevel[ERHIFeatureLevel::SM4] = PLATFORM_MAC ? SP_OPENGL_SM4_MAC : SP_OPENGL_SM4;
GShaderPlatformForFeatureLevel[ERHIFeatureLevel::SM5] = OPENGL_ESDEFERRED ? SP_OPENGL_ES31_EXT : SP_OPENGL_SM5;
// Set to same values as in DX11, as for the time being clip space adjustment are done entirely
// in HLSLCC-generated shader code and OpenGLDrv.
GMinClipZ = 0.0f;
GProjectionSignY = 1.0f;
// Disable texture streaming on ES2 unless we have the GL_APPLE_copy_texture_levels extension
if (GMaxRHIFeatureLevel == ERHIFeatureLevel::ES2 && !FOpenGL::SupportsCopyTextureLevels())
{
GRHISupportsTextureStreaming = false;
}
else
{
GRHISupportsTextureStreaming = true;
}
GVertexElementTypeSupport.SetSupported(VET_Half2, FOpenGL::SupportsVertexHalfFloat());
GVertexElementTypeSupport.SetSupported(VET_Half4, FOpenGL::SupportsVertexHalfFloat());
GVertexElementTypeSupport.SetSupported(VET_URGB10A2N, FOpenGL::SupportsRGB10A2());
for (int32 PF = 0; PF < PF_MAX; ++PF)
{
SetupTextureFormat(EPixelFormat(PF), FOpenGLTextureFormat());
}
GLenum DepthFormat = FOpenGL::GetDepthFormat();
GLenum ShadowDepthFormat = FOpenGL::GetShadowDepthFormat();
// Initialize the platform pixel format map. InternalFormat InternalFormatSRGB Format Type bCompressed bBGRA
SetupTextureFormat( PF_Unknown, FOpenGLTextureFormat( ));
SetupTextureFormat( PF_A32B32G32R32F, FOpenGLTextureFormat( GL_RGBA32F, GL_NONE, GL_RGBA, GL_FLOAT, false, false));
SetupTextureFormat( PF_UYVY, FOpenGLTextureFormat( ));
//@todo: ES2 requires GL_OES_depth_texture extension to support depth textures of any kind.
SetupTextureFormat( PF_ShadowDepth, FOpenGLTextureFormat( ShadowDepthFormat, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false));
SetupTextureFormat( PF_D24, FOpenGLTextureFormat( DepthFormat, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false));
SetupTextureFormat( PF_A16B16G16R16, FOpenGLTextureFormat( GL_RGBA16, GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT, false, false));
SetupTextureFormat( PF_A1, FOpenGLTextureFormat( ));
SetupTextureFormat( PF_R16G16B16A16_UINT, FOpenGLTextureFormat( GL_RGBA16UI, GL_NONE, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, false, false));
SetupTextureFormat( PF_R16G16B16A16_SINT, FOpenGLTextureFormat( GL_RGBA16I, GL_NONE, GL_RGBA_INTEGER, GL_SHORT, false, false));
SetupTextureFormat( PF_R5G6B5_UNORM, FOpenGLTextureFormat( ));
#if PLATFORM_DESKTOP || PLATFORM_ANDROIDESDEFERRED
CA_SUPPRESS(6286);
if (PLATFORM_DESKTOP || FOpenGL::GetFeatureLevel() >= ERHIFeatureLevel::SM4)
{
// Not supported for rendering:
SetupTextureFormat( PF_G16, FOpenGLTextureFormat( GL_R16, GL_R16, GL_RED, GL_UNSIGNED_SHORT, false, false));
SetupTextureFormat( PF_R32_FLOAT, FOpenGLTextureFormat( GL_R32F, GL_R32F, GL_RED, GL_FLOAT, false, false));
SetupTextureFormat( PF_G16R16F, FOpenGLTextureFormat( GL_RG16F, GL_RG16F, GL_RG, GL_HALF_FLOAT, false, false));
SetupTextureFormat( PF_G16R16F_FILTER, FOpenGLTextureFormat( GL_RG16F, GL_RG16F, GL_RG, GL_HALF_FLOAT, false, false));
SetupTextureFormat( PF_G32R32F, FOpenGLTextureFormat( GL_RG32F, GL_RG32F, GL_RG, GL_FLOAT, false, false));
SetupTextureFormat( PF_A2B10G10R10, FOpenGLTextureFormat( GL_RGB10_A2, GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false, false));
SetupTextureFormat( PF_R16F, FOpenGLTextureFormat( GL_R16F, GL_R16F, GL_RED, GL_HALF_FLOAT, false, false));
SetupTextureFormat( PF_R16F_FILTER, FOpenGLTextureFormat( GL_R16F, GL_R16F, GL_RED, GL_HALF_FLOAT, false, false));
if (FOpenGL::SupportsR11G11B10F())
{
// Note: Also needs to include support for compute shaders to be defined here (e.g. glBindImageTexture)
SetupTextureFormat(PF_FloatRGB, FOpenGLTextureFormat(GL_R11F_G11F_B10F, GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false, false));
SetupTextureFormat(PF_FloatR11G11B10, FOpenGLTextureFormat(GL_RGBA16F, GL_RGBA16F, GL_RGB, GL_HALF_FLOAT, false, false));
}
else
{
SetupTextureFormat(PF_FloatRGB, FOpenGLTextureFormat(GL_RGBA16F, GL_RGBA16F, GL_RGB, GL_HALF_FLOAT, false, false));
SetupTextureFormat(PF_FloatR11G11B10, FOpenGLTextureFormat(GL_R11F_G11F_B10F, GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false, false));
}
SetupTextureFormat(PF_V8U8, FOpenGLTextureFormat(GL_RG8_SNORM, GL_NONE, GL_RG, GL_BYTE, false, false));
SetupTextureFormat( PF_R8G8, FOpenGLTextureFormat( GL_RG8, GL_NONE, GL_RG, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat( PF_BC5, FOpenGLTextureFormat( GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_BC4, FOpenGLTextureFormat( GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1,GL_RED, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_A8, FOpenGLTextureFormat( GL_R8, GL_NONE, GL_RED, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat( PF_R32_UINT, FOpenGLTextureFormat( GL_R32UI, GL_NONE, GL_RED_INTEGER, GL_UNSIGNED_INT, false, false));
SetupTextureFormat( PF_R32_SINT, FOpenGLTextureFormat( GL_R32I, GL_NONE, GL_RED_INTEGER, GL_INT, false, false));
SetupTextureFormat( PF_R16_UINT, FOpenGLTextureFormat( GL_R16UI, GL_NONE, GL_RED_INTEGER, GL_UNSIGNED_SHORT, false, false));
SetupTextureFormat( PF_R16_SINT, FOpenGLTextureFormat( GL_R16I, GL_NONE, GL_RED_INTEGER, GL_SHORT, false, false));
SetupTextureFormat( PF_R8_UINT, FOpenGLTextureFormat( GL_R8UI, GL_NONE, GL_RED_INTEGER, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat( PF_FloatRGBA, FOpenGLTextureFormat( GL_RGBA16F, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, false, false));
if (FOpenGL::GetShaderPlatform() == EShaderPlatform::SP_OPENGL_ES31_EXT)
{
SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_R8, GL_R8, GL_RED, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false, true));
SetupTextureFormat(PF_R8G8B8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false, false));
if (FOpenGL::SupportsRG16UI())
{
// The user should check for support for PF_G16R16 and implement a fallback if it's not supported!
SetupTextureFormat(PF_G16R16, FOpenGLTextureFormat(GL_RG16, GL_RG16, GL_RG, GL_UNSIGNED_SHORT, false, false));
}
}
else
{
SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_R8, GL_SRGB8, GL_RED, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, false, false));
SetupTextureFormat(PF_R8G8B8A8, FOpenGLTextureFormat(GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, false, false));
SetupTextureFormat(PF_G16R16, FOpenGLTextureFormat(GL_RG16, GL_RG16, GL_RG, GL_UNSIGNED_SHORT, false, false));
}
if (FOpenGL::SupportsPackedDepthStencil())
{
SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(GL_DEPTH24_STENCIL8, GL_NONE, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false, false));
}
else
{
// @todo android: This is cheating by not setting a stencil anywhere, need that! And Shield is still rendering black scene
SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(DepthFormat, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false));
}
}
else
#endif // PLATFORM_DESKTOP || PLATFORM_ANDROIDESDEFERRED
{
#if !PLATFORM_DESKTOP
// ES2-based cases
GLuint BGRA8888 = FOpenGL::SupportsBGRA8888() ? GL_BGRA_EXT : GL_RGBA;
GLuint RGBA8 = FOpenGL::SupportsRGBA8() ? GL_RGBA8_OES : GL_RGBA;
#if PLATFORM_ANDROID
SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(BGRA8888, FOpenGL::SupportsSRGB() ? GL_SRGB_ALPHA_EXT : BGRA8888, BGRA8888, GL_UNSIGNED_BYTE, false, false));
#else
SetupTextureFormat(PF_B8G8R8A8, FOpenGLTextureFormat(GL_RGBA, FOpenGL::SupportsSRGB() ? GL_SRGB_ALPHA_EXT : GL_RGBA, GL_BGRA8_EXT, FOpenGL::SupportsSRGB() ? GL_SRGB8_ALPHA8_EXT : GL_BGRA8_EXT, BGRA8888, GL_UNSIGNED_BYTE, false, false));
#endif
SetupTextureFormat(PF_R8G8B8A8, FOpenGLTextureFormat(RGBA8, FOpenGL::SupportsSRGB() ? GL_SRGB_ALPHA_EXT : RGBA8, GL_RGBA8, FOpenGL::SupportsSRGB() ? GL_SRGB8_ALPHA8_EXT : GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, false, false));
#if PLATFORM_IOS
SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE8_EXT, GL_LUMINANCE8_EXT, GL_LUMINANCE, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat(PF_A8, FOpenGLTextureFormat(GL_ALPHA, GL_ALPHA, GL_ALPHA8_EXT, GL_ALPHA8_EXT, GL_ALPHA, GL_UNSIGNED_BYTE, false, false));
#else
SetupTextureFormat(PF_G8, FOpenGLTextureFormat(GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, false, false));
SetupTextureFormat(PF_A8, FOpenGLTextureFormat(GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, false, false));
#endif
if (FOpenGL::SupportsColorBufferHalfFloat() && FOpenGL::SupportsTextureHalfFloat())
{
#if PLATFORM_ANDROID
GLenum InternalFormatRGBA16 = FOpenGL::GetTextureHalfFloatInternalFormat();
GLenum PixelTypeRGBA16 = FOpenGL::GetTextureHalfFloatPixelType();
SetupTextureFormat(PF_FloatRGBA, FOpenGLTextureFormat(InternalFormatRGBA16, InternalFormatRGBA16, GL_RGBA, PixelTypeRGBA16, false, false));
#else
SetupTextureFormat(PF_FloatRGBA, FOpenGLTextureFormat(GL_RGBA, GL_RGBA, GL_RGBA, GL_HALF_FLOAT_OES, false, false));
#endif
}
else
{
SetupTextureFormat( PF_FloatRGBA, FOpenGLTextureFormat(GL_RGBA, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, false, false));
}
if (FOpenGL::SupportsColorBufferFloat())
{
SetupTextureFormat( PF_G16, FOpenGLTextureFormat( GL_R16, GL_R16, GL_RED, GL_UNSIGNED_SHORT, false, false));
SetupTextureFormat( PF_R32_FLOAT, FOpenGLTextureFormat( GL_R32F, GL_R32F, GL_RED, GL_FLOAT, false, false));
#ifdef GL_RG_EXT
SetupTextureFormat( PF_G16R16F, FOpenGLTextureFormat( GL_RG16F, GL_RG16F, GL_RG_EXT, GL_HALF_FLOAT, false, false));
SetupTextureFormat( PF_G16R16F_FILTER, FOpenGLTextureFormat( GL_RG16F, GL_RG16F, GL_RG_EXT, GL_HALF_FLOAT, false, false));
SetupTextureFormat( PF_G32R32F, FOpenGLTextureFormat( GL_RG32F, GL_RG32F, GL_RG_EXT, GL_FLOAT, false, false));
#endif
#ifdef GL_UNSIGNED_INT_2_10_10_10_REV
SetupTextureFormat( PF_A2B10G10R10, FOpenGLTextureFormat( GL_RGB10_A2, GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false, false));
#endif
SetupTextureFormat( PF_R16F, FOpenGLTextureFormat( GL_R16F, GL_R16F, GL_RED, GL_HALF_FLOAT, false, false));
SetupTextureFormat( PF_R16F_FILTER, FOpenGLTextureFormat( GL_R16F, GL_R16F, GL_RED, GL_HALF_FLOAT, false, false));
}
if (FOpenGL::SupportsPackedDepthStencil())
{
SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(GL_DEPTH_STENCIL_OES, GL_NONE, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, false, false));
}
else
{
// @todo android: This is cheating by not setting a stencil anywhere, need that! And Shield is still rendering black scene
SetupTextureFormat(PF_DepthStencil, FOpenGLTextureFormat(GL_DEPTH_COMPONENT, GL_NONE, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false, false));
}
#endif // !PLATFORM_DESKTOP
}
if (FOpenGL::SupportsDXT())
{
if ( FOpenGL::SupportsSRGB() )
{
SetupTextureFormat( PF_DXT1, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_DXT3, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_DXT5, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
}
else
{
// WebGL does not support SRGB versions of DXTn texture formats! Run with SRGB formats disabled. Will need to make sure
// sRGB is always emulated if it's needed.
SetupTextureFormat( PF_DXT1, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_DXT3, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_DXT5, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
}
}
if ( FOpenGL::SupportsPVRTC() )
{
SetupTextureFormat( PF_PVRTC2, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_PVRTC4, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
}
if ( FOpenGL::SupportsATITC() )
{
SetupTextureFormat( PF_ATC_RGB, FOpenGLTextureFormat(GL_ATC_RGB_AMD, GL_ATC_RGB_AMD, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_ATC_RGBA_E, FOpenGLTextureFormat(GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, GL_ATC_RGBA_EXPLICIT_ALPHA_AMD, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_ATC_RGBA_I, FOpenGLTextureFormat(GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
}
if ( FOpenGL::SupportsETC1() )
{
SetupTextureFormat( PF_ETC1, FOpenGLTextureFormat(GL_ETC1_RGB8_OES, GL_ETC1_RGB8_OES, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
}
#if PLATFORM_ANDROID
if ( FOpenGL::SupportsETC2() )
{
SetupTextureFormat( PF_ETC2_RGB, FOpenGLTextureFormat(GL_COMPRESSED_RGB8_ETC2, FOpenGL::SupportsSRGB() ? GL_COMPRESSED_SRGB8_ETC2 : GL_COMPRESSED_RGB8_ETC2, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
SetupTextureFormat( PF_ETC2_RGBA, FOpenGLTextureFormat(GL_COMPRESSED_RGBA8_ETC2_EAC, FOpenGL::SupportsSRGB() ? GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : GL_COMPRESSED_RGBA8_ETC2_EAC, GL_RGBA, GL_UNSIGNED_BYTE, true, false));
}
#endif
if (FOpenGL::SupportsASTC())
{
SetupTextureFormat( PF_ASTC_4x4, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_ASTC_4x4_KHR, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, GL_RGBA, GL_UNSIGNED_BYTE, true, false) );
SetupTextureFormat( PF_ASTC_6x6, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_ASTC_6x6_KHR, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, GL_RGBA, GL_UNSIGNED_BYTE, true, false) );
SetupTextureFormat( PF_ASTC_8x8, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_ASTC_8x8_KHR, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, GL_RGBA, GL_UNSIGNED_BYTE, true, false) );
SetupTextureFormat( PF_ASTC_10x10, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_ASTC_10x10_KHR, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, GL_RGBA, GL_UNSIGNED_BYTE, true, false) );
SetupTextureFormat( PF_ASTC_12x12, FOpenGLTextureFormat(GL_COMPRESSED_RGBA_ASTC_12x12_KHR, GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, GL_RGBA, GL_UNSIGNED_BYTE, true, false) );
}
// Some formats need to know how large a block is.
GPixelFormats[ PF_DepthStencil ].BlockBytes = 4;
GPixelFormats[ PF_FloatRGB ].BlockBytes = 4;
GPixelFormats[ PF_FloatRGBA ].BlockBytes = 8;
// Temporary fix for nvidia driver issue with non-power-of-two shadowmaps (9/8/2016) UE-35312
// @TODO revisit this with newer drivers
GRHINeedsUnatlasedCSMDepthsWorkaround = true;
}
FDynamicRHI* FOpenGLDynamicRHIModule::CreateRHI(ERHIFeatureLevel::Type InRequestedFeatureLevel)
{
GRequestedFeatureLevel = InRequestedFeatureLevel;
return new FOpenGLDynamicRHI();
}
FOpenGLDynamicRHI::FOpenGLDynamicRHI()
: SceneFrameCounter(0)
, ResourceTableFrameCounter(INDEX_NONE)
, bRevertToSharedContextAfterDrawingViewport(false)
, bIsRenderingContextAcquired(false)
, PlatformDevice(NULL)
, GPUProfilingData(this)
{
// This should be called once at the start
check( IsInGameThread() );
check( !GIsThreadedRendering );
PlatformInitOpenGL();
PlatformDevice = PlatformCreateOpenGLDevice();
VERIFY_GL_SCOPE();
InitRHICapabilitiesForGL();
check(PlatformOpenGLCurrentContext(PlatformDevice) == CONTEXT_Shared);
if (PlatformCanEnableGPUCapture())
{
EnableIdealGPUCaptureOptions(true);
// Disable persistent mapping
{
auto* CVar = IConsoleManager::Get().FindConsoleVariable(TEXT("OpenGL.UBODirectWrite"));
if (CVar)
{
CVar->Set(false);
}
}
{
auto* CVar = IConsoleManager::Get().FindConsoleVariable(TEXT("OpenGL.UseStagingBuffer"));
if (CVar)
{
CVar->Set(false);
}
}
}
PrivateOpenGLDevicePtr = this;
}
extern void DestroyShadersAndPrograms();
#if PLATFORM_ANDROID
// only used to test for shader compatibility issues
static bool VerifyCompiledShader(GLuint Shader, const ANSICHAR* GlslCode, bool IsFatal )
{
SCOPE_CYCLE_COUNTER(STAT_OpenGLShaderCompileVerifyTime);
GLint CompileStatus;
glGetShaderiv(Shader, GL_COMPILE_STATUS, &CompileStatus);
if (CompileStatus != GL_TRUE)
{
GLint LogLength;
ANSICHAR DefaultLog[] = "No log";
ANSICHAR *CompileLog = DefaultLog;
glGetShaderiv(Shader, GL_INFO_LOG_LENGTH, &LogLength);
#if PLATFORM_ANDROID
if ( LogLength == 0 )
{
// make it big anyway
// there was a bug in android 2.2 where glGetShaderiv would return 0 even though there was a error message
// https://code.google.com/p/android/issues/detail?id=9953
LogLength = 4096;
}
#endif
if (LogLength > 1)
{
CompileLog = (ANSICHAR *)FMemory::Malloc(LogLength);
glGetShaderInfoLog(Shader, LogLength, NULL, CompileLog);
}
#if DEBUG_GL_SHADERS
if (GlslCode)
{
UE_LOG(LogRHI,Warning,TEXT("Shader:\n%s"),ANSI_TO_TCHAR(GlslCode));
const ANSICHAR *Temp = GlslCode;
for ( int i = 0; i < 30 && (*Temp != '\0'); ++i )
{
FString Converted = ANSI_TO_TCHAR( Temp );
Converted.LeftChop( 256 );
UE_LOG(LogRHI,Display,TEXT("%s"), *Converted );
Temp += Converted.Len();
}
}
#endif
UE_LOG(LogRHI,Warning,TEXT("Failed to compile shader. Compile log:\n%s"), ANSI_TO_TCHAR(CompileLog));
if (LogLength > 1)
{
FMemory::Free(CompileLog);
}
return false;
}
return true;
}
#endif
static void CheckVaryingLimit()
{
#if PLATFORM_ANDROID
FOpenGL::bRequiresGLFragCoordVaryingLimitHack = false;
if (IsES2Platform(GMaxRHIShaderPlatform))
{
// Some mobile GPUs require an available varying vector to support gl_FragCoord.
// If there are only 8 supported, it is possible to run out of varyings on these
// GPUs so test to see if need to fake gl_FragCoord with the assumption it is
// used for mobile HDR mosaic.
// Do not need to do this check if more than 8 varyings supported
if (FOpenGL::GetMaxVaryingVectors() > 8)
{
return;
}
// Make sure MobileHDR is on and device needs mosaic
static auto* MobileHDRCvar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.MobileHDR"));
static auto* MobileHDR32bppModeCvar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.MobileHDR32bppMode"));
const bool bMobileHDR32bpp = (MobileHDRCvar && MobileHDRCvar->GetValueOnAnyThread() == 1)
&& (FAndroidMisc::SupportsFloatingPointRenderTargets() == false || (MobileHDR32bppModeCvar && MobileHDR32bppModeCvar->GetValueOnAnyThread() != 0));
const bool bRequiresMosaic = bMobileHDR32bpp && (!FAndroidMisc::SupportsShaderFramebufferFetch() || (MobileHDR32bppModeCvar && MobileHDR32bppModeCvar->GetValueOnAnyThread() == 1));
if (!bRequiresMosaic)
{
return;
}
UE_LOG(LogRHI, Display, TEXT("Testing for gl_FragCoord requiring a varying since mosaic is enabled"));
FOpenGL::bIsCheckingShaderCompilerHacks = true;
static const ANSICHAR TestVertexProgram[] = "\n"
"#version 100\n"
"attribute vec4 in_ATTRIBUTE0;\n"
"attribute vec4 in_ATTRIBUTE1;\n"
"varying highp vec4 TexCoord0;\n"
"varying highp vec4 TexCoord1;\n"
"varying highp vec4 TexCoord2;\n"
"varying highp vec4 TexCoord3;\n"
"varying highp vec4 TexCoord4;\n"
"varying highp vec4 TexCoord5;\n"
"varying highp vec4 TexCoord6;\n"
"varying highp vec4 TexCoord7;\n"
"void main()\n"
"{\n"
" TexCoord0 = in_ATTRIBUTE1 * vec4(0.1,0.2,0.3,0.4);\n"
" TexCoord1 = in_ATTRIBUTE1 * vec4(0.5,0.6,0.7,0.8);\n"
" TexCoord2 = in_ATTRIBUTE1 * vec4(0.12,0.22,0.32,0.42);\n"
" TexCoord3 = in_ATTRIBUTE1 * vec4(0.52,0.62,0.72,0.82);\n"
" TexCoord4 = in_ATTRIBUTE1 * vec4(0.14,0.24,0.34,0.44);\n"
" TexCoord5 = in_ATTRIBUTE1 * vec4(0.54,0.64,0.74,0.84);\n"
" TexCoord6 = in_ATTRIBUTE1 * vec4(0.16,0.26,0.36,0.46);\n"
" TexCoord7 = in_ATTRIBUTE1 * vec4(0.56,0.66,0.76,0.86);\n"
" gl_Position.xyzw = in_ATTRIBUTE0;\n"
"}\n";
static const ANSICHAR TestFragmentProgram[] = "\n"
"#version 100\n"
"varying highp vec4 TexCoord0;\n"
"varying highp vec4 TexCoord1;\n"
"varying highp vec4 TexCoord2;\n"
"varying highp vec4 TexCoord3;\n"
"varying highp vec4 TexCoord4;\n"
"varying highp vec4 TexCoord5;\n"
"varying highp vec4 TexCoord6;\n"
"varying highp vec4 TexCoord7;\n"
"void main()\n"
"{\n"
" gl_FragColor = TexCoord0 * TexCoord1 * TexCoord2 * TexCoord3 * TexCoord4 * TexCoord5 * TexCoord6 * TexCoord7 * gl_FragCoord.xyxy;"
"}\n";
FShaderCode VertexShaderCode;
{
FOpenGLCodeHeader Header;
Header.FrequencyMarker = 0x5653;
Header.GlslMarker = 0x474c534c;
FMemoryWriter Writer(VertexShaderCode.GetWriteAccess(), true);
Writer << Header;
Writer.Serialize((void*)TestVertexProgram, sizeof(TestVertexProgram));
Writer.Close();
}
FShaderCode FragmentShaderCode;
{
FOpenGLCodeHeader Header;
Header.FrequencyMarker = 0x5053;
Header.GlslMarker = 0x474c534c;
FMemoryWriter Writer(FragmentShaderCode.GetWriteAccess(), true);
Writer << Header;
Writer.Serialize((void*)(TestFragmentProgram), sizeof(TestFragmentProgram));
Writer.Close();
}
// Try to compile test shaders
TRefCountPtr<FOpenGLVertexShader> VertexShader = (FOpenGLVertexShader*)(RHICreateVertexShader(VertexShaderCode.GetReadAccess()).GetReference());
if (!VerifyCompiledShader(VertexShader->Resource, TestVertexProgram, false))
{
UE_LOG(LogRHI, Warning, TEXT("Vertex shader for varying test failed to compile. Try running anyway."));
FOpenGL::bIsCheckingShaderCompilerHacks = false;
return;
}
TRefCountPtr<FOpenGLPixelShader> PixelShader = (FOpenGLPixelShader*)(RHICreatePixelShader(FragmentShaderCode.GetReadAccess()).GetReference());
if (!VerifyCompiledShader(PixelShader->Resource, TestFragmentProgram, false))
{
UE_LOG(LogRHI, Warning, TEXT("Fragment shader for varying test failed to compile. Try running anyway."));
FOpenGL::bIsCheckingShaderCompilerHacks = false;
return;
}
FOpenGL::bIsCheckingShaderCompilerHacks = false;
// Now try linking them.. this is where gl_FragCoord may cause a failure
GLuint Program = glCreateProgram();
glAttachShader(Program, VertexShader->Resource);
glAttachShader(Program, PixelShader->Resource);
glLinkProgram(Program);
GLint LinkStatus = 0;
glGetProgramiv(Program, GL_LINK_STATUS, &LinkStatus);
if (LinkStatus != GL_TRUE)
{
FOpenGL::bRequiresGLFragCoordVaryingLimitHack = true;
UE_LOG(LogRHI, Warning, TEXT("gl_FragCoord uses a varying... enabled hack"));
return;
}
UE_LOG(LogRHI, Warning, TEXT("gl_FragCoord does not need a varying"));
}
#elif PLATFORM_IOS
if (IsES2Platform(GMaxRHIShaderPlatform))
{
FOpenGL::bIsLimitingShaderCompileCount = FPlatformMisc::GetIOSDeviceType() == FPlatformMisc::IOS_IPad4;
}
#endif
}
static void CheckTextureCubeLodSupport()
{
#if PLATFORM_ANDROID
if (IsES2Platform(GMaxRHIShaderPlatform))
{
UE_LOG(LogRHI, Display, TEXT("Testing for shader compiler compatibility"));
FOpenGL::bIsCheckingShaderCompilerHacks = true;
// This code creates a sample program and finds out which hacks are required to compile it
static const ANSICHAR TestFragmentProgram[] = "\n"
"#version 100\n"
"#ifndef DONTEMITEXTENSIONSHADERTEXTURELODENABLE\n"
"#extension GL_EXT_shader_texture_lod : enable\n"
"#endif\n"
"precision mediump float;\n"
"precision mediump int;\n"
"#ifndef DONTEMITSAMPLERDEFAULTPRECISION\n"
"precision mediump sampler2D;\n"
"precision mediump samplerCube;\n"
"#endif\n"
"varying vec3 TexCoord;\n"
"uniform samplerCube Texture;\n"
"void main()\n"
"{\n"
" gl_FragColor = textureCubeLodEXT(Texture,TexCoord, 4.0);\n"
"}\n";
FOpenGL::bRequiresDontEmitPrecisionForTextureSamplers = false;
FOpenGL::bRequiresTextureCubeLodEXTToTextureCubeLodDefine = false;
FShaderCode ShaderCode;
{
FOpenGLCodeHeader Header;
Header.FrequencyMarker = 0x5053;
Header.GlslMarker = 0x474c534c;
FMemoryWriter Writer(ShaderCode.GetWriteAccess(), true);
Writer << Header;
Writer.Serialize((void*)TestFragmentProgram, sizeof(TestFragmentProgram));
Writer.Close();
}
const TArray<uint8>& Code = ShaderCode.GetReadAccess();
// try to compile without any hacks
TRefCountPtr<FOpenGLPixelShader> PixelShader = (FOpenGLPixelShader*)(RHICreatePixelShader(Code).GetReference());
if (VerifyCompiledShader(PixelShader->Resource, TestFragmentProgram, false))
{
UE_LOG(LogRHI, Display, TEXT("Shaders compile fine no need to enable hacks"));
// we are done
FOpenGL::bIsCheckingShaderCompilerHacks = false;
return;
}
FOpenGL::bRequiresDontEmitPrecisionForTextureSamplers = true;
FOpenGL::bRequiresTextureCubeLodEXTToTextureCubeLodDefine = false;
// second most number of devices fall into this hack category
// try to compile without using precision for texture samplers
// Samsung Galaxy Express Samsung Galaxy S3 Samsung Galaxy S3 mini Samsung Galaxy Tab GT-P1000 Samsung Galaxy Tab 2
PixelShader = (FOpenGLPixelShader*)(RHICreatePixelShader(Code).GetReference());
if (VerifyCompiledShader(PixelShader->Resource, TestFragmentProgram, false))
{
UE_LOG(LogRHI, Warning, TEXT("Enabling shader compiler hack to remove precision modifiers for texture samplers"));
// we are done
FOpenGL::bIsCheckingShaderCompilerHacks = false;
return;
}
FOpenGL::bRequiresDontEmitPrecisionForTextureSamplers = false;
FOpenGL::bRequiresTextureCubeLodEXTToTextureCubeLodDefine = true;
// third most likely Samsung Galaxy Tab GT-P1000
PixelShader = (FOpenGLPixelShader*)(RHICreatePixelShader(Code).GetReference());
if (VerifyCompiledShader(PixelShader->Resource, TestFragmentProgram, false))
{
UE_LOG(LogRHI, Warning, TEXT("Enabling shader compiler hack to redefine textureCubeLodEXT to textureCubeLod"));
// we are done
FOpenGL::bIsCheckingShaderCompilerHacks = false;
return;
}
FOpenGL::bRequiresDontEmitPrecisionForTextureSamplers = true;
FOpenGL::bRequiresTextureCubeLodEXTToTextureCubeLodDefine = true;
// try both hacks
PixelShader = (FOpenGLPixelShader*)(RHICreatePixelShader(Code).GetReference());
if (VerifyCompiledShader(PixelShader->Resource, TestFragmentProgram, false))
{
UE_LOG(LogRHI, Warning, TEXT("Enabling shader compiler hack to redefine textureCubeLodEXT to textureCubeLod and remove precision modifiers"));
// we are done
FOpenGL::bIsCheckingShaderCompilerHacks = false;
return;
}
UE_LOG(LogRHI, Warning, TEXT("Unable to find a test shader that compiles try running anyway"));
FOpenGL::bIsCheckingShaderCompilerHacks = false;
}
#endif
}
void FOpenGLDynamicRHI::Init()
{
check(!GIsRHIInitialized);
VERIFY_GL_SCOPE();
FOpenGLProgramBinaryCache::Initialize();
FShaderCache::SetMaxShaderResources(FOpenGL::GetMaxTextureImageUnits());
InitializeStateResources();
// Create a default point sampler state for internal use.
FSamplerStateInitializerRHI PointSamplerStateParams(SF_Point,AM_Clamp,AM_Clamp,AM_Clamp);
PointSamplerState = this->RHICreateSamplerState(PointSamplerStateParams);
// Allocate vertex and index buffers for DrawPrimitiveUP calls.
DynamicVertexBuffers.Init(CalcDynamicBufferSize(1));
DynamicIndexBuffers.Init(CalcDynamicBufferSize(1));
// Notify all initialized FRenderResources that there's a valid RHI device to create their RHI resources for now.
for(TLinkedList<FRenderResource*>::TIterator ResourceIt(FRenderResource::GetResourceList());ResourceIt;ResourceIt.Next())
{
ResourceIt->InitRHI();
}
// Dynamic resources can have dependencies on static resources (with uniform buffers) and must initialized last!
for(TLinkedList<FRenderResource*>::TIterator ResourceIt(FRenderResource::GetResourceList());ResourceIt;ResourceIt.Next())
{
ResourceIt->InitDynamicRHI();
}
#if PLATFORM_WINDOWS || PLATFORM_MAC || PLATFORM_LINUX
extern int64 GOpenGLDedicatedVideoMemory;
extern int64 GOpenGLTotalGraphicsMemory;
GOpenGLDedicatedVideoMemory = FOpenGL::GetVideoMemorySize();
if ( GOpenGLDedicatedVideoMemory != 0)
{
GOpenGLTotalGraphicsMemory = GOpenGLDedicatedVideoMemory;
if ( GPoolSizeVRAMPercentage > 0 )
{
float PoolSize = float(GPoolSizeVRAMPercentage) * 0.01f * float(GOpenGLTotalGraphicsMemory);
// Truncate GTexturePoolSize to MB (but still counted in bytes)
GTexturePoolSize = int64(FGenericPlatformMath::TruncToInt(PoolSize / 1024.0f / 1024.0f)) * 1024 * 1024;
UE_LOG(LogRHI, Log, TEXT("Texture pool is %llu MB (%d%% of %llu MB)"),
GTexturePoolSize / 1024 / 1024,
GPoolSizeVRAMPercentage,
GOpenGLTotalGraphicsMemory / 1024 / 1024);
}
}
#endif
// Flush here since we might be switching to a different context/thread for rendering
FOpenGL::Flush();
FHardwareInfo::RegisterHardwareInfo( NAME_RHI, TEXT( "OpenGL" ) );
// Set the RHI initialized flag.
GIsRHIInitialized = true;
CheckTextureCubeLodSupport();
CheckVaryingLimit();
}
void FOpenGLDynamicRHI::Shutdown()
{
check(IsInGameThread() && IsInRenderingThread()); // require that the render thread has been shut down
Cleanup();
DestroyShadersAndPrograms();
PlatformDestroyOpenGLDevice(PlatformDevice);
PrivateOpenGLDevicePtr = NULL;
}
void FOpenGLDynamicRHI::Cleanup()
{
if(GIsRHIInitialized)
{
FOpenGLProgramBinaryCache::Shutdown();
// Reset the RHI initialized flag.
GIsRHIInitialized = false;
GPUProfilingData.Cleanup();
// Ask all initialized FRenderResources to release their RHI resources.
for(TLinkedList<FRenderResource*>::TIterator ResourceIt(FRenderResource::GetResourceList());ResourceIt;ResourceIt.Next())
{
ResourceIt->ReleaseRHI();
}
for(TLinkedList<FRenderResource*>::TIterator ResourceIt(FRenderResource::GetResourceList());ResourceIt;ResourceIt.Next())
{
ResourceIt->ReleaseDynamicRHI();
}
}
// Release dynamic vertex and index buffers.
DynamicVertexBuffers.Cleanup();
DynamicIndexBuffers.Cleanup();
FreeZeroStrideBuffers();
// Release the point sampler state.
PointSamplerState.SafeRelease();
extern void EmptyGLSamplerStateCache();
EmptyGLSamplerStateCache();
// Release zero-filled dummy uniform buffer, if it exists.
if (PendingState.ZeroFilledDummyUniformBuffer)
{
FOpenGL::DeleteBuffers(1, &PendingState.ZeroFilledDummyUniformBuffer);
PendingState.ZeroFilledDummyUniformBuffer = 0;
DecrementBufferMemory(GL_UNIFORM_BUFFER, false, ZERO_FILLED_DUMMY_UNIFORM_BUFFER_SIZE);
}
// Release pending shader
PendingState.BoundShaderState.SafeRelease();
check(!IsValidRef(PendingState.BoundShaderState));
PendingState.CleanupResources();
SharedContextState.CleanupResources();
RenderingContextState.CleanupResources();
}
void FOpenGLDynamicRHI::RHIFlushResources()
{
PlatformFlushIfNeeded();
}
void FOpenGLDynamicRHI::RHIAcquireThreadOwnership()
{
check(!bRevertToSharedContextAfterDrawingViewport); // if this is true, then main thread is rendering using our context right now.
PlatformRenderingContextSetup(PlatformDevice);
PlatformRebindResources(PlatformDevice);
bIsRenderingContextAcquired = true;
VERIFY_GL(RHIAcquireThreadOwnership);
{
FScopeLock lock(&CustomPresentSection);
if (CustomPresent)
{
CustomPresent->OnAcquireThreadOwnership();
}
}
}
void FOpenGLDynamicRHI::RHIReleaseThreadOwnership()
{
{
FScopeLock lock(&CustomPresentSection);
if (CustomPresent)
{
CustomPresent->OnReleaseThreadOwnership();
}
}
VERIFY_GL(RHIReleaseThreadOwnership);
bIsRenderingContextAcquired = false;
PlatformNULLContextSetup();
}
void FOpenGLDynamicRHI::RegisterQuery( FOpenGLRenderQuery* Query )
{
FScopeLock Lock(&QueriesListCriticalSection);
Queries.Add(Query);
}
void FOpenGLDynamicRHI::UnregisterQuery( FOpenGLRenderQuery* Query )
{
FScopeLock Lock(&QueriesListCriticalSection);
Queries.RemoveSingleSwap(Query);
}
void FOpenGLDynamicRHI::RHIAutomaticCacheFlushAfterComputeShader(bool bEnable)
{
// Nothing to do here...
}
void FOpenGLDynamicRHI::RHIFlushComputeShaderCache()
{
// Nothing to do here...
}
void* FOpenGLDynamicRHI::RHIGetNativeDevice()
{
return nullptr;
}
void FOpenGLDynamicRHI::InvalidateQueries( void )
{
{
FScopeLock Lock(&QueriesListCriticalSection);
PendingState.RunningOcclusionQuery = 0;
for( int32 Index = 0; Index < Queries.Num(); ++Index )
{
Queries[Index]->bInvalidResource = true;
}
}
{
FScopeLock Lock(&TimerQueriesListCriticalSection);
for( int32 Index = 0; Index < TimerQueries.Num(); ++Index )
{
TimerQueries[Index]->bInvalidResource = true;
}
}
}
void FOpenGLDynamicRHI::SetCustomPresent(FRHICustomPresent* InCustomPresent)
{
FScopeLock lock(&CustomPresentSection);
CustomPresent = InCustomPresent;
}
bool FOpenGLDynamicRHIModule::IsSupported()
{
return true;
}