public PointsGisLayer(Game engine, int maxPointsCount, bool isDynamic = false) : base(engine) { DotsBuffer = new ConstantBuffer(engine.GraphicsDevice, typeof(DotsData)); ColorBuffer = new ConstantBuffer(engine.GraphicsDevice, typeof(ColorData), 16); PointsCountToDraw = maxPointsCount; PointsDrawOffset = 0; SizeMultiplier = 1; IsDynamic = isDynamic; var vbOptions = isDynamic ? VertexBufferOptions.Dynamic : VertexBufferOptions.Default; firstBuffer = new VertexBuffer(engine.GraphicsDevice, typeof(Gis.GeoPoint), maxPointsCount, vbOptions); currentBuffer = firstBuffer; PointsCpu = new Gis.GeoPoint[maxPointsCount]; Flags = (int) (PointFlags.DOTS_WORLDSPACE); shader = Game.Content.Load<Ubershader>("globe.Point.hlsl"); factory = shader.CreateFactory( typeof(PointFlags), Primitive.PointList, VertexInputElement.FromStructure<Gis.GeoPoint>(), BlendState.AlphaBlend, RasterizerState.CullCCW, DepthStencilState.None); ColorDatas = new ColorData[16]; for (int i = 0; i < ColorDatas.Length; i++) { ColorDatas[i] = new ColorData {Color = Color.White}; } ColorBuffer.SetData(ColorDatas); }
protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); try { m_Device.Init( panelOutput.Handle, false, true ); } catch ( Exception _e ) { m_Device = null; MessageBox.Show( "Failed to initialize DX device!\n\n" + _e.Message, "GI Probes Debugger", MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } m_CB_Main = new ConstantBuffer<CB_Main>( m_Device, 0 ); try { m_Shader_Render = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/Render.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );; } catch ( Exception _e ) { MessageBox.Show( "Shader failed to compile!\n\n" + _e.Message, "GI Probes Debugger", MessageBoxButtons.OK, MessageBoxIcon.Error ); m_Shader_Render = null; } // Setup camera m_Camera.CreatePerspectiveCamera( (float) (60.0 * Math.PI / 180.0), (float) panelOutput.Width / panelOutput.Height, 0.01f, 100.0f ); m_Manipulator.Attach( panelOutput, m_Camera ); m_Manipulator.InitializeCamera( new float3( 0, 1, 4 ), new float3( 0, 1, 0 ), float3.UnitY ); }
/// <summary> /// / /// </summary> public override void Initialize () { paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Params) ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
/// <summary> /// Initializes Filter service /// </summary> public override void Initialize() { // create structured buffers and shaders : buffer2 = new StructuredBuffer( device, typeof(Vector2), NumberOfElements , StructuredBufferFlags.None ); paramsCB = new ConstantBuffer( device, typeof(Params) ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
/// <summary> /// /// </summary> public override void Initialize() { LoadContent(); Game.Reloading += (s,e) => LoadContent(); constBuffer = new ConstantBuffer( device, typeof(ConstData) ); constData = new ConstData(); }
// Primitive m_Prim_Cube; public ViewerForm( BImage _Image ) { InitializeComponent(); //TransparencyKey = SystemColors.Control; // Setup device m_Device = new Device(); m_Device.Init( Handle, false, true ); m_CB_Global = new ConstantBuffer< CB_Global >( m_Device, 0 ); // Create shaders m_Shader_Render2D = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"./Shaders/Render2D.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ); // Create the texture try { if ( _Image.m_Opts.m_type == BImage.ImageOptions.TYPE.TT_2D ) { m_Tex2D = _Image.CreateTexture2D( m_Device ); m_CB_Global.m.m_ImageWidth = (uint) m_Tex2D.Width; m_CB_Global.m.m_ImageHeight = (uint) m_Tex2D.Height; m_CB_Global.m.m_ImageDepth = (uint) m_Tex2D.ArraySize; m_CB_Global.m.m_ImageType = 0; integerTrackbarControlMipLevel.RangeMax = m_Tex2D.MipLevelsCount; integerTrackbarControlMipLevel.VisibleRangeMax = m_Tex2D.MipLevelsCount; } else if ( _Image.m_Opts.m_type == BImage.ImageOptions.TYPE.TT_CUBIC ) { m_TexCube = _Image.CreateTextureCube( m_Device ); m_CB_Global.m.m_ImageWidth = (uint) m_TexCube.Width; m_CB_Global.m.m_ImageHeight = (uint) m_TexCube.Height; m_CB_Global.m.m_ImageDepth = (uint) m_TexCube.ArraySize; m_CB_Global.m.m_ImageType = 1; integerTrackbarControlMipLevel.RangeMax = m_TexCube.MipLevelsCount; integerTrackbarControlMipLevel.VisibleRangeMax = m_TexCube.MipLevelsCount; } else if ( _Image.m_Opts.m_type == BImage.ImageOptions.TYPE.TT_3D ) { m_Tex3D = _Image.CreateTexture3D( m_Device ); } // Enable EV manipulation for HDR images bool showExposure = _Image.m_Opts.m_format.m_type == BImage.PixelFormat.Type.FLOAT; labelEV.Visible = showExposure; floatTrackbarControlEV.Visible = showExposure; } catch ( Exception _e ) { MessageBox.Show( this, "Failed to create a valid texture from the image:\r\n\r\n" + _e.Message, "BImage Viewer", MessageBoxButtons.OK, MessageBoxIcon.Error ); } Application.Idle += new EventHandler( Application_Idle ); }
CompiledShaderReader(string fn,string shaderType,ConstantBuffer[] cbs , ShaderParameterDescription[] pds,InputBindingDescription[] rbs,ShaderReflection reflec,ShaderBytecode bytec) { cBuffers = cbs; parameterDescriptions = pds; resourceBindings = rbs; filename = fn; typePrefix = shaderType; reflector = reflec; bytecode = bytec; }
/// <summary> /// / /// </summary> public override void Initialize () { averageLum = new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba16F, 256,256, true, false ); paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Params) ); whiteTex = new DynamicTexture( Game.RenderSystem, 4,4, typeof(Color), false, false); whiteTex.SetData( Enumerable.Range(0,16).Select( i=> Color.White ).ToArray() ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
/// <summary> /// Initializes Filter service /// </summary> public override void Initialize() { paramsCB = new ConstantBuffer( device, typeof(SsaoParams) ); randomDirsCB = new ConstantBuffer( device, typeof(Vector4), MaxSamples ); randomDirsCB.SetData( Enumerable.Range(0,MaxSamples).Select( i => new Vector4(rand.UniformRadialDistribution(0,1), 0) ).ToArray() ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
/// <summary> /// Initializes Filter service /// </summary> public override void Initialize() { bufLinearizeDepth = new ConstantBuffer( rs, 128 ); gaussWeightsCB = new ConstantBuffer( rs, typeof(Vector4), MaxBlurTaps ); sourceRectCB = new ConstantBuffer( rs, typeof(Vector4) ); matrixCB = new ConstantBuffer( rs, typeof(Matrix), 1 ); vectorCB = new ConstantBuffer( rs, typeof(Vector4), 1 ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
/// <summary> /// /// </summary> public override void Initialize () { paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Params) ); injectionVB = new VertexBuffer( Game.GraphicsDevice, typeof(ParticleVertex), MaxInjectingParticles ); simulationSrcVB = new VertexBuffer( Game.GraphicsDevice, typeof(ParticleVertex), MaxSimulatedParticles, VertexBufferOptions.VertexOutput ); simulationDstVB = new VertexBuffer( Game.GraphicsDevice, typeof(ParticleVertex), MaxSimulatedParticles, VertexBufferOptions.VertexOutput ); base.Initialize(); Game.Reloading += Game_Reloading; Game_Reloading( this, EventArgs.Empty ); }
/// <summary> /// Initialization /// </summary> public override void Initialize () { var dev = Game.GraphicsDevice; effect = Game.Content.Load<Ubershader>("debugRender.hlsl"); factory = effect.CreateFactory( typeof(RenderFlags), Primitive.LineList, VertexInputElement.FromStructure( typeof(LineVertex) ), BlendState.AlphaBlend, RasterizerState.CullNone ); constData = new ConstData(); constBuffer = new ConstantBuffer(dev, typeof(ConstData)); // create vertex buffer : vertexBuffer = new VertexBuffer(dev, typeof(LineVertex), vertexBufferSize, VertexBufferOptions.Dynamic ); vertexDataAccum.Capacity = vertexBufferSize; }
/// <summary> /// / /// </summary> public override void Initialize() { base.Initialize(); averageLum = new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba16F, 256,256, true, false ); measuredOld = new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba32F, 1, 1 ); measuredNew = new RenderTarget2D( Game.GraphicsDevice, ColorFormat.Rgba32F, 1, 1 ); paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Params) ); CreateTargets(); LoadContent(); Game.GraphicsDevice.DisplayBoundsChanged += (s,e) => CreateTargets(); Game.Reloading += (s,e) => LoadContent(); }
public override void Draw(GameTime gameTime, ConstantBuffer constBuffer) { Game.GraphicsDevice.VertexShaderConstants[0] = constBuffer; Game.GraphicsDevice.PipelineState = factory[(int)(DebugFlags.DRAW_LINES)]; if (isDirty) { isDirty = false; buf.SetData(lines.ToArray(), 0, Math.Min(lines.Count, buf.Capacity)); } if (lines.Any()) { Game.GraphicsDevice.SetupVertexInput(buf, null); Game.GraphicsDevice.Draw(lines.Count, 0); } }
/// <summary> /// / /// </summary> public override void Initialize () { base.Initialize(); paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Params) ); CreateTargets(); LoadContent(); Random rand = new Random(); randomDir = new Texture2D( Game.GraphicsDevice, 64,64, ColorFormat.Rgba8, false ); randomDir.SetData( Enumerable.Range(0,4096).Select( i => rand.NextColor() ).ToArray() ); Game.GraphicsDevice.DisplayBoundsChanged += (s,e) => CreateTargets(); Game.Reloading += (s,e) => LoadContent(); }
public Form1() { InitializeComponent(); m_Device = new Device(); m_Device.Init( panel1.Handle, false, false ); m_Shader_RenderCellPlanes = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "RenderCellPlanes.hlsl" ) ), VERTEX_FORMAT.T2, "VS", null, "PS", null ); m_Shader_RenderCellMesh = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "RenderCellMesh.hlsl" ) ), VERTEX_FORMAT.P3N3, "VS", null, "PS", null ); m_Shader_RenderCellMesh_Opaque = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "RenderCellMesh_Opaque.hlsl" ) ), VERTEX_FORMAT.P3N3, "VS", null, "PS", null ); m_Shader_PostProcess = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "PostProcess.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ); m_Shader_PostProcess2 = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "PostProcess.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ); VertexT2[] Vertices = new VertexT2[4] { new VertexT2() { UV = new float2( 0, 0 ) }, new VertexT2() { UV = new float2( 0, 1 ) }, new VertexT2() { UV = new float2( 1, 0 ) }, new VertexT2() { UV = new float2( 1, 1 ) }, }; m_Prim_Quad = new Primitive( m_Device, 4, VertexT2.FromArray( Vertices ), null, Primitive.TOPOLOGY.TRIANGLE_STRIP, VERTEX_FORMAT.T2 ); m_RT_WorldPositions[0] = new Texture2D( m_Device, panel1.Width, panel1.Height, 1, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, null ); m_RT_WorldPositions[1] = new Texture2D( m_Device, panel1.Width, panel1.Height, 1, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, null ); m_Device.Clear( m_RT_WorldPositions[0], float4.Zero ); m_Device.Clear( m_RT_WorldPositions[1], float4.Zero ); // Setup camera m_CB_Camera = new ConstantBuffer< CB_Camera >( m_Device, 0 ); m_CB_Mesh = new ConstantBuffer< CB_Mesh >( m_Device, 1 ); m_Camera.CreatePerspectiveCamera( 120.0f * (float) Math.PI / 180.0f, (float) panel1.Width / panel1.Height, 0.01f, 100.0f ); m_Camera.CameraTransformChanged += new EventHandler( Camera_CameraTransformChanged ); m_CameraManipulator.Attach( panel1, m_Camera ); m_CameraManipulator.InitializeCamera( -0.1f * float3.UnitZ, float3.Zero, float3.UnitY ); // Initalize random neighbors integerTrackbarControlNeighborsCount_ValueChanged( integerTrackbarControlNeighborsCount, 0 ); Application.Idle += new EventHandler( Application_Idle ); }
public override void Draw(GameTime gameTime, ConstantBuffer constBuffer) { var dev = Game.GraphicsDevice; dev.VertexShaderConstants[0] = constBuffer; dev.PixelShaderSamplers[0] = SamplerState.AnisotropicClamp; dev.PixelShaderResources[1] = frame; //dev.PipelineState = factory[(int)(TileFlags.SHOW_FRAMES)]; dev.PipelineState = factory[0]; foreach (var globeTile in tilesToRender) { var tex = CurrentMapSource.GetTile(globeTile.Value.X, globeTile.Value.Y, globeTile.Value.Z).Tile; dev.PixelShaderResources[0] = tex; dev.SetupVertexInput(globeTile.Value.VertexBuf, globeTile.Value.IndexBuf); dev.DrawIndexed(globeTile.Value.IndexBuf.Capacity, 0, 0); } }
/// <summary> /// Add services : /// </summary> protected override void Initialize () { // initialize services : base.Initialize(); // create structured buffers and shaders : buffer1 = new StructuredBuffer( GraphicsDevice, typeof(Vector2), NumberOfElements , StructuredBufferFlags.None ); buffer2 = new StructuredBuffer( GraphicsDevice, typeof(Vector2), NumberOfElements , StructuredBufferFlags.None ); paramsCB = new ConstantBuffer( GraphicsDevice, typeof(Params) ); shader = Content.Load<Ubershader>("test"); factory = new StateFactory( shader, typeof(ShaderFlags), Primitive.TriangleList, VertexInputElement.Empty ); // // Create and write data : // var rand = new Random(); var input = Enumerable.Range(0, NumberOfElements).Select( i => new Vector2( rand.NextFloat(0,100), i ) ).ToArray(); buffer1.SetData( input ); // add keyboard handler : InputDevice.KeyDown += InputDevice_KeyDown; }
public void Init() { #if !DEBUG using ( ScopedForceMaterialsLoadFromBinary scope = new ScopedForceMaterialsLoadFromBinary() ) #endif { m_PS_Display = new Shader( Device, new System.IO.FileInfo( "./Shaders/Display.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ); } m_CB_Display = new ConstantBuffer<CBDisplay>( Device, 0 ); m_CB_Display.m._Width = (uint) Width; m_CB_Display.m._Height = (uint) Height; // Setup camera m_Camera.CreatePerspectiveCamera( (float) (60.0 * Math.PI / 180.0), (float) Width / Height, 0.01f, 100.0f ); m_Manipulator.Attach( this, m_Camera ); m_Manipulator.InitializeCamera( new float3( 0, -0.1f, 0.1f ), new float3( 0, 0, 0 ), float3.UnitY ); m_Manipulator.ManipulationPanSpeed = 0.1f; m_Camera.CameraTransformChanged += new EventHandler( Camera_CameraTransformChanged ); m_Manipulator.EnableMouseAction += new CameraManipulator.EnableMouseActionEventHandler( m_Manipulator_EnableMouseAction ); Camera_CameraTransformChanged( m_Manipulator, EventArgs.Empty ); Application.Idle += new EventHandler( Application_Idle ); }
/// <summary> /// /// </summary> public override void Initialize () { LoadContent(); constBuffer = new ConstantBuffer( Game.GraphicsDevice, typeof(CBMeshInstanceData) ); constBufferBones = new ConstantBuffer( Game.GraphicsDevice, typeof(Matrix), MaxBones ); defaultDiffuse = new Texture2D( Game.GraphicsDevice, 4,4, ColorFormat.Rgba8, false ); defaultDiffuse.SetData( Enumerable.Range(0,16).Select( i => Color.Gray ).ToArray() ); defaultSpecular = new Texture2D( Game.GraphicsDevice, 4,4, ColorFormat.Rgba8, false ); defaultSpecular.SetData( Enumerable.Range(0,16).Select( i => new Color(0,128,0,255) ).ToArray() ); defaultNormalMap = new Texture2D( Game.GraphicsDevice, 4,4, ColorFormat.Rgba8, false ); defaultNormalMap.SetData( Enumerable.Range(0,16).Select( i => new Color(128,128,255,255) ).ToArray() ); defaultEmission = new Texture2D( Game.GraphicsDevice, 4,4, ColorFormat.Rgba8, false ); defaultEmission.SetData( Enumerable.Range(0,16).Select( i => Color.Black ).ToArray() ); //Ubershader.AddEnumerator( "SceneRenderer", (t Game.Reloading += (s,e) => LoadContent(); }
public static CompiledShaderReader ReadCompiledShader(string path) { if (File.Exists(path) && (Path.GetExtension(path) == ".cso")) { byte[] bytes = File.ReadAllBytes(path); ShaderReflection reflecter = new ShaderReflection(bytes); ShaderBytecode bytecode = new ShaderBytecode(bytes); ShaderProfile profile = bytecode.GetVersion(); ConstantBuffer[] cbuffers = new ConstantBuffer[reflecter.Description.ConstantBuffers]; for (int i = 0; i < reflecter.Description.ConstantBuffers; i++) { cbuffers[i] = reflecter.GetConstantBuffer(i);//this might not work } ShaderParameterDescription[] paramdescriptions = new ShaderParameterDescription[reflecter.Description.InputParameters]; for (int i = 0; i < reflecter.Description.InputParameters; i++) { paramdescriptions[i] = reflecter.GetInputParameterDescription(i); } InputBindingDescription[] bindings = new InputBindingDescription[reflecter.Description.BoundResources]; for (int i = 0; i < reflecter.Description.BoundResources; i++) { bindings[i] = reflecter.GetResourceBindingDescription(i); } ConstantBuffer[] cbuffersCOPY = cbuffers.ToArray(); return new CompiledShaderReader(path, profile.GetTypePrefix(), cbuffersCOPY, paramdescriptions.ToArray(), bindings.ToArray(), reflecter, bytecode); } else throw new Exception("Bad path " + path); }
protected override void PlatformSetConstantBuffer(int slot, ConstantBuffer cb) { _constantBuffers[slot] = (VkConstantBuffer)cb; }
TextureHandle DirGenRTR(RenderGraph renderGraph, HDCamera hdCamera, ScreenSpaceReflection settings, TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle clearCoatTexture, bool transparent) { using (var builder = renderGraph.AddRenderPass <DirGenRTRPassData>("Generating the rays for RTR", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingIndirectDiffuseDirectionGeneration))) { builder.EnableAsyncCompute(false); // Set the camera parameters passData.texWidth = settings.fullResolution ? hdCamera.actualWidth : hdCamera.actualWidth / 2; passData.texHeight = settings.fullResolution ? hdCamera.actualHeight : hdCamera.actualHeight / 2; passData.viewCount = hdCamera.viewCount; // Set the generation parameters passData.minSmoothness = settings.minSmoothness; // Grab the right kernel passData.directionGenCS = HDRenderPipelineGlobalSettings.instance.renderPipelineRayTracingResources.reflectionRaytracingCS; if (settings.fullResolution) { passData.dirGenKernel = transparent ? m_RaytracingReflectionsTransparentFullResKernel : m_RaytracingReflectionsFullResKernel; } else { passData.dirGenKernel = transparent ? m_RaytracingReflectionsTransparentHalfResKernel : m_RaytracingReflectionsHalfResKernel; } // Grab the additional parameters passData.ditheredTextureSet = GetBlueNoiseManager().DitheredTextureSet8SPP(); passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB; passData.depthBuffer = builder.ReadTexture(depthPyramid); passData.stencilBuffer = builder.ReadTexture(stencilBuffer); passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Reflection Ray Directions" })); builder.SetRenderFunc( (DirGenRTRPassData data, RenderGraphContext ctx) => { // TODO: check if this is required, i do not think so CoreUtils.SetRenderTarget(ctx.cmd, data.outputBuffer, ClearFlag.Color, clearColor: Color.black); // Inject the ray-tracing sampling data BlueNoise.BindDitheredTextureSet(ctx.cmd, data.ditheredTextureSet); // Bind all the required scalars to the CB data.shaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness = data.minSmoothness; ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind all the required textures ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._DepthTexture, data.depthBuffer); ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._NormalBufferTexture, data.normalBuffer); ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._SsrClearCoatMaskTexture, data.clearCoatMaskTexture); ctx.cmd.SetComputeIntParam(data.directionGenCS, HDShaderIDs._SsrStencilBit, (int)StencilUsage.TraceReflectionRay); ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._StencilTexture, data.stencilBuffer, 0, RenderTextureSubElement.Stencil); // Bind the output buffers ctx.cmd.SetComputeTextureParam(data.directionGenCS, data.dirGenKernel, HDShaderIDs._RaytracingDirectionBuffer, data.outputBuffer); // Evaluate the dispatch parameters int numTilesX = (data.texWidth + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize; int numTilesY = (data.texHeight + (rtReflectionsComputeTileSize - 1)) / rtReflectionsComputeTileSize; // Compute the directions ctx.cmd.DispatchCompute(data.directionGenCS, data.dirGenKernel, numTilesX, numTilesY, data.viewCount); }); return(passData.outputBuffer); } }
private void ValidateConstantBufferReflection(ConstantBuffer constantBufferRaw, ref ConstantBufferDescription constantBufferRawDesc, EffectConstantBufferDescription constantBuffer, LoggerResult log) { switch (constantBufferRawDesc.Type) { case SharpDX.D3DCompiler.ConstantBufferType.ConstantBuffer: if (constantBuffer.Type != ConstantBufferType.ConstantBuffer) { log.Error($"Invalid buffer type for {constantBuffer.Name}: {constantBuffer.Type} instead of {ConstantBufferType.ConstantBuffer}"); } break; case SharpDX.D3DCompiler.ConstantBufferType.TextureBuffer: if (constantBuffer.Type != ConstantBufferType.TextureBuffer) { log.Error($"Invalid buffer type for {constantBuffer.Name}: {constantBuffer.Type} instead of {ConstantBufferType.TextureBuffer}"); } break; default: if (constantBuffer.Type != ConstantBufferType.Unknown) { log.Error($"Invalid buffer type for {constantBuffer.Name}: {constantBuffer.Type} instead of {ConstantBufferType.Unknown}"); } break; } // ConstantBuffers variables for (int i = 0; i < constantBufferRawDesc.VariableCount; i++) { var variable = constantBufferRaw.GetVariable(i); var variableType = variable.GetVariableType(); var variableDescription = variable.Description; var variableTypeDescription = variableType.Description; if (variableTypeDescription.Offset != 0) { log.Error($"Unexpected offset [{variableTypeDescription.Offset}] for variable [{variableDescription.Name}] in constant buffer [{constantBuffer.Name}]"); } var binding = constantBuffer.Members[i]; // Retrieve Link Member if (binding.RawName != variableDescription.Name) { log.Error($"Variable [{variableDescription.Name}] in constant buffer [{constantBuffer.Name}] has no link"); } else { var parameter = new EffectValueDescription() { Type = { Class = (EffectParameterClass)variableTypeDescription.Class, Type = ConvertVariableValueType(variableTypeDescription.Type, log), Elements = variableTypeDescription.ElementCount, RowCount = (byte)variableTypeDescription.RowCount, ColumnCount = (byte)variableTypeDescription.ColumnCount, }, RawName = variableDescription.Name, Offset = variableDescription.StartOffset, Size = variableDescription.Size, }; if (parameter.Offset != binding.Offset || parameter.Size != binding.Size || parameter.Type.Elements != binding.Type.Elements || ((parameter.Type.Class != EffectParameterClass.Struct) && // Ignore columns/rows if it's a struct (sometimes it contains weird data) (parameter.Type.RowCount != binding.Type.RowCount || parameter.Type.ColumnCount != binding.Type.ColumnCount))) { log.Error($"Variable [{variableDescription.Name}] in constant buffer [{constantBuffer.Name}] binding doesn't match what was expected"); } } } if (constantBuffer.Size != constantBufferRawDesc.Size) { log.Error($"Error precomputing buffer size for {constantBuffer.Name}: {constantBuffer.Size} instead of {constantBufferRawDesc.Size}"); } }
private ShaderConstantBufferDescription GetConstantBufferReflection(ConstantBuffer constantBufferRaw, ref ConstantBufferDescription constantBufferRawDesc, ShaderConstantBufferDescription linkBuffer, LoggerResult log) { var constantBuffer = new ShaderConstantBufferDescription { Name = constantBufferRawDesc.Name, Size = constantBufferRawDesc.Size, }; switch (constantBufferRawDesc.Type) { case SharpDX.D3DCompiler.ConstantBufferType.ConstantBuffer: constantBuffer.Type = ConstantBufferType.ConstantBuffer; break; case SharpDX.D3DCompiler.ConstantBufferType.TextureBuffer: constantBuffer.Type = ConstantBufferType.TextureBuffer; break; default: constantBuffer.Type = ConstantBufferType.Unknown; break; } // ConstantBuffers variables var members = new List<EffectParameterValueData>(); for (int i = 0; i < constantBufferRawDesc.VariableCount; i++) { var variable = constantBufferRaw.GetVariable(i); var variableType = variable.GetVariableType(); var variableDescription = variable.Description; var variableTypeDescription = variableType.Description; var parameter = new EffectParameterValueData() { Param = { Class = (EffectParameterClass)variableTypeDescription.Class, Type = ConvertVariableValueType(variableTypeDescription.Type, log), RawName = variableDescription.Name, }, Offset = variableDescription.StartOffset, Size = variableDescription.Size, Count = variableTypeDescription.ElementCount == 0 ? 1 : variableTypeDescription.ElementCount, RowCount = (byte)variableTypeDescription.RowCount, ColumnCount = (byte)variableTypeDescription.ColumnCount, }; if (variableTypeDescription.Offset != 0) { log.Error("Unexpected offset [{0}] for variable [{1}] in constant buffer [{2}]", variableTypeDescription.Offset, variableDescription.Name, constantBuffer.Name); } bool bindingNotFound = true; // Retrieve Link Member foreach (var binding in linkBuffer.Members) { if (binding.Param.RawName == variableDescription.Name) { // TODO: should we replicate linkMember.Count/RowCount/ColumnCount? or use what is retrieved by D3DCompiler reflection parameter.Param.KeyName = binding.Param.KeyName; bindingNotFound = false; break; } } if (bindingNotFound) { log.Error("Variable [{0}] in constant buffer [{1}] has no link", variableDescription.Name, constantBuffer.Name); } members.Add(parameter); } constantBuffer.Members = members.ToArray(); return constantBuffer; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect Simple point cloud view sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); VertexShader vertexShader = ShaderCompiler.CompileFromFile<VertexShader>(device, "ColoredPointCloudView.fx", "VS"); PixelShader pixelShader = ShaderCompiler.CompileFromFile<PixelShader>(device, "ColoredPointCloudView.fx", "PS"); DX11NullInstancedDrawer nulldrawer = new DX11NullInstancedDrawer(); nulldrawer.VertexCount = Consts.DepthWidth; nulldrawer.InstanceCount = Consts.DepthHeight; DX11NullGeometry nullGeom = new DX11NullGeometry(device, nulldrawer); nullGeom.Topology = SharpDX.Direct3D.PrimitiveTopology.PointList; KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); cbCamera camera = new cbCamera(); camera.Projection = Matrix.PerspectiveFovLH(1.57f * 0.5f, 1.3f, 0.01f, 100.0f); camera.View = Matrix.Translation(0.0f, 0.0f, 2.0f); camera.Projection.Transpose(); camera.View.Transpose(); ConstantBuffer<cbCamera> cameraBuffer = new ConstantBuffer<cbCamera>(device); cameraBuffer.Update(context, ref camera); bool doQuit = false; bool uploadCamera = false; bool uploadRgb = false; CameraRGBFrameData cameraFrame = new CameraRGBFrameData(); DynamicCameraRGBTexture cameraTexture = new DynamicCameraRGBTexture(device); DepthToColorFrameData depthToColorFrame = new DepthToColorFrameData(); DynamicDepthToColorTexture depthToColorTexture = new DynamicDepthToColorTexture(device); KinectSensorDepthFrameProvider provider = new KinectSensorDepthFrameProvider(sensor); provider.FrameReceived += (sender, args) => { cameraFrame.Update(sensor.CoordinateMapper, args.DepthData); depthToColorFrame.Update(sensor.CoordinateMapper, args.DepthData); uploadCamera = true; }; //Get coordinate map + rgb ColorRGBAFrameData colorFrame = new ColorRGBAFrameData(); DynamicColorRGBATexture colorTexture = new DynamicColorRGBATexture(device); KinectSensorColorRGBAFrameProvider colorProvider = new KinectSensorColorRGBAFrameProvider(sensor); colorProvider.FrameReceived += (sender, args) => { colorFrame = args.FrameData; uploadRgb = true; }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } if (uploadCamera) { cameraTexture.Copy(context.Context, cameraFrame); depthToColorTexture.Copy(context.Context, depthToColorFrame); uploadCamera = false; } if (uploadRgb) { colorTexture.Copy(context.Context, colorFrame); uploadRgb = false; } context.RenderTargetStack.Push(swapChain); context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black); context.Context.VertexShader.Set(vertexShader); context.Context.PixelShader.Set(pixelShader); context.Context.VertexShader.SetShaderResource(0, cameraTexture.ShaderView); context.Context.VertexShader.SetShaderResource(1, colorTexture.ShaderView); context.Context.VertexShader.SetShaderResource(2, depthToColorTexture.ShaderView); context.Context.VertexShader.SetSampler(0, device.SamplerStates.LinearClamp); context.Context.VertexShader.SetConstantBuffer(0, cameraBuffer.Buffer); nullGeom.Bind(context, null); nullGeom.Draw(context); context.RenderTargetStack.Pop(); swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); cameraBuffer.Dispose(); cameraTexture.Dispose(); provider.Dispose(); pixelShader.Dispose(); vertexShader.Dispose(); sensor.Close(); colorTexture.Dispose(); colorProvider.Dispose(); depthToColorFrame.Dispose(); depthToColorTexture.Dispose(); }
TextureHandle QualityRTGI(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthPyramid, TextureHandle normalBuffer, TextureHandle rayCountTexture) { using (var builder = renderGraph.AddRenderPass <TraceQualityRTGIPassData>("Quality RT Indirect Diffuse", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingIndirectDiffuseEvaluation))) { builder.EnableAsyncCompute(false); var settings = hdCamera.volumeStack.GetComponent <GlobalIllumination>(); // Set the camera parameters passData.texWidth = hdCamera.actualWidth; passData.texHeight = hdCamera.actualHeight; passData.viewCount = hdCamera.viewCount; // Evaluation parameters passData.rayLength = settings.rayLength; passData.sampleCount = settings.sampleCount.value; passData.clampValue = settings.clampValue; passData.bounceCount = settings.bounceCount.value; // Grab the additional parameters passData.indirectDiffuseRT = m_Asset.renderPipelineRayTracingResources.indirectDiffuseRaytracingRT; passData.accelerationStructure = RequestAccelerationStructure(); passData.lightCluster = RequestLightCluster(); passData.skyTexture = m_SkyManager.GetSkyReflection(hdCamera); passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB; passData.ditheredTextureSet = GetBlueNoiseManager().DitheredTextureSet8SPP(); passData.depthBuffer = builder.ReadTexture(depthPyramid); passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.rayCountTexture = builder.ReadWriteTexture(rayCountTexture); passData.outputBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Indirect Diffuse" })); builder.SetRenderFunc( (TraceQualityRTGIPassData data, RenderGraphContext ctx) => { // Define the shader pass to use for the indirect diffuse pass ctx.cmd.SetRayTracingShaderPass(data.indirectDiffuseRT, "IndirectDXR"); // Set the acceleration structure for the pass ctx.cmd.SetRayTracingAccelerationStructure(data.indirectDiffuseRT, HDShaderIDs._RaytracingAccelerationStructureName, data.accelerationStructure); // Inject the ray-tracing sampling data BlueNoise.BindDitheredTextureSet(ctx.cmd, data.ditheredTextureSet); // Set the data for the ray generation ctx.cmd.SetRayTracingTextureParam(data.indirectDiffuseRT, HDShaderIDs._IndirectDiffuseTextureRW, data.outputBuffer); ctx.cmd.SetRayTracingTextureParam(data.indirectDiffuseRT, HDShaderIDs._DepthTexture, data.depthBuffer); ctx.cmd.SetRayTracingTextureParam(data.indirectDiffuseRT, HDShaderIDs._NormalBufferTexture, data.normalBuffer); // Set ray count texture ctx.cmd.SetRayTracingTextureParam(data.indirectDiffuseRT, HDShaderIDs._RayCountTexture, data.rayCountTexture); // LightLoop data data.lightCluster.BindLightClusterData(ctx.cmd); // Set the data for the ray miss ctx.cmd.SetRayTracingTextureParam(data.indirectDiffuseRT, HDShaderIDs._SkyTexture, data.skyTexture); // Update global constant buffer data.shaderVariablesRayTracingCB._RaytracingIntensityClamp = data.clampValue; data.shaderVariablesRayTracingCB._RaytracingIncludeSky = 1; data.shaderVariablesRayTracingCB._RaytracingRayMaxLength = data.rayLength; data.shaderVariablesRayTracingCB._RaytracingNumSamples = data.sampleCount; data.shaderVariablesRayTracingCB._RaytracingMaxRecursion = data.bounceCount; data.shaderVariablesRayTracingCB._RayTracingDiffuseLightingOnly = 1; ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Only use the shader variant that has multi bounce if the bounce count > 1 CoreUtils.SetKeyword(ctx.cmd, "MULTI_BOUNCE_INDIRECT", data.bounceCount > 1); // Run the computation ctx.cmd.DispatchRays(data.indirectDiffuseRT, m_RayGenIndirectDiffuseIntegrationName, (uint)data.texWidth, (uint)data.texHeight, (uint)data.viewCount); // Disable the keywords we do not need anymore CoreUtils.SetKeyword(ctx.cmd, "MULTI_BOUNCE_INDIRECT", false); }); return(passData.outputBuffer); } }
TextureHandle QualityRTR(RenderGraph renderGraph, HDCamera hdCamera, ScreenSpaceReflection settings, TextureHandle depthPyramid, TextureHandle stencilBuffer, TextureHandle normalBuffer, TextureHandle clearCoatTexture, TextureHandle rayCountTexture, bool transparent) { using (var builder = renderGraph.AddRenderPass <TraceQualityRTRPassData>("Quality RT Reflections", out var passData, ProfilingSampler.Get(HDProfileId.RaytracingReflectionEvaluation))) { builder.EnableAsyncCompute(false); // Camera parameters passData.texWidth = hdCamera.actualWidth; passData.texHeight = hdCamera.actualHeight; passData.viewCount = hdCamera.viewCount; // Reflection evaluation parameters passData.clampValue = settings.clampValue; passData.reflectSky = settings.reflectSky.value ? 1 : 0; passData.rayLength = settings.rayLength; passData.sampleCount = settings.sampleCount.value; passData.bounceCount = settings.bounceCount.value; passData.transparent = transparent; passData.minSmoothness = settings.minSmoothness; passData.smoothnessFadeStart = settings.smoothnessFadeStart; passData.lodBias = settings.textureLodBias.value; // Other parameters passData.accelerationStructure = RequestAccelerationStructure(); passData.lightCluster = RequestLightCluster(); passData.ditheredTextureSet = GetBlueNoiseManager().DitheredTextureSet8SPP(); passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB; passData.skyTexture = m_SkyManager.GetSkyReflection(hdCamera); passData.reflectionShader = HDRenderPipelineGlobalSettings.instance.renderPipelineRayTracingResources.reflectionRaytracingRT; passData.depthBuffer = builder.ReadTexture(depthPyramid); passData.stencilBuffer = builder.ReadTexture(stencilBuffer); passData.normalBuffer = builder.ReadTexture(normalBuffer); passData.clearCoatMaskTexture = builder.ReadTexture(clearCoatTexture); passData.rayCountTexture = builder.ReadWriteTexture(rayCountTexture); passData.outputTexture = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Ray Traced Reflections" })); builder.SetRenderFunc( (TraceQualityRTRPassData data, RenderGraphContext ctx) => { // Define the shader pass to use for the reflection pass ctx.cmd.SetRayTracingShaderPass(data.reflectionShader, "IndirectDXR"); // Set the acceleration structure for the pass ctx.cmd.SetRayTracingAccelerationStructure(data.reflectionShader, HDShaderIDs._RaytracingAccelerationStructureName, data.accelerationStructure); // Global reflection parameters data.shaderVariablesRayTracingCB._RaytracingIntensityClamp = data.clampValue; data.shaderVariablesRayTracingCB._RaytracingIncludeSky = data.reflectSky; // Inject the ray generation data data.shaderVariablesRayTracingCB._RaytracingRayMaxLength = data.rayLength; data.shaderVariablesRayTracingCB._RaytracingNumSamples = data.sampleCount; // Set the number of bounces for reflections data.shaderVariablesRayTracingCB._RaytracingMaxRecursion = data.bounceCount; data.shaderVariablesRayTracingCB._RayTracingDiffuseLightingOnly = 0; // Bind all the required scalars to the CB data.shaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness = data.minSmoothness; data.shaderVariablesRayTracingCB._RaytracingReflectionSmoothnessFadeStart = data.smoothnessFadeStart; data.shaderVariablesRayTracingCB._RayTracingLodBias = data.lodBias; ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Inject the ray-tracing sampling data BlueNoise.BindDitheredTextureSet(ctx.cmd, data.ditheredTextureSet); // Set the data for the ray generation ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._SsrLightingTextureRW, data.outputTexture); ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._DepthTexture, data.depthBuffer); ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._NormalBufferTexture, data.normalBuffer); ctx.cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, data.stencilBuffer, RenderTextureSubElement.Stencil); ctx.cmd.SetRayTracingIntParams(data.reflectionShader, HDShaderIDs._SsrStencilBit, (int)StencilUsage.TraceReflectionRay); // Set ray count texture ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._RayCountTexture, data.rayCountTexture); // Bind the lightLoop data data.lightCluster.BindLightClusterData(ctx.cmd); // Evaluate the clear coat mask texture based on the lit shader mode ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._SsrClearCoatMaskTexture, data.clearCoatMaskTexture); // Set the data for the ray miss ctx.cmd.SetRayTracingTextureParam(data.reflectionShader, HDShaderIDs._SkyTexture, data.skyTexture); // Only use the shader variant that has multi bounce if the bounce count > 1 CoreUtils.SetKeyword(ctx.cmd, "MULTI_BOUNCE_INDIRECT", data.bounceCount > 1); // Run the computation ctx.cmd.DispatchRays(data.reflectionShader, data.transparent ? m_RayGenIntegrationTransparentName : m_RayGenIntegrationName, (uint)data.texWidth, (uint)data.texHeight, (uint)data.viewCount); // Disable multi-bounce CoreUtils.SetKeyword(ctx.cmd, "MULTI_BOUNCE_INDIRECT", false); }); return(passData.outputTexture); } }
void RenderSSGI(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, int frameCount) { // Grab the global illumination volume component GlobalIllumination giSettings = hdCamera.volumeStack.GetComponent <GlobalIllumination>(); // Grab the noise texture manager BlueNoise blueNoise = GetBlueNoiseManager(); // Grab the shaders we shall be using ComputeShader ssGICS = m_Asset.renderPipelineResources.shaders.screenSpaceGlobalIlluminationCS; // Evaluate the dispatch parameters int texWidth, texHeight; if (giSettings.fullResolutionSS) { texWidth = hdCamera.actualWidth; texHeight = hdCamera.actualHeight; halfScreenSize.Set(texWidth * 0.5f, texHeight * 0.5f, 2.0f / texWidth, 2.0f / texHeight); } else { texWidth = hdCamera.actualWidth / 2; texHeight = hdCamera.actualHeight / 2; halfScreenSize.Set(texWidth, texHeight, 1.0f / texWidth, 1.0f / texHeight); } int areaTileSize = 8; int numTilesXHR = (texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (texHeight + (areaTileSize - 1)) / areaTileSize; // Based on if we are doing it in half resolution or full, we need to define initial and final buffer to avoid a useless blit RTHandle buffer0, buffer1; if (!giSettings.fullResolutionSS) { buffer0 = m_IndirectDiffuseBuffer0; buffer1 = m_IndirectDiffuseBuffer1; } else { buffer0 = m_IndirectDiffuseBuffer1; buffer1 = m_IndirectDiffuseBuffer0; } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SsgiPass))) { // Fetch the right tracing kernel int currentKernel = giSettings.fullResolutionSS ? m_TraceGlobalIlluminationKernel : m_TraceGlobalIlluminationHalfKernel; // Inject all the input scalars float n = hdCamera.camera.nearClipPlane; float f = hdCamera.camera.farClipPlane; float thickness = giSettings.depthBufferThickness.value; float thicknessScale = 1.0f / (1.0f + thickness); float thicknessBias = -n / (f - n) * (thickness * thicknessScale); cmd.SetComputeFloatParam(ssGICS, HDShaderIDs._IndirectDiffuseThicknessScale, thicknessScale); cmd.SetComputeFloatParam(ssGICS, HDShaderIDs._IndirectDiffuseThicknessBias, thicknessBias); cmd.SetComputeIntParam(ssGICS, HDShaderIDs._IndirectDiffuseSteps, giSettings.raySteps); cmd.SetComputeFloatParam(ssGICS, HDShaderIDs._IndirectDiffuseMaximalRadius, giSettings.maximalRadius); // Inject half screen size if required if (!giSettings.fullResolutionSS) { cmd.SetComputeVectorParam(ssGICS, HDShaderIDs._HalfScreenSize, halfScreenSize); } // Inject the ray-tracing sampling data blueNoise.BindDitheredRNGData1SPP(cmd); // Inject all the input textures/buffers cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthTexture()); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._IndirectDiffuseHitPointTextureRW, m_IndirectDiffuseHitPointBuffer); var info = m_SharedRTManager.GetDepthBufferMipChainInfo(); cmd.SetComputeBufferParam(ssGICS, currentKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer)); cmd.SetGlobalBuffer(HDShaderIDs.g_vLightListGlobal, m_TileAndClusterData.lightList); // Do the ray marching cmd.DispatchCompute(ssGICS, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); // Fetch the right kernel to use currentKernel = giSettings.fullResolutionSS ? m_ReprojectGlobalIlluminationKernel : m_ReprojectGlobalIlluminationHalfKernel; // Update global constant buffer. // This should probably be a shader specific uniform instead of reusing the global constant buffer one since it's the only one udpated here. m_ShaderVariablesRayTracingCB._RaytracingIntensityClamp = giSettings.clampValueSS; ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Inject all the input scalars cmd.SetComputeVectorParam(ssGICS, HDShaderIDs._ColorPyramidUvScaleAndLimitPrevFrame, HDUtils.ComputeViewportScaleAndLimit(hdCamera.historyRTHandleProperties.previousViewportSize, hdCamera.historyRTHandleProperties.previousRenderTargetSize)); // Bind all the input buffers cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer()); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._IndirectDiffuseHitPointTexture, m_IndirectDiffuseHitPointBuffer); var previousColorPyramid = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorBufferMipChain); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._ColorPyramidTexture, previousColorPyramid != null ? previousColorPyramid : TextureXR.GetBlackTexture()); var historyDepthBuffer = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth); cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._HistoryDepthTexture, historyDepthBuffer != null ? historyDepthBuffer : TextureXR.GetBlackTexture()); cmd.SetComputeBufferParam(ssGICS, currentKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer)); // Bind the output texture cmd.SetComputeTextureParam(ssGICS, currentKernel, HDShaderIDs._IndirectDiffuseTextureRW, buffer1); // Do the reprojection cmd.DispatchCompute(ssGICS, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); float historyValidity = 1.0f; #if UNITY_HDRP_DXR_TESTS_DEFINE if (Application.isPlaying) { historyValidity = 0.0f; } else #endif // We need to check if something invalidated the history buffers historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; // Do the denoising part SSGIDenoiser ssgiDenoiser = GetSSGIDenoiser(); ssgiDenoiser.Denoise(cmd, hdCamera, buffer1, buffer0, halfResolution: !giSettings.fullResolutionSS, historyValidity: historyValidity); // If this was a half resolution effect, we still have to upscale it if (!giSettings.fullResolutionSS) { ComputeShader bilateralUpsampleCS = m_Asset.renderPipelineResources.shaders.bilateralUpsampleCS; // Re-evaluate the dispatch parameters (we are evaluating the upsample in full resolution) numTilesXHR = (hdCamera.actualWidth + (areaTileSize - 1)) / areaTileSize; numTilesYHR = (hdCamera.actualHeight + (areaTileSize - 1)) / areaTileSize; // Inject the input scalars cmd.SetComputeVectorParam(bilateralUpsampleCS, HDShaderIDs._HalfScreenSize, halfScreenSize); firstMipOffset.Set(HDShadowUtils.Asfloat((uint)info.mipLevelOffsets[1].x), HDShadowUtils.Asfloat((uint)info.mipLevelOffsets[1].y)); cmd.SetComputeVectorParam(bilateralUpsampleCS, HDShaderIDs._DepthPyramidFirstMipLevelOffset, firstMipOffset); // Inject all the input buffers cmd.SetComputeTextureParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthTexture()); cmd.SetComputeTextureParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._LowResolutionTexture, buffer1); cmd.SetComputeBufferParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._DepthPyramidMipLevelOffsets, info.GetOffsetBufferData(m_DepthPyramidMipLevelOffsetsBuffer)); // Inject the output textures cmd.SetComputeTextureParam(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, HDShaderIDs._OutputUpscaledTexture, buffer0); // Upscale the buffer to full resolution cmd.DispatchCompute(bilateralUpsampleCS, m_BilateralUpSampleColorTMKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); } (RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, m_IndirectDiffuseBuffer0, FullScreenDebugMode.ScreenSpaceGlobalIllumination); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { m_Device.Init(panelOutput.Handle, false, true); } catch (Exception _e) { m_Device = null; MessageBox.Show("Failed to initialize DX device!\n\n" + _e.Message, "ShaderToy", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { m_Shader_UpdateHeightMap = new ComputeShader(m_Device, new System.IO.FileInfo("Shaders/UpdateHeightMap.hlsl"), "CS"); m_shader_GenerateDensity = new ComputeShader(m_Device, new System.IO.FileInfo("Shaders/GenerateDensity.hlsl"), "CS"); m_Shader_ClearAccumulator = new ComputeShader(m_Device, new System.IO.FileInfo("Shaders/TracePhotons.hlsl"), "CS_ClearAccumulator"); m_Shader_InitPhotons = new ComputeShader(m_Device, new System.IO.FileInfo("Shaders/TracePhotons.hlsl"), "CS_InitPhotons"); m_Shader_TracePhotons = new ComputeShader(m_Device, new System.IO.FileInfo("Shaders/TracePhotons.hlsl"), "CS_TracePhotons"); m_Shader_RenderRoom = new Shader(m_Device, new System.IO.FileInfo("Shaders/RenderRoom.hlsl"), VERTEX_FORMAT.P3N3G3T2, "VS", null, "PS"); m_Shader_RenderSphere = new Shader(m_Device, new System.IO.FileInfo("Shaders/RenderSphere.hlsl"), VERTEX_FORMAT.P3N3G3T2, "VS", null, "PS"); m_Shader_RayMarcher = new Shader(m_Device, new System.IO.FileInfo("Shaders/RayMarch.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); m_Shader_PostProcess = new Shader(m_Device, new System.IO.FileInfo("Shaders/PostProcess.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); // m_ShaderDownsample = new Shader( m_Device, new System.IO.FileInfo( "Shaders/Downsample.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS" ); } catch (Exception _e) { MessageBox.Show("Shader failed to compile!\n\n" + _e.Message, "ShaderToy", MessageBoxButtons.OK, MessageBoxIcon.Error); } uint W = (uint)panelOutput.Width; uint H = (uint)panelOutput.Height; m_CB_Global = new ConstantBuffer <CB_Global>(m_Device, 0); m_CB_Camera = new ConstantBuffer <CB_Camera>(m_Device, 1); m_CB_GenerateDensity = new ConstantBuffer <CB_GenerateDensity>(m_Device, 2); m_CB_TracePhotons = new ConstantBuffer <CB_TracePhotons>(m_Device, 2); m_CB_RenderRoom = new ConstantBuffer <CB_RenderRoom>(m_Device, 2); m_CB_RenderSphere = new ConstantBuffer <CB_RenderSphere>(m_Device, 2); m_CB_PostProcess = new ConstantBuffer <CB_PostProcess>(m_Device, 2); m_CB_RayMarch = new ConstantBuffer <CB_RayMarch>(m_Device, 3); m_Tex_TempBackBuffer = new Texture2D(m_Device, W, H, 1, 1, ImageUtility.PIXEL_FORMAT.RGBA16F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, null); m_Tex_HeightMap = new Texture2D(m_Device, HEIGHTMAP_SIZE, HEIGHTMAP_SIZE, 1, 1, ImageUtility.PIXEL_FORMAT.RG16F, ImageUtility.COMPONENT_FORMAT.AUTO, false, true, null); m_Tex_Scattering = new Texture2D(m_Device, (uint)panelOutput.Width, (uint)panelOutput.Height, 2, 1, ImageUtility.PIXEL_FORMAT.RGBA16F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, null); m_Tex_VolumeDensity = new Texture3D(m_Device, VOLUME_SIZE, VOLUME_SIZE, VOLUME_SIZE, 1, ImageUtility.PIXEL_FORMAT.R8, ImageUtility.COMPONENT_FORMAT.UNORM, false, true, null); m_Tex_AccumPhotonCube = new Texture2D(m_Device, 256, 256, -6, 1, ImageUtility.PIXEL_FORMAT.RGBA16F, ImageUtility.COMPONENT_FORMAT.AUTO, false, true, null); m_Tex_AccumPhoton3D = new Texture3D(m_Device, VOLUME_SIZE, VOLUME_SIZE, VOLUME_SIZE, 1, ImageUtility.PIXEL_FORMAT.R32, ImageUtility.COMPONENT_FORMAT.UINT, false, true, null); BuildNoiseTextures(); //BuildMSBRDF( new DirectoryInfo( @"D:\Workspaces\Patapom.com\Web\blog\patapom\docs\BRDF" ) ); BuildMSBRDF(new DirectoryInfo(@"D:\Workspaces\www.patapom.com\Web\blog\patapom\docs\BRDF")); // Structured buffer m_SB_PhotonInfos = new StructuredBuffer <SB_PhotonInfo_t>(m_Device, PHOTONS_COUNT, false); m_SB_Photons[0] = new StructuredBuffer <SB_Photon_t>(m_Device, PHOTONS_COUNT, false); m_SB_Photons[1] = new StructuredBuffer <SB_Photon_t>(m_Device, PHOTONS_COUNT, false); BuildPrimitives(); // Setup camera m_Camera.CreatePerspectiveCamera((float)(60.0 * Math.PI / 180.0), (float)panelOutput.Width / panelOutput.Height, 0.01f, 100.0f); m_Manipulator.Attach(panelOutput, m_Camera); m_Manipulator.InitializeCamera(new float3(0, 1, -2.5f), new float3(0, 1, 0), float3.UnitY); // Start game time m_Ticks2Seconds = 1.0 / System.Diagnostics.Stopwatch.Frequency; m_StopWatch.Start(); m_StartGameTime = GetGameTime(); }
TextureHandle RaytracingRecursiveRender(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle colorBuffer, TextureHandle depthPyramid, TextureHandle flagMask, TextureHandle rayCountTexture) { // If ray tracing is disabled in the frame settings or the effect is not enabled RecursiveRendering recursiveSettings = hdCamera.volumeStack.GetComponent <RecursiveRendering>(); if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) || !recursiveSettings.enable.value) { return(colorBuffer); } using (var builder = renderGraph.AddRenderPass <RecursiveRenderingPassData>("Recursive Rendering Evaluation", out var passData, ProfilingSampler.Get(HDProfileId.RayTracingRecursiveRendering))) { builder.EnableAsyncCompute(false); // Camera parameters passData.texWidth = hdCamera.actualWidth; passData.texHeight = hdCamera.actualHeight; passData.viewCount = hdCamera.viewCount; // Effect parameters passData.rayLength = recursiveSettings.rayLength.value; passData.maxDepth = recursiveSettings.maxDepth.value; passData.minSmoothness = recursiveSettings.minSmoothness.value; // Other data passData.accelerationStructure = RequestAccelerationStructure(); passData.lightCluster = RequestLightCluster(); passData.recursiveRenderingRT = HDRenderPipelineGlobalSettings.instance.renderPipelineRayTracingResources.forwardRaytracing; passData.skyTexture = m_SkyManager.GetSkyReflection(hdCamera); passData.shaderVariablesRayTracingCB = m_ShaderVariablesRayTracingCB; passData.ditheredTextureSet = GetBlueNoiseManager().DitheredTextureSet8SPP(); passData.depthStencilBuffer = builder.ReadTexture(depthPyramid); passData.flagMask = builder.ReadTexture(flagMask); passData.rayCountTexture = builder.ReadWriteTexture(rayCountTexture); passData.outputBuffer = builder.ReadWriteTexture(colorBuffer); // Right now the debug buffer is written to independently of what is happening. This must be changed // TODO RENDERGRAPH passData.debugBuffer = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R16G16B16A16_SFloat, enableRandomWrite = true, name = "Recursive Rendering Debug Texture" })); builder.SetRenderFunc( (RecursiveRenderingPassData data, RenderGraphContext ctx) => { // Define the shader pass to use for the reflection pass ctx.cmd.SetRayTracingShaderPass(data.recursiveRenderingRT, "ForwardDXR"); // Set the acceleration structure for the pass ctx.cmd.SetRayTracingAccelerationStructure(data.recursiveRenderingRT, HDShaderIDs._RaytracingAccelerationStructureName, data.accelerationStructure); // Inject the ray-tracing sampling data BlueNoise.BindDitheredTextureSet(ctx.cmd, data.ditheredTextureSet); // Update Global Constant Buffer. data.shaderVariablesRayTracingCB._RaytracingRayMaxLength = data.rayLength; data.shaderVariablesRayTracingCB._RaytracingMaxRecursion = data.maxDepth; data.shaderVariablesRayTracingCB._RaytracingReflectionMinSmoothness = data.minSmoothness; ConstantBuffer.PushGlobal(ctx.cmd, data.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Fecth the temporary buffers we shall be using ctx.cmd.SetRayTracingTextureParam(data.recursiveRenderingRT, HDShaderIDs._RaytracingFlagMask, data.flagMask); ctx.cmd.SetRayTracingTextureParam(data.recursiveRenderingRT, HDShaderIDs._DepthTexture, data.depthStencilBuffer); ctx.cmd.SetRayTracingTextureParam(data.recursiveRenderingRT, HDShaderIDs._CameraColorTextureRW, data.outputBuffer); // Set ray count texture ctx.cmd.SetRayTracingTextureParam(data.recursiveRenderingRT, HDShaderIDs._RayCountTexture, data.rayCountTexture); // LightLoop data data.lightCluster.BindLightClusterData(ctx.cmd); // Set the data for the ray miss ctx.cmd.SetRayTracingTextureParam(data.recursiveRenderingRT, HDShaderIDs._SkyTexture, data.skyTexture); // If this is the right debug mode and we have at least one light, write the first shadow to the de-noised texture ctx.cmd.SetRayTracingTextureParam(data.recursiveRenderingRT, HDShaderIDs._RaytracingPrimaryDebug, data.debugBuffer); // Run the computation ctx.cmd.DispatchRays(data.recursiveRenderingRT, m_RayGenShaderName, (uint)data.texWidth, (uint)data.texHeight, (uint)data.viewCount); }); PushFullScreenDebugTexture(m_RenderGraph, passData.debugBuffer, FullScreenDebugMode.RecursiveRayTracing); return(passData.outputBuffer); } }
internal HDShadowAtlasInitParameters(HDRenderPipelineRuntimeResources renderPipelineResources, RenderGraph renderGraph, bool useSharedTexture, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, HDShadowInitParameters initParams, ConstantBuffer <ShaderVariablesGlobal> cb) { this.renderPipelineResources = renderPipelineResources; this.renderGraph = renderGraph; this.useSharedTexture = useSharedTexture; this.width = width; this.height = height; this.atlasShaderID = atlasShaderID; this.clearMaterial = clearMaterial; this.maxShadowRequests = maxShadowRequests; this.initParams = initParams; this.blurAlgorithm = BlurAlgorithm.None; this.filterMode = FilterMode.Bilinear; this.depthBufferBits = DepthBits.Depth16; this.format = RenderTextureFormat.Shadowmap; this.name = ""; this.cb = cb; }
public unsafe void SetConstants(DeviceContext deviceContext, RoomAliveToolkit.Kinect2Calibration kinect2Calibration, SharpDX.Matrix projection) { // hlsl matrices are default column order var constants = new ConstantBuffer(); for (int i = 0, col = 0; col < 4; col++) for (int row = 0; row < 4; row++) { constants.projection[i] = projection[row, col]; constants.depthToColorTransform[i] = (float)kinect2Calibration.depthToColorTransform[row, col]; i++; } constants.f[0] = (float)kinect2Calibration.colorCameraMatrix[0, 0]; constants.f[1] = (float)kinect2Calibration.colorCameraMatrix[1, 1]; constants.c[0] = (float)kinect2Calibration.colorCameraMatrix[0, 2]; constants.c[1] = (float)kinect2Calibration.colorCameraMatrix[1, 2]; constants.k1 = (float)kinect2Calibration.colorLensDistortion[0]; constants.k2 = (float)kinect2Calibration.colorLensDistortion[1]; DataStream dataStream; deviceContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out dataStream); dataStream.Write<ConstantBuffer>(constants); deviceContext.UnmapSubresource(constantBuffer, 0); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Initialize the device m_device.Init( panelOutput1.Handle, false, true ); // Build cube primitive { float3 colorXp = new float3( 1, 0, 0 ); float3 colorXn = new float3( 1, 1, 0 ); float3 colorYp = new float3( 0, 1, 0 ); float3 colorYn = new float3( 0, 1, 1 ); float3 colorZp = new float3( 0, 0, 1 ); float3 colorZn = new float3( 1, 0, 1 ); VertexP3N3G3T2[] vertices = new VertexP3N3G3T2[6*4] { // +X new VertexP3N3G3T2() { P = new float3( 1, 1, 1 ), N = new float3( 1, 0, 0 ), T = colorXp, UV = new float2( 0, 0 ) }, new VertexP3N3G3T2() { P = new float3( 1, -1, 1 ), N = new float3( 1, 0, 0 ), T = colorXp, UV = new float2( 0, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, -1, -1 ), N = new float3( 1, 0, 0 ), T = colorXp, UV = new float2( 1, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, 1, -1 ), N = new float3( 1, 0, 0 ), T = colorXp, UV = new float2( 1, 0 ) }, // -X new VertexP3N3G3T2() { P = new float3( -1, 1, -1 ), N = new float3( -1, 0, 0 ), T = colorXn, UV = new float2( 0, 0 ) }, new VertexP3N3G3T2() { P = new float3( -1, -1, -1 ), N = new float3( -1, 0, 0 ), T = colorXn, UV = new float2( 0, 1 ) }, new VertexP3N3G3T2() { P = new float3( -1, -1, 1 ), N = new float3( -1, 0, 0 ), T = colorXn, UV = new float2( 1, 1 ) }, new VertexP3N3G3T2() { P = new float3( -1, 1, 1 ), N = new float3( -1, 0, 0 ), T = colorXn, UV = new float2( 1, 0 ) }, // +Y new VertexP3N3G3T2() { P = new float3( -1, 1, -1 ), N = new float3( 0, 1, 0 ), T = colorYp, UV = new float2( 0, 0 ) }, new VertexP3N3G3T2() { P = new float3( -1, 1, 1 ), N = new float3( 0, 1, 0 ), T = colorYp, UV = new float2( 0, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, 1, 1 ), N = new float3( 0, 1, 0 ), T = colorYp, UV = new float2( 1, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, 1, -1 ), N = new float3( 0, 1, 0 ), T = colorYp, UV = new float2( 1, 0 ) }, // -Y new VertexP3N3G3T2() { P = new float3( -1, -1, 1 ), N = new float3( 0, -1, 0 ), T = colorYn, UV = new float2( 0, 0 ) }, new VertexP3N3G3T2() { P = new float3( -1, -1, -1 ), N = new float3( 0, -1, 0 ), T = colorYn, UV = new float2( 0, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, -1, -1 ), N = new float3( 0, -1, 0 ), T = colorYn, UV = new float2( 1, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, -1, 1 ), N = new float3( 0, -1, 0 ), T = colorYn, UV = new float2( 1, 0 ) }, // +Z new VertexP3N3G3T2() { P = new float3( -1, 1, 1 ), N = new float3( 0, 0, 1 ), T = colorZp, UV = new float2( 0, 0 ) }, new VertexP3N3G3T2() { P = new float3( -1, -1, 1 ), N = new float3( 0, 0, 1 ), T = colorZp, UV = new float2( 0, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, -1, 1 ), N = new float3( 0, 0, 1 ), T = colorZp, UV = new float2( 1, 1 ) }, new VertexP3N3G3T2() { P = new float3( 1, 1, 1 ), N = new float3( 0, 0, 1 ), T = colorZp, UV = new float2( 1, 0 ) }, // -Z new VertexP3N3G3T2() { P = new float3( 1, 1, -1 ), N = new float3( 0, 0, -1 ), T = colorZn, UV = new float2( 0, 0 ) }, new VertexP3N3G3T2() { P = new float3( 1, -1, -1 ), N = new float3( 0, 0, -1 ), T = colorZn, UV = new float2( 0, 1 ) }, new VertexP3N3G3T2() { P = new float3( -1, -1, -1 ), N = new float3( 0, 0, -1 ), T = colorZn, UV = new float2( 1, 1 ) }, new VertexP3N3G3T2() { P = new float3( -1, 1, -1 ), N = new float3( 0, 0, -1 ), T = colorZn, UV = new float2( 1, 0 ) }, }; uint[] indices = new uint[3*2*6] { 4*0+0, 4*0+1, 4*0+2, 4*0+0, 4*0+2, 4*0+3, 4*1+0, 4*1+1, 4*1+2, 4*1+0, 4*1+2, 4*1+3, 4*2+0, 4*2+1, 4*2+2, 4*2+0, 4*2+2, 4*2+3, 4*3+0, 4*3+1, 4*3+2, 4*3+0, 4*3+2, 4*3+3, 4*4+0, 4*4+1, 4*4+2, 4*4+0, 4*4+2, 4*4+3, 4*5+0, 4*5+1, 4*5+2, 4*5+0, 4*5+2, 4*5+3, }; m_prim_cube = new Primitive( m_device, 6*4, VertexP3N3G3T2.FromArray( vertices ), indices, Primitive.TOPOLOGY.TRIANGLE_LIST, VERTEX_FORMAT.P3N3G3T2 ); } // Build the shader to render the cube m_shader_renderCube = new Shader( m_device, new ShaderFile( new System.IO.FileInfo( @".\Shaders\RenderCube.hlsl" ) ), VERTEX_FORMAT.P3N3G3T2, "VS", null, "PS", null ); // Build constant buffer to provide camera transform m_CB_Camera = new ConstantBuffer<CBCamera>( m_device, 0 ); Application.Idle += Application_Idle; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect Simple point cloud view sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); VertexShader vertexShader = ShaderCompiler.CompileFromFile <VertexShader>(device, "PointCloudView.fx", "VS"); PixelShader pixelShader = ShaderCompiler.CompileFromFile <PixelShader>(device, "PointCloudView.fx", "PS"); DX11NullInstancedDrawer nulldrawer = new DX11NullInstancedDrawer(); nulldrawer.VertexCount = Consts.DepthWidth; nulldrawer.InstanceCount = Consts.DepthHeight; DX11NullGeometry nullGeom = new DX11NullGeometry(device, nulldrawer); nullGeom.Topology = SharpDX.Direct3D.PrimitiveTopology.PointList; KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); cbCamera camera = new cbCamera(); camera.Projection = Matrix.PerspectiveFovLH(1.57f * 0.5f, 1.3f, 0.01f, 100.0f); camera.View = Matrix.Translation(0.0f, 0.0f, 2.0f); camera.Projection.Transpose(); camera.View.Transpose(); ConstantBuffer <cbCamera> cameraBuffer = new ConstantBuffer <cbCamera>(device); cameraBuffer.Update(context, ref camera); bool doQuit = false; bool doUpload = false; CameraRGBFrameData rgbFrame = new CameraRGBFrameData(); DynamicCameraRGBTexture cameraTexture = new DynamicCameraRGBTexture(device); KinectSensorDepthFrameProvider provider = new KinectSensorDepthFrameProvider(sensor); provider.FrameReceived += (sender, args) => { rgbFrame.Update(sensor.CoordinateMapper, args.DepthData); doUpload = true; }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } if (doUpload) { cameraTexture.Copy(context.Context, rgbFrame); } context.RenderTargetStack.Push(swapChain); context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black); context.Context.VertexShader.Set(vertexShader); context.Context.PixelShader.Set(pixelShader); context.Context.VertexShader.SetShaderResource(0, cameraTexture.ShaderView); context.Context.VertexShader.SetConstantBuffer(0, cameraBuffer.Buffer); nullGeom.Bind(context, null); nullGeom.Draw(context); context.RenderTargetStack.Pop(); swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); cameraBuffer.Dispose(); cameraTexture.Dispose(); provider.Dispose(); pixelShader.Dispose(); vertexShader.Dispose(); sensor.Close(); }
/// <summary> /// /// </summary> public override void Initialize() { base.Initialize(); lightingCB = new ConstantBuffer( Game.GraphicsDevice, typeof(LightingParams) ); omniLightBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(OmniLightGPU), MaxOmniLights, StructuredBufferFlags.None ); spotLightBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(SpotLightGPU), MaxSpotLights, StructuredBufferFlags.None ); CreateShadowMaps(); CreateGBuffer(); Game.GraphicsDevice.DisplayBoundsChanged += (s,e) => CreateGBuffer(); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
internal Terrain(MapFile mapFile, AssetLoadContext loadContext) { Map = mapFile; HeightMap = new HeightMap(mapFile.HeightMapData); _graphicsDevice = loadContext.GraphicsDevice; _indexBufferCache = AddDisposable(new TerrainPatchIndexBufferCache(loadContext.GraphicsDevice)); var tileDataTexture = AddDisposable(CreateTileDataTexture( loadContext.GraphicsDevice, mapFile, HeightMap)); var cliffDetailsBuffer = AddDisposable(CreateCliffDetails( loadContext.GraphicsDevice, mapFile)); CreateTextures( loadContext, mapFile.BlendTileData, out var textureArray, out var textureDetails); var textureDetailsBuffer = AddDisposable(loadContext.GraphicsDevice.CreateStaticStructuredBuffer(textureDetails)); var terrainPipeline = loadContext.ShaderResources.Terrain.Pipeline; _materialConstantsBuffer = AddDisposable( new ConstantBuffer <TerrainShaderResources.TerrainMaterialConstants>( loadContext.GraphicsDevice, "TerrainMaterialConstants")); _materialConstantsBuffer.Value = new TerrainShaderResources.TerrainMaterialConstants { MapBorderWidth = new Vector2(mapFile.HeightMapData.BorderWidth, mapFile.HeightMapData.BorderWidth) * HeightMap.HorizontalScale, MapSize = new Vector2(mapFile.HeightMapData.Width, mapFile.HeightMapData.Height) * HeightMap.HorizontalScale, IsMacroTextureStretched = mapFile.EnvironmentData?.IsMacroTextureStretched ?? false }; _materialConstantsBuffer.Update(loadContext.GraphicsDevice); var macroTexture = loadContext.AssetStore.Textures.GetByName(mapFile.EnvironmentData?.MacroTexture ?? "tsnoiseurb.dds"); RadiusCursorDecals = AddDisposable(new RadiusCursorDecals(loadContext.AssetStore, loadContext.GraphicsDevice)); var casuticsTextures = BuildCausticsTextureArray(loadContext.AssetStore); _materialResourceSet = AddDisposable(loadContext.ShaderResources.Terrain.CreateMaterialResourceSet( _materialConstantsBuffer.Buffer, tileDataTexture, cliffDetailsBuffer ?? loadContext.StandardGraphicsResources.GetNullStructuredBuffer(TerrainShaderResources.CliffInfo.Size), textureDetailsBuffer, textureArray, macroTexture, casuticsTextures)); RadiusCursorDecalsResourceSet = AddDisposable(loadContext.ShaderResources.RadiusCursor.CreateRadiusCursorDecalsResourceSet( RadiusCursorDecals.TextureArray, RadiusCursorDecals.DecalConstants, RadiusCursorDecals.DecalsBuffer)); var cloudTexture = loadContext.AssetStore.Textures.GetByName(mapFile.EnvironmentData?.CloudTexture ?? "tscloudmed.dds"); var cloudResourceLayout = AddDisposable(loadContext.GraphicsDevice.ResourceFactory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("Global_CloudTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment)))); CloudResourceSet = AddDisposable(loadContext.GraphicsDevice.ResourceFactory.CreateResourceSet( new ResourceSetDescription( cloudResourceLayout, cloudTexture.Texture))); CloudResourceSet.Name = "Cloud resource set"; _shaderSet = loadContext.ShaderResources.Terrain.ShaderSet; _pipeline = terrainPipeline; OnHeightMapChanged(); }
/// <summary> /// Load stuff here /// </summary> protected override void Initialize() { var device = GraphicsDevice; base.Initialize(); vb = new VertexBuffer(device, typeof(Vertex), 6 ); cb = new ConstantBuffer(GraphicsDevice, typeof(ConstData) ); instDataGpu = new StructuredBuffer( device, typeof(InstData), InstanceCount, StructuredBufferFlags.None ); instDataCpu = new InstData[ InstanceCount ]; var rand = new Random(); for (int i=0; i<InstanceCount; i++) { instDataCpu[ i ].Offset = rand.NextVector2( new Vector2(-2.5f,-2f), new Vector2( 2.5f,2f) ); instDataCpu[ i ].Scale = rand.NextFloat( 0, 0.7f); instDataCpu[ i ].Rotation = rand.NextFloat( 0, MathUtil.TwoPi ); instDataCpu[ i ].Color = rand.NextVector4( Vector4.Zero, Vector4.One * 0.7f ); instDataCpu[ i ].TexId = rand.Next(4); } Reloading += InstancingDemo_Reloading; InstancingDemo_Reloading ( this, EventArgs.Empty ); }
void RenderSubsurfaceScattering(HDCamera hdCamera, CommandBuffer cmd, RTHandle colorBufferRT, RTHandle diffuseBufferRT, RTHandle depthStencilBufferRT, RTHandle depthTextureRT) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.SubsurfaceScattering)) { return; } BuildCoarseStencilAndResolveIfNeeded(hdCamera, cmd); var settings = hdCamera.volumeStack.GetComponent <SubSurfaceScattering>(); // If ray tracing is enabled for the camera, if the volume override is active and if the RAS is built, we want to do ray traced SSS if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing) && settings.rayTracing.value && GetRayTracingState()) { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering))) { // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesXHR = (hdCamera.actualWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (hdCamera.actualHeight + (areaTileSize - 1)) / areaTileSize; // Fetch the volume overrides that we shall be using RayTracingShader subSurfaceShader = m_Asset.renderPipelineRayTracingResources.subSurfaceRayTracing; ComputeShader deferredRayTracing = m_Asset.renderPipelineRayTracingResources.deferredRaytracingCS; // Fetch all the intermediate buffers that we need RTHandle intermediateBuffer0 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA0); RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1); RTHandle intermediateBuffer2 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA2); RTHandle intermediateBuffer3 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA3); RTHandle intermediateBuffer4 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA4); RTHandle directionBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.Direction); // Clear the integration texture first cmd.SetComputeTextureParam(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, HDShaderIDs._RaytracedShadowIntegration, intermediateBuffer4); cmd.DispatchCompute(m_ScreenSpaceShadowsCS, m_ClearShadowTexture, numTilesXHR, numTilesYHR, hdCamera.viewCount); // Grab the acceleration structure for the target camera RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure(); // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(subSurfaceShader, "SubSurfaceDXR"); // Set the acceleration structure for the pass cmd.SetRayTracingAccelerationStructure(subSurfaceShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray-tracing sampling data BlueNoise blueNoise = GetBlueNoiseManager(); blueNoise.BindDitheredRNGData8SPP(cmd); // For every sample that we need to process for (int sampleIndex = 0; sampleIndex < settings.sampleCount.value; ++sampleIndex) { // Inject the ray generation data m_ShaderVariablesRayTracingCB._RaytracingNumSamples = settings.sampleCount.value; m_ShaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIndex; ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the textures for ray generation cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._NormalBufferTexture, sharedRTManager.GetNormalBuffer()); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._SSSBufferTexture, m_SSSColor); cmd.SetGlobalTexture(HDShaderIDs._StencilTexture, sharedRTManager.GetDepthStencilBuffer(), RenderTextureSubElement.Stencil); // Set the output textures cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._ThroughputTextureRW, intermediateBuffer0); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._NormalTextureRW, intermediateBuffer1); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._PositionTextureRW, intermediateBuffer2); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DiffuseLightingTextureRW, intermediateBuffer3); cmd.SetRayTracingTextureParam(subSurfaceShader, HDShaderIDs._DirectionTextureRW, directionBuffer); // Run the computation cmd.DispatchRays(subSurfaceShader, m_RayGenSubSurfaceShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, (uint)hdCamera.viewCount); // Now let's do the deferred shading pass on the samples // TODO: Do this only once in the init pass int currentKernel = deferredRayTracing.FindKernel("RaytracingDiffuseDeferred"); // Bind the lightLoop data HDRaytracingLightCluster lightCluster = RequestLightCluster(); lightCluster.BindLightClusterData(cmd); // Bind the input textures cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DepthTexture, sharedRTManager.GetDepthStencilBuffer()); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._ThroughputTextureRW, intermediateBuffer0); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._NormalTextureRW, intermediateBuffer1); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._PositionTextureRW, intermediateBuffer2); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DirectionTextureRW, directionBuffer); cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._DiffuseLightingTextureRW, intermediateBuffer3); // Bind the output texture (it is used for accumulation read and write) cmd.SetComputeTextureParam(deferredRayTracing, currentKernel, HDShaderIDs._RaytracingLitBufferRW, intermediateBuffer4); // Compute the Lighting cmd.DispatchCompute(deferredRayTracing, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); } // Grab the history buffer RTHandle subsurfaceHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RayTracedSubSurface, SubSurfaceHistoryBufferAllocatorFunction, 1); // Check if we need to invalidate the history float historyValidity = 1.0f; #if UNITY_HDRP_DXR_TESTS_DEFINE if (Application.isPlaying) { historyValidity = 0.0f; } else #endif // We need to check if something invalidated the history buffers historyValidity *= ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; // Apply temporal filtering to the buffer HDTemporalFilter temporalFilter = GetTemporalFilter(); temporalFilter.DenoiseBuffer(cmd, hdCamera, intermediateBuffer4, subsurfaceHistory, intermediateBuffer0, singleChannel: false, historyValidity: historyValidity); // Now based on the mask, we need to blend the subsurface and the diffuse lighting ComputeShader rayTracingSubSurfaceCS = m_Asset.renderPipelineRayTracingResources.subSurfaceRayTracingCS; int m_CombineSubSurfaceKernel = rayTracingSubSurfaceCS.FindKernel("BlendSubSurfaceData"); cmd.SetComputeTextureParam(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, HDShaderIDs._SubSurfaceLightingBuffer, intermediateBuffer0); cmd.SetComputeTextureParam(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, HDShaderIDs._DiffuseLightingTextureRW, diffuseBufferRT); cmd.SetComputeTextureParam(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, HDShaderIDs._SSSBufferTexture, m_SSSColor); cmd.DispatchCompute(rayTracingSubSurfaceCS, m_CombineSubSurfaceKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); // Push this version of the texture for debug PushFullScreenDebugTexture(hdCamera, cmd, diffuseBufferRT, FullScreenDebugMode.RayTracedSubSurface); // Combine it with the rest of the lighting m_CombineLightingPass.SetTexture(HDShaderIDs._IrradianceSource, diffuseBufferRT); HDUtils.DrawFullScreen(cmd, m_CombineLightingPass, colorBufferRT, depthStencilBufferRT, shaderPassId: 1); } } else { using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.SubsurfaceScattering))) { var parameters = PrepareSubsurfaceScatteringParameters(hdCamera); var resources = new SubsurfaceScatteringResources(); resources.colorBuffer = colorBufferRT; resources.diffuseBuffer = diffuseBufferRT; resources.depthStencilBuffer = depthStencilBufferRT; resources.depthTexture = depthTextureRT; resources.cameraFilteringBuffer = m_SSSCameraFilteringBuffer; resources.coarseStencilBuffer = parameters.coarseStencilBuffer; resources.sssBuffer = m_SSSColor; // For Jimenez we always need an extra buffer, for Disney it depends on platform if (parameters.needTemporaryBuffer) { // Clear the SSS filtering target using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.ClearSSSFilteringTarget))) { CoreUtils.SetRenderTarget(cmd, m_SSSCameraFilteringBuffer, ClearFlag.Color, Color.clear); } } RenderSubsurfaceScattering(parameters, resources, cmd); } } }
protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); try { m_Device.Init( panelOutput.Handle, false, true ); } catch ( Exception _e ) { m_Device = null; MessageBox( "Failed to initialize DX device!\n\n" + _e.Message, MessageBoxButtons.OK, MessageBoxIcon.Error ); return; } m_CB_Main = new ConstantBuffer<CB_Main>( m_Device, 0 ); m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 1 ); m_CB_AutoExposure = new ConstantBuffer<CB_AutoExposure>( m_Device, 10 ); m_CB_ToneMapping = new ConstantBuffer<CB_ToneMapping>( m_Device, 10 ); try { #if DEBUG m_Shader_RenderHDR = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/RenderCubeMap.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ); m_Shader_ComputeTallHistogram = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/AutoExposure/ComputeTallHistogram.hlsl" ) ), "CS", null ); m_Shader_FinalizeHistogram = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/AutoExposure/FinalizeHistogram.hlsl" ) ), "CS", null ); m_Shader_ComputeAutoExposure = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/AutoExposure/ComputeAutoExposure.hlsl" ) ), "CS", null ); m_Shader_ToneMapping = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/ToneMapping.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ); #else m_Shader_RenderHDR = Shader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/RenderCubeMap.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS" ); m_Shader_ComputeTallHistogram = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/AutoExposure/ComputeTallHistogram.hlsl" ), "CS" ); m_Shader_FinalizeHistogram = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/AutoExposure/FinalizeHistogram.hlsl" ), "CS" ); m_Shader_ComputeAutoExposure = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/AutoExposure/ComputeAutoExposure.hlsl" ), "CS" ); m_Shader_ToneMapping = Shader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/ToneMapping.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS" ); #endif } catch ( Exception _e ) { MessageBox( "Shader failed to compile!\n\n" + _e.Message, MessageBoxButtons.OK, MessageBoxIcon.Error ); m_Shader_RenderHDR = null; m_Shader_ComputeTallHistogram = null; m_Shader_FinalizeHistogram = null; m_Shader_ComputeAutoExposure = null; m_Shader_ToneMapping = null; } // Create the HDR buffer m_Tex_HDR = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 1, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, null ); // Create the histogram & auto-exposure buffers int tallHistogramHeight = (panelOutput.Height + 3) >> 2; m_Tex_TallHistogram = new Texture2D( m_Device, 128, tallHistogramHeight, 1, 1, PIXEL_FORMAT.R32_UINT, false, true, null ); m_Tex_Histogram = new Texture2D( m_Device, 128, 1, 1, 1, PIXEL_FORMAT.R32_UINT, false, true, null ); m_Buffer_AutoExposureSource = new StructuredBuffer<autoExposure_t>( m_Device, 1, true ); m_Buffer_AutoExposureSource.m[0].EngineLuminanceFactor = 1.0f; m_Buffer_AutoExposureSource.m[0].TargetLuminance = 1.0f; m_Buffer_AutoExposureSource.m[0].MinLuminanceLDR = 0.0f; m_Buffer_AutoExposureSource.m[0].MaxLuminanceLDR = 1.0f; m_Buffer_AutoExposureSource.m[0].MiddleGreyLuminanceLDR = 1.0f; m_Buffer_AutoExposureSource.m[0].EV = 0.0f; m_Buffer_AutoExposureSource.m[0].Fstop = 0.0f; m_Buffer_AutoExposureSource.m[0].PeakHistogramValue = 0; m_Buffer_AutoExposureSource.Write(); m_Buffer_AutoExposureTarget = new StructuredBuffer<autoExposure_t>( m_Device, 1, true ); // Load cube map try { m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( "garage4_hd.dds" ) ); // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\hdrcube6.dds" ) ); // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_28_cube_BC6H_UF16.bimage" ) ); // Tunnel // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_89_cube_BC6H_UF16.bimage" ) ); // Large sky // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_115_cube_BC6H_UF16.bimage" ) ); // Indoor // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_123_cube_BC6H_UF16.bimage" ) ); // Under the arch // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_189_cube_BC6H_UF16.bimage" ) ); // Indoor viewing out (vista) // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_246_cube_BC6H_UF16.bimage" ) ); // Nice! Statue's feet // m_Tex_CubeMap = LoadCubeMap( new System.IO.FileInfo( @"..\..\..\Arkane\CubeMaps\dust_return\pr_obe_248_cube_BC6H_UF16.bimage" ) ); // Nice! In a corner with lot of sky } catch ( Exception ) { } // Setup camera m_Camera.CreatePerspectiveCamera( (float) (90.0 * Math.PI / 180.0), (float) panelOutput.Width / panelOutput.Height, 0.01f, 100.0f ); m_Manipulator.Attach( panelOutput, m_Camera ); m_Manipulator.InitializeCamera( new float3( 0, 0, 1 ), new float3( 0, 0, 0 ), float3.UnitY ); }
/// <summary> /// Updates shader variables in ShaderVariablesGlobal CBuffer with given camera properties. /// </summary> /// <param name="cmd">CommandBuffer used for queueing commands.</param> /// <param name="camera">Camera from which values will be taken.</param> public void UpdateShaderVariablesForCamera(CommandBuffer cmd, HDCamera camera) { camera.UpdateShaderVariablesGlobalCB(ref m_ShaderVariablesGlobalCB); ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesGlobalCB, HDShaderIDs._ShaderVariablesGlobal); }
private void Run() { var window = new TesselationParameterForm(); window.Show(); var deviceManager = new DeviceManager(); deviceManager.Initialize(deviceCreationFlags: DeviceCreationFlags.Debug); var settings = new RenderFormSettings(800, 600, false, false, "hello!", WindowAssociationFlags.IgnoreAll); var renderWindow = new PresentationWindow(settings); renderWindow.SwapChain = deviceManager.CreateSwapChainForWindow(renderWindow.Handle, settings); var rtCreationSettings = new RenderTarget.Configuration.CreationSettings( new Size(settings.Width, settings.Height), true, new SampleDescription(1, 0), RenderTarget.Configuration.RenderTargetClearSettings.Default, RenderTarget.Configuration.DepthStencilClearSettings.Default); var renderTarget = deviceManager.RenderTargetManager.CreateRenderTargetFromSwapChain(renderWindow.SwapChain, rtCreationSettings); var context = deviceManager.Context; context.Rasterizer.SetViewports(new Viewport(0, 0, settings.Width, settings.Height, 0.0f, 1.0f)); var vertexData = new[] { new VertexPosition {Position = new Vector3(0.0f, 0.5f, 0.5f)}, new VertexPosition {Position = new Vector3(0.5f, -0.5f, 0.5f)}, new VertexPosition {Position = new Vector3(-0.5f, -0.5f, 0.5f)}, }; var stride = Marshal.SizeOf(typeof (VertexPosition)); var vertexBufferDesc = new BufferDescription( stride*vertexData.Length, ResourceUsage.Immutable, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, stride); var vertexBuffer = Buffer.Create(deviceManager.Device, vertexData, vertexBufferDesc); var binding = new VertexBufferBinding(vertexBuffer, stride, 0); var inputLayout = new InputLayoutCache(deviceManager.Device).GetLayout<VertexPosition>(); var fileName = "../../Shaders/triangle.fx"; var hullShader = new HullShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.HullShader, fileName, "HS")); var domainerShader = new DomainShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.DomainShader, fileName, "DS")); var vertexShader = new VertexShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.VertexShader, fileName, "VS")); var pixelShader = new PixelShader(deviceManager.Device, deviceManager.ShaderCompiler.LoadByteCodeFromFile(ShaderCompiler.ShaderType.PixelShader, fileName, "PS")); Console.Out.WriteLine(""); var rasterizerState = new RasterizerState(deviceManager.Device, new RasterizerStateDescription { CullMode = CullMode.None, FillMode = FillMode.Wireframe, IsDepthClipEnabled = false, IsFrontCounterClockwise = false, IsScissorEnabled = false }); var constantBuffer = new ConstantBuffer<TessellationParameters>(deviceManager.Device); var parameters = new TessellationParameters { TessellationFactor = 5 }; RenderLoop.Run(renderWindow, () => { renderTarget.SetActive(context); renderTarget.Clear(context); context.InputAssembler.SetVertexBuffers(0, binding); context.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith3ControlPoints; context.InputAssembler.InputLayout = inputLayout; context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); context.HullShader.Set(hullShader); context.DomainShader.Set(domainerShader); parameters.TessellationFactor = window.TesselationFactor; constantBuffer.UpdateValue(parameters); context.HullShader.SetConstantBuffer(0, constantBuffer.Buffer); //context.OutputMerger.DepthStencilState = null; context.Rasterizer.State = rasterizerState; context.Draw(3, 0); renderWindow.Present(); }); deviceManager.Dispose(); }
static void ExecuteSSSAreaRayTrace(CommandBuffer cmd, RTSAreaRayTraceParameters parameters, RTSAreaRayTraceResources sssartResources) { // Inject the ray-tracing sampling data BlueNoise.BindDitheredTextureSet(cmd, parameters.ditheredTextureSet); // Evaluate the dispatch parameters int areaTileSize = 8; int numTilesX = (parameters.texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesY = (parameters.texHeight + (areaTileSize - 1)) / areaTileSize; // We have noticed from extensive profiling that ray-trace shaders are not as effective for running per-pixel computation. In order to reduce that, // we do a first prepass that compute the analytic term and probability and generates the first integration sample // Bind the light data cmd.SetComputeMatrixParam(parameters.screenSpaceShadowsCS, HDShaderIDs._RaytracingAreaWorldToLocal, parameters.worldToLocalMatrix); cmd.SetComputeIntParam(parameters.screenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, parameters.lightIndex); parameters.shaderVariablesRayTracingCB._RaytracingNumSamples = parameters.numSamples; ConstantBuffer.PushGlobal(cmd, parameters.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the input buffers cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._GBufferTexture[0], sssartResources.gbuffer0); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._GBufferTexture[1], sssartResources.gbuffer1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._GBufferTexture[2], sssartResources.gbuffer2); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._GBufferTexture[3], sssartResources.gbuffer3); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._StencilTexture, sssartResources.depthStencilBuffer, 0, RenderTextureSubElement.Stencil); // Bind the output buffers cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._RaytracedAreaShadowIntegration, sssartResources.outputShadowTexture); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._RaytracedAreaShadowSample, sssartResources.intermediateBufferRGBA1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._RaytracingDirectionBuffer, sssartResources.directionBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._RayTracingLengthBuffer, sssartResources.rayLengthBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.DispatchCompute(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowPrepassKernel, numTilesX, numTilesY, parameters.viewCount); // Set ray count texture cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RayCountTexture, sssartResources.rayCountTexture); // Set the acceleration structure for the pass cmd.SetRayTracingAccelerationStructure(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracingAccelerationStructureName, parameters.accelerationStructure); // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(parameters.screenSpaceShadowsRT, "VisibilityDXR"); // Input data cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracedAreaShadowSample, sssartResources.intermediateBufferRGBA1); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracingDirectionBuffer, sssartResources.directionBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RayTracingLengthBuffer, sssartResources.rayLengthBuffer); cmd.SetRayTracingIntParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracingTargetAreaLight, parameters.lightIndex); // Output data cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracedAreaShadowIntegration, sssartResources.outputShadowTexture); // Evaluate the intersection cmd.DispatchRays(parameters.screenSpaceShadowsRT, m_RayGenAreaShadowSingleName, (uint)parameters.texWidth, (uint)parameters.texHeight, (uint)parameters.viewCount); // Let's do the following samples (if any) for (int sampleIndex = 1; sampleIndex < parameters.numSamples; ++sampleIndex) { // Update global Constant Buffer parameters.shaderVariablesRayTracingCB._RaytracingNumSamples = parameters.numSamples; parameters.shaderVariablesRayTracingCB._RaytracingSampleIndex = sampleIndex; ConstantBuffer.PushGlobal(cmd, parameters.shaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Bind the light data cmd.SetComputeIntParam(parameters.screenSpaceShadowsCS, HDShaderIDs._RaytracingTargetAreaLight, parameters.lightIndex); cmd.SetComputeMatrixParam(parameters.screenSpaceShadowsCS, HDShaderIDs._RaytracingAreaWorldToLocal, parameters.worldToLocalMatrix); // Input Buffers cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._GBufferTexture[0], sssartResources.gbuffer0); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._GBufferTexture[1], sssartResources.gbuffer1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._GBufferTexture[2], sssartResources.gbuffer2); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._GBufferTexture[3], sssartResources.gbuffer3); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._StencilTexture, sssartResources.depthStencilBuffer, 0, RenderTextureSubElement.Stencil); // Output buffers cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._RaytracedAreaShadowSample, sssartResources.intermediateBufferRGBA1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._RaytracingDirectionBuffer, sssartResources.directionBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._RayTracingLengthBuffer, sssartResources.rayLengthBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.DispatchCompute(parameters.screenSpaceShadowsCS, parameters.areaRaytracingShadowNewSampleKernel, numTilesX, numTilesY, parameters.viewCount); // Input buffers cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracedAreaShadowSample, sssartResources.intermediateBufferRGBA1); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracingDirectionBuffer, sssartResources.directionBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RayTracingLengthBuffer, sssartResources.rayLengthBuffer); cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.SetRayTracingIntParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracingTargetAreaLight, parameters.lightIndex); // Output buffers cmd.SetRayTracingTextureParam(parameters.screenSpaceShadowsRT, HDShaderIDs._RaytracedAreaShadowIntegration, sssartResources.outputShadowTexture); // Evaluate the intersection cmd.DispatchRays(parameters.screenSpaceShadowsRT, m_RayGenAreaShadowSingleName, (uint)parameters.texWidth, (uint)parameters.texHeight, (uint)parameters.viewCount); } if (parameters.filterTracedShadow) { Vector4 shadowChannelMask0 = new Vector4(); Vector4 shadowChannelMask1 = new Vector4(); Vector4 shadowChannelMask2 = new Vector4(); GetShadowChannelMask(parameters.areaShadowSlot, ScreenSpaceShadowType.Area, ref shadowChannelMask0); GetShadowChannelMask(parameters.areaShadowSlot, ScreenSpaceShadowType.GrayScale, ref shadowChannelMask1); GetShadowChannelMask(parameters.areaShadowSlot + 1, ScreenSpaceShadowType.GrayScale, ref shadowChannelMask2); // Global parameters cmd.SetComputeIntParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._RaytracingDenoiseRadius, parameters.filterSize); cmd.SetComputeIntParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._DenoisingHistorySlice, parameters.areaShadowSlot / 4); cmd.SetComputeVectorParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._DenoisingHistoryMask, shadowChannelMask0); cmd.SetComputeVectorParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._DenoisingHistoryMaskSn, shadowChannelMask1); cmd.SetComputeVectorParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._DenoisingHistoryMaskUn, shadowChannelMask2); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._CameraMotionVectorsTexture, sssartResources.motionVectorsBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._AreaShadowHistory, sssartResources.shadowHistoryArray); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._AnalyticHistoryBuffer, sssartResources.analyticHistoryArray); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._DenoiseInputTexture, sssartResources.outputShadowTexture); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, HDShaderIDs._DenoiseOutputTextureRW, sssartResources.intermediateBufferRGBA1); cmd.SetComputeFloatParam(parameters.screenSpaceShadowsFilterCS, HDShaderIDs._HistoryValidity, parameters.historyValidity); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowApplyTAAKernel, numTilesX, numTilesY, parameters.viewCount); // Update the shadow history buffer cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateAnalyticHistoryKernel, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateAnalyticHistoryKernel, HDShaderIDs._AnalyticHistoryBuffer, sssartResources.analyticHistoryArray); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateAnalyticHistoryKernel, numTilesX, numTilesY, parameters.viewCount); // Update the analytic history buffer cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateShadowHistoryKernel, HDShaderIDs._DenoiseInputTexture, sssartResources.intermediateBufferRGBA1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateShadowHistoryKernel, HDShaderIDs._AreaShadowHistoryRW, sssartResources.shadowHistoryArray); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaUpdateShadowHistoryKernel, numTilesX, numTilesY, parameters.viewCount); // Inject parameters for noise estimation cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaEstimateNoiseKernel, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaEstimateNoiseKernel, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaEstimateNoiseKernel, HDShaderIDs._ScramblingTexture, parameters.scramblingTex); // Noise estimation pre-pass cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaEstimateNoiseKernel, HDShaderIDs._DenoiseInputTexture, sssartResources.intermediateBufferRGBA1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaEstimateNoiseKernel, HDShaderIDs._DenoiseOutputTextureRW, sssartResources.outputShadowTexture); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaEstimateNoiseKernel, numTilesX, numTilesY, parameters.viewCount); // Reinject parameters for denoising cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaFirstDenoiseKernel, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaFirstDenoiseKernel, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); // First denoising pass cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaFirstDenoiseKernel, HDShaderIDs._DenoiseInputTexture, sssartResources.outputShadowTexture); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaFirstDenoiseKernel, HDShaderIDs._DenoiseOutputTextureRW, sssartResources.intermediateBufferRGBA1); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaFirstDenoiseKernel, numTilesX, numTilesY, parameters.viewCount); // Re-inject parameters for denoising cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaSecondDenoiseKernel, HDShaderIDs._DepthTexture, sssartResources.depthStencilBuffer); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaSecondDenoiseKernel, HDShaderIDs._NormalBufferTexture, sssartResources.normalBuffer); // Second (and final) denoising pass cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaSecondDenoiseKernel, HDShaderIDs._DenoiseInputTexture, sssartResources.intermediateBufferRGBA1); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaSecondDenoiseKernel, HDShaderIDs._DenoiseOutputTextureRW, sssartResources.outputShadowTexture); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaSecondDenoiseKernel, numTilesX, numTilesY, parameters.viewCount); } else { cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowNoDenoiseKernel, HDShaderIDs._AnalyticProbBuffer, sssartResources.intermediateBufferRG0); cmd.SetComputeTextureParam(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowNoDenoiseKernel, HDShaderIDs._DenoiseOutputTextureRW, sssartResources.outputShadowTexture); cmd.DispatchCompute(parameters.screenSpaceShadowsFilterCS, parameters.areaShadowNoDenoiseKernel, numTilesX, numTilesY, parameters.viewCount); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Initialize the device m_device.Init(panelOutput1.Handle, false, true); // Build cube primitive { float3 colorXp = new float3(1, 0, 0); float3 colorXn = new float3(1, 1, 0); float3 colorYp = new float3(0, 1, 0); float3 colorYn = new float3(0, 1, 1); float3 colorZp = new float3(0, 0, 1); float3 colorZn = new float3(1, 0, 1); VertexP3N3G3T2[] vertices = new VertexP3N3G3T2[6 * 4] { // +X new VertexP3N3G3T2() { P = new float3(1, 1, 1), N = new float3(1, 0, 0), T = colorXp, UV = new float2(0, 0) }, new VertexP3N3G3T2() { P = new float3(1, -1, 1), N = new float3(1, 0, 0), T = colorXp, UV = new float2(0, 1) }, new VertexP3N3G3T2() { P = new float3(1, -1, -1), N = new float3(1, 0, 0), T = colorXp, UV = new float2(1, 1) }, new VertexP3N3G3T2() { P = new float3(1, 1, -1), N = new float3(1, 0, 0), T = colorXp, UV = new float2(1, 0) }, // -X new VertexP3N3G3T2() { P = new float3(-1, 1, -1), N = new float3(-1, 0, 0), T = colorXn, UV = new float2(0, 0) }, new VertexP3N3G3T2() { P = new float3(-1, -1, -1), N = new float3(-1, 0, 0), T = colorXn, UV = new float2(0, 1) }, new VertexP3N3G3T2() { P = new float3(-1, -1, 1), N = new float3(-1, 0, 0), T = colorXn, UV = new float2(1, 1) }, new VertexP3N3G3T2() { P = new float3(-1, 1, 1), N = new float3(-1, 0, 0), T = colorXn, UV = new float2(1, 0) }, // +Y new VertexP3N3G3T2() { P = new float3(-1, 1, -1), N = new float3(0, 1, 0), T = colorYp, UV = new float2(0, 0) }, new VertexP3N3G3T2() { P = new float3(-1, 1, 1), N = new float3(0, 1, 0), T = colorYp, UV = new float2(0, 1) }, new VertexP3N3G3T2() { P = new float3(1, 1, 1), N = new float3(0, 1, 0), T = colorYp, UV = new float2(1, 1) }, new VertexP3N3G3T2() { P = new float3(1, 1, -1), N = new float3(0, 1, 0), T = colorYp, UV = new float2(1, 0) }, // -Y new VertexP3N3G3T2() { P = new float3(-1, -1, 1), N = new float3(0, -1, 0), T = colorYn, UV = new float2(0, 0) }, new VertexP3N3G3T2() { P = new float3(-1, -1, -1), N = new float3(0, -1, 0), T = colorYn, UV = new float2(0, 1) }, new VertexP3N3G3T2() { P = new float3(1, -1, -1), N = new float3(0, -1, 0), T = colorYn, UV = new float2(1, 1) }, new VertexP3N3G3T2() { P = new float3(1, -1, 1), N = new float3(0, -1, 0), T = colorYn, UV = new float2(1, 0) }, // +Z new VertexP3N3G3T2() { P = new float3(-1, 1, 1), N = new float3(0, 0, 1), T = colorZp, UV = new float2(0, 0) }, new VertexP3N3G3T2() { P = new float3(-1, -1, 1), N = new float3(0, 0, 1), T = colorZp, UV = new float2(0, 1) }, new VertexP3N3G3T2() { P = new float3(1, -1, 1), N = new float3(0, 0, 1), T = colorZp, UV = new float2(1, 1) }, new VertexP3N3G3T2() { P = new float3(1, 1, 1), N = new float3(0, 0, 1), T = colorZp, UV = new float2(1, 0) }, // -Z new VertexP3N3G3T2() { P = new float3(1, 1, -1), N = new float3(0, 0, -1), T = colorZn, UV = new float2(0, 0) }, new VertexP3N3G3T2() { P = new float3(1, -1, -1), N = new float3(0, 0, -1), T = colorZn, UV = new float2(0, 1) }, new VertexP3N3G3T2() { P = new float3(-1, -1, -1), N = new float3(0, 0, -1), T = colorZn, UV = new float2(1, 1) }, new VertexP3N3G3T2() { P = new float3(-1, 1, -1), N = new float3(0, 0, -1), T = colorZn, UV = new float2(1, 0) }, }; uint[] indices = new uint[3 * 2 * 6] { 4 * 0 + 0, 4 * 0 + 1, 4 * 0 + 2, 4 * 0 + 0, 4 * 0 + 2, 4 * 0 + 3, 4 * 1 + 0, 4 * 1 + 1, 4 * 1 + 2, 4 * 1 + 0, 4 * 1 + 2, 4 * 1 + 3, 4 * 2 + 0, 4 * 2 + 1, 4 * 2 + 2, 4 * 2 + 0, 4 * 2 + 2, 4 * 2 + 3, 4 * 3 + 0, 4 * 3 + 1, 4 * 3 + 2, 4 * 3 + 0, 4 * 3 + 2, 4 * 3 + 3, 4 * 4 + 0, 4 * 4 + 1, 4 * 4 + 2, 4 * 4 + 0, 4 * 4 + 2, 4 * 4 + 3, 4 * 5 + 0, 4 * 5 + 1, 4 * 5 + 2, 4 * 5 + 0, 4 * 5 + 2, 4 * 5 + 3, }; m_prim_cube = new Primitive(m_device, 6 * 4, VertexP3N3G3T2.FromArray(vertices), indices, Primitive.TOPOLOGY.TRIANGLE_LIST, VERTEX_FORMAT.P3N3G3T2); } // Build the shader to render the cube m_shader_renderCube = new Shader(m_device, new System.IO.FileInfo(@".\Shaders\RenderCube.hlsl"), VERTEX_FORMAT.P3N3G3T2, "VS", null, "PS"); // Build constant buffer to provide camera transform m_CB_Camera = new ConstantBuffer <CBCamera>(m_device, 0); Application.Idle += Application_Idle; }
public void RenderAO(HDCamera hdCamera, CommandBuffer cmd, RTHandle outputTexture, ShaderVariablesRaytracing globalCB, ScriptableRenderContext renderContext, int frameCount) { // If any of the previous requirements is missing, the effect is not requested or no acceleration structure, set the default one and leave right away if (!m_RenderPipeline.GetRayTracingState()) { SetDefaultAmbientOcclusionTexture(cmd); return; } RayTracingShader aoShaderRT = m_PipelineRayTracingResources.aoRaytracingRT; var aoSettings = hdCamera.volumeStack.GetComponent <AmbientOcclusion>(); RayCountManager rayCountManager = m_RenderPipeline.GetRayCountManager(); using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingAmbientOcclusion))) { // Grab the acceleration structure for the target camera RayTracingAccelerationStructure accelerationStructure = m_RenderPipeline.RequestAccelerationStructure(); // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(aoShaderRT, "VisibilityDXR"); // Set the acceleration structure for the pass cmd.SetRayTracingAccelerationStructure(aoShaderRT, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray generation data (be careful of the global constant buffer limitation) globalCB._RaytracingRayMaxLength = aoSettings.rayLength; globalCB._RaytracingNumSamples = aoSettings.sampleCount; ConstantBuffer.PushGlobal(cmd, globalCB, HDShaderIDs._ShaderVariablesRaytracing); // Set the data for the ray generation cmd.SetRayTracingTextureParam(aoShaderRT, HDShaderIDs._DepthTexture, m_RenderPipeline.sharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(aoShaderRT, HDShaderIDs._NormalBufferTexture, m_RenderPipeline.sharedRTManager.GetNormalBuffer()); // Inject the ray-tracing sampling data BlueNoise blueNoise = m_RenderPipeline.GetBlueNoiseManager(); blueNoise.BindDitheredRNGData8SPP(cmd); // Set the output textures cmd.SetRayTracingTextureParam(aoShaderRT, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); cmd.SetRayTracingTextureParam(aoShaderRT, HDShaderIDs._AmbientOcclusionTextureRW, m_AOIntermediateBuffer0); // Run the computation cmd.DispatchRays(aoShaderRT, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, (uint)hdCamera.viewCount); } using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingFilterAmbientOcclusion))) { if (aoSettings.denoise) { // Grab the history buffer RTHandle ambientOcclusionHistory = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion) ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedAmbientOcclusion, AmbientOcclusionHistoryBufferAllocatorFunction, 1); float historyValidity = 1.0f; #if UNITY_HDRP_DXR_TESTS_DEFINE if (Application.isPlaying) { historyValidity = 0.0f; } else #endif // We need to check if something invalidated the history buffers historyValidity = m_RenderPipeline.ValidRayTracingHistory(hdCamera) ? 1.0f : 0.0f; // Apply the temporal denoiser HDTemporalFilter temporalFilter = m_RenderPipeline.GetTemporalFilter(); temporalFilter.DenoiseBuffer(cmd, hdCamera, m_AOIntermediateBuffer0, ambientOcclusionHistory, m_AOIntermediateBuffer1, historyValidity: historyValidity); // Apply the diffuse denoiser HDDiffuseDenoiser diffuseDenoiser = m_RenderPipeline.GetDiffuseDenoiser(); diffuseDenoiser.DenoiseBuffer(cmd, hdCamera, m_AOIntermediateBuffer1, outputTexture, aoSettings.denoiserRadius); } else { HDUtils.BlitCameraTexture(cmd, m_AOIntermediateBuffer0, outputTexture); } ComputeShader aoShaderCS = m_PipelineRayTracingResources.aoRaytracingCS; cmd.SetComputeFloatParam(aoShaderCS, HDShaderIDs._RaytracingAOIntensity, aoSettings.intensity.value); cmd.SetComputeTextureParam(aoShaderCS, m_RTAOApplyIntensityKernel, HDShaderIDs._AmbientOcclusionTextureRW, outputTexture); int texWidth = hdCamera.actualWidth; int texHeight = hdCamera.actualHeight; int areaTileSize = 8; int numTilesXHR = (texWidth + (areaTileSize - 1)) / areaTileSize; int numTilesYHR = (texHeight + (areaTileSize - 1)) / areaTileSize; cmd.DispatchCompute(aoShaderCS, m_RTAOApplyIntensityKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount); } // Bind the textures and the params cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, outputTexture); // TODO: All the push-debug stuff should be centralized somewhere (RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(hdCamera, cmd, outputTexture, FullScreenDebugMode.SSAO); }
/// <summary> /// Add services : /// </summary> protected override void Initialize () { base.Initialize(); constBuffer = new ConstantBuffer(GraphicsDevice, typeof(CBData)); LoadContent(); Reloading += (s, e) => LoadContent(); GetService<Camera>().FreeCamPosition = new Vector3Fusion(0, 12, 21); // fill vertex buffer for cube: Vector4Fusion color = new Vector4Fusion(Vector3Fusion.Zero, 1); Fusion.Mathematics.Vector2 texcoord = Fusion.Mathematics.Vector2.Zero; // back face var v0 = new CubeVertex { Position = new Vector3Fusion(-0.5f, -0.5f, -0.5f), Normal = new Vector3Fusion(-1.0f, 0, 0), Color = color, TexCoord = texcoord }; var v1 = new CubeVertex { Position = new Vector3Fusion(-0.5f, -0.5f, 0.5f), Normal = new Vector3Fusion(-1.0f, 0, 0), Color = color, TexCoord = texcoord }; var v2 = new CubeVertex { Position = new Vector3Fusion(-0.5f, 0.5f, 0.5f), Normal = new Vector3Fusion(-1.0f, 0, 0), Color = color, TexCoord = texcoord }; var v3 = new CubeVertex { Position = new Vector3Fusion(-0.5f, 0.5f, -0.5f), Normal = new Vector3Fusion(-1.0f, 0, 0), Color = color, TexCoord = texcoord }; // front var v4 = new CubeVertex { Position = new Vector3Fusion(0.5f, -0.5f, -0.5f), Normal = new Vector3Fusion(1.0f, 0, 0), Color = color, TexCoord = texcoord }; var v5 = new CubeVertex { Position = new Vector3Fusion(0.5f, -0.5f, 0.5f), Normal = new Vector3Fusion(1.0f, 0, 0), Color = color, TexCoord = texcoord }; var v6 = new CubeVertex { Position = new Vector3Fusion(0.5f, 0.5f, 0.5f), Normal = new Vector3Fusion(1.0f, 0, 0), Color = color, TexCoord = texcoord }; var v7 = new CubeVertex { Position = new Vector3Fusion(0.5f, 0.5f, -0.5f), Normal = new Vector3Fusion(1.0f, 0, 0), Color = color, TexCoord = texcoord }; // left var v8 = new CubeVertex { Position = new Vector3Fusion(-0.5f, -0.5f, -0.5f), Normal = new Vector3Fusion(0, 0, -1.0f), Color = color, TexCoord = texcoord }; var v9 = new CubeVertex { Position = new Vector3Fusion(0.5f, -0.5f, -0.5f), Normal = new Vector3Fusion(0, 0, -1.0f), Color = color, TexCoord = texcoord }; var v10 = new CubeVertex { Position = new Vector3Fusion(0.5f, 0.5f, -0.5f), Normal = new Vector3Fusion(0, 0, -1.0f), Color = color, TexCoord = texcoord }; var v11 = new CubeVertex { Position = new Vector3Fusion(-0.5f, 0.5f, -0.5f), Normal = new Vector3Fusion(0, 0, -1.0f), Color = color, TexCoord = texcoord }; // right var v12 = new CubeVertex { Position = new Vector3Fusion(-0.5f, -0.5f, 0.5f), Normal = new Vector3Fusion(0, 0, 1.0f), Color = color, TexCoord = texcoord }; var v13 = new CubeVertex { Position = new Vector3Fusion(0.5f, -0.5f, 0.5f), Normal = new Vector3Fusion(0, 0, 1.0f), Color = color, TexCoord = texcoord }; var v14 = new CubeVertex { Position = new Vector3Fusion(0.5f, 0.5f, 0.5f), Normal = new Vector3Fusion(0, 0, 1.0f), Color = color, TexCoord = texcoord }; var v15 = new CubeVertex { Position = new Vector3Fusion(-0.5f, 0.5f, 0.5f), Normal = new Vector3Fusion(0, 0, 1.0f), Color = color, TexCoord = texcoord }; // top var v16 = new CubeVertex { Position = new Vector3Fusion(0.5f, 0.5f, -0.5f), Normal = new Vector3Fusion(0, 1.0f, 0), Color = color, TexCoord = texcoord }; var v17 = new CubeVertex { Position = new Vector3Fusion(0.5f, 0.5f, 0.5f), Normal = new Vector3Fusion(0, 1.0f, 0), Color = color, TexCoord = texcoord }; var v18 = new CubeVertex { Position = new Vector3Fusion(-0.5f, 0.5f, 0.5f), Normal = new Vector3Fusion(0, 1.0f, 0), Color = color, TexCoord = texcoord }; var v19 = new CubeVertex { Position = new Vector3Fusion(-0.5f, 0.5f, -0.5f), Normal = new Vector3Fusion(0, 1.0f, 0), Color = color, TexCoord = texcoord }; // bottom var v20 = new CubeVertex { Position = new Vector3Fusion(0.5f, -0.5f, -0.5f), Normal = new Vector3Fusion(0, -1.0f, 0), Color = color, TexCoord = texcoord }; var v21 = new CubeVertex { Position = new Vector3Fusion(0.5f, -0.5f, 0.5f), Normal = new Vector3Fusion(0, -1.0f, 0), Color = color, TexCoord = texcoord }; var v22 = new CubeVertex { Position = new Vector3Fusion(-0.5f, -0.5f, 0.5f), Normal = new Vector3Fusion(0, -1.0f, 0), Color = color, TexCoord = texcoord }; var v23 = new CubeVertex { Position = new Vector3Fusion(-0.5f, -0.5f, -0.5f), Normal = new Vector3Fusion(0, -1.0f, 0), Color = color, TexCoord = texcoord }; data = new CubeVertex[] { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23 }; vb.SetData(data, 0, 24); // fill the index buffer var index = new int[] { 3, 1, 0, // back 3, 2, 1, 4, 5, 7, // front 7, 5, 6, 8, 9, 11, // left 11, 9, 10, 14, 13, 12, // right 14, 12, 15, 19, 16, 17, // top 19, 17, 18, 20, 23, 22, // bottom 20, 22, 21}; ib.SetData(index); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { m_device.Init(panelOutput.Handle, false, true); } catch (Exception _e) { m_device = null; MessageBox.Show("Failed to initialize DX device!\n\n" + _e.Message, "Area Light Test", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } m_CB_Main = new ConstantBuffer <CB_Main>(m_device, 0); m_CB_Camera = new ConstantBuffer <CB_Camera>(m_device, 1); m_CB_Light = new ConstantBuffer <CB_Light>(m_device, 2); m_CB_TestQuad = new ConstantBuffer <CB_TestQuad>(m_device, 3); try { m_shader_RenderLight = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderLight.hlsl"), VERTEX_FORMAT.P3N3, "VS", null, "PS"); m_shader_RenderScene = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderScene.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); m_shader_RenderScene_Reference = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderScene_Reference.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); m_shader_RenderDiff = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderDiff.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); m_shader_RenderTestQuad = new Shader(m_device, new System.IO.FileInfo("Shaders/RenderTestQuad.hlsl"), VERTEX_FORMAT.Pt4, "VS", null, "PS"); } catch (Exception _e) { MessageBox.Show("Shader failed to compile!\n\n" + _e.Message, "Area Light Test", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } BuildPrimitives(); // Allocate temp targets & false colors spectrum m_RT_temp0 = new Texture2D(m_device, m_device.DefaultTarget.Width, m_device.DefaultTarget.Height, 1, 1, ImageUtility.PIXEL_FORMAT.RGBA32F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, null); m_RT_temp1 = new Texture2D(m_device, m_device.DefaultTarget.Width, m_device.DefaultTarget.Height, 1, 1, ImageUtility.PIXEL_FORMAT.RGBA32F, ImageUtility.COMPONENT_FORMAT.AUTO, false, false, null); m_tex_FalseColors = Image2Texture(new System.IO.FileInfo("FalseColorsSpectrum.png"), ImageUtility.COMPONENT_FORMAT.UNORM_sRGB); // Setup camera m_camera.CreatePerspectiveCamera((float)(FOV_DEGREES * Math.PI / 180.0), (float)panelOutput.Width / panelOutput.Height, 0.01f, 100.0f); m_manipulator.Attach(panelOutput, m_camera); m_manipulator.InitializeCamera(new float3(0, 1, 4), new float3(0, 1, 0), float3.UnitY); m_manipulator.EnableMouseAction += m_manipulator_EnableMouseAction; // Pre-integrated BRDF tables LoadMSBRDF(new uint[] { 128, 32 }, new System.IO.FileInfo[] { new System.IO.FileInfo("./Tables/MSBRDF_GGX_G2_E128x128.float"), new System.IO.FileInfo("./Tables/MSBRDF_OrenNayar_E32x32.float"), }, new System.IO.FileInfo[] { new System.IO.FileInfo("./Tables/MSBRDF_GGX_G2_Eavg128.float"), new System.IO.FileInfo("./Tables/MSBRDF_OrenNayar_Eavg32.float"), }, out m_tex_MSBRDF_E, out m_tex_MSBRDF_Eavg ); // LTC Tables m_tex_LTC = LoadLTC(new System.IO.FileInfo(@".\Tables\LTC.dds")); m_tex_MS_LTC = LoadMSLTC(new System.IO.FileInfo(@".\Tables\MS_LTC.dds")); // Start game time m_ticks2Seconds = 1.0 / System.Diagnostics.Stopwatch.Frequency; m_stopWatch.Start(); m_startTime = GetGameTime(); m_camera.CameraTransformChanged += new EventHandler(Camera_CameraTransformChanged); Camera_CameraTransformChanged(m_camera, EventArgs.Empty); Application.Idle += new EventHandler(Application_Idle); }