예제 #1
0
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            if (m_Device == null)
            {
                return;
            }

            m_CB_PostProcess.Dispose();
            m_CB_Downsample.Dispose();
            m_CB_Camera.Dispose();
            m_CB_Main.Dispose();

            m_Tex_DownsampledDepth.Dispose();
            m_Tex_LinearDepth.Dispose();

            m_Tex_TempBuffer2.Dispose();
            m_Tex_TempBuffer.Dispose();

            if (m_Shader != null)
            {
                m_Shader_Glass.Dispose();
                m_Shader.Dispose();
                m_ShaderPostProcess.Dispose();
//				m_ShaderDownsample.Dispose();
                m_ShaderDownsampleCS.Dispose();
                m_ShaderLinearizeDepthCS.Dispose();
            }
            m_Prim_Quad.Dispose();

            m_Device.Exit();

            base.OnFormClosed(e);
        }
예제 #2
0
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            m_Tex_DistanceField[1].Dispose();
            m_Tex_DistanceField[0].Dispose();
            m_Tex_SplatDepthStencil[0].Dispose();
            m_Tex_SplatDepthStencil[1].Dispose();
            m_Tex_TempDepthAccumulatorBA.Dispose();
            m_Tex_TempDepthAccumulatorRG.Dispose();
            m_Tex_TempTarget.Dispose();

            m_Prim_Cube.Dispose();
            m_Prim_Sphere.Dispose();
            m_Prim_Rectangle.Dispose();
            m_Prim_Quad.Dispose();

            m_CB_Object.Dispose();
            m_CB_Camera.Dispose();
            m_CB_Main.Dispose();

            m_Shader_BuildDistanceField[2].Dispose();
            m_Shader_BuildDistanceField[1].Dispose();
            m_Shader_BuildDistanceField[0].Dispose();
            m_Shader_PostProcess.Dispose();
            m_Shader_FinalizeSplat.Dispose();
            m_Shader_SplatDepthStencil.Dispose();
            m_Shader_ClearAccumulator.Dispose();
            m_Shader_RenderScene.Dispose();

            m_Device.Dispose();
            m_Device = null;
        }
예제 #3
0
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            if (m_Device == null)
            {
                return;
            }

            m_SB_Points2D.Dispose();
            m_SB_Points4D[0].Dispose();
            m_SB_Points4D[1].Dispose();
            m_SB_Velocities4D.Dispose();

            m_CB_Simulation.Dispose();
            m_CB_Camera4D.Dispose();
            m_CB_Camera.Dispose();

            m_PrimQuad.Dispose();

            m_PS_Display.Dispose();
            m_CS_Project4D.Dispose();
            m_CS_Simulator.Dispose();

            m_Device.Exit();

            base.OnFormClosed(e);
        }
예제 #4
0
파일: Shader.cs 프로젝트: lypvc/ImageViewer
 public void Dispose()
 {
     vertex?.Dispose();
     pixel?.Dispose();
     compute?.Dispose();
     geometry?.Dispose();
 }
        protected override void Deallocate()
        {
            mConstants.Reset();
            mResources.Reset();
            mOutputs.Reset();

            mShader?.Dispose();
            mShader = null;
        }
 public void Dispose()
 {
     m_CS__Generic.Dispose();
     m_CS__1to16.Dispose();
     m_texBufferCPU.Dispose();
     m_texBufferOut.Dispose();
     m_texBufferIn.Dispose();
     m_CB.Dispose();
 }
 public void Dispose()
 {
     if (m_CS__Remainder != null)
     {
         m_CS__Remainder.Dispose();
     }
     m_CS__1to256.Dispose();
     m_texBufferCPU.Dispose();
     m_texBufferOut.Dispose();
     m_texBufferIn.Dispose();
     m_CB.Dispose();
 }
예제 #8
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                }

                computeFillNoiseTexture.Dispose();
            }

            isDisposed = true;
        }
예제 #9
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            m_closing = true;
            if (m_Device == null)
            {
                return;
            }

                        #if DEBUG
            if (m_Shader_ToneMapping != null)
            {
                m_Shader_ToneMapping.Dispose();
            }
            if (m_Shader_ComputeAutoExposure != null)
            {
                m_Shader_ComputeAutoExposure.Dispose();
            }
            if (m_Shader_FinalizeHistogram != null)
            {
                m_Shader_FinalizeHistogram.Dispose();
            }
            if (m_Shader_ComputeTallHistogram != null)
            {
                m_Shader_ComputeTallHistogram.Dispose();
            }
            if (m_Shader_RenderHDR != null)
            {
                m_Shader_RenderHDR.Dispose();
            }

            m_Buffer_AutoExposureTarget.Dispose();
            m_Buffer_AutoExposureSource.Dispose();
            m_Tex_Histogram.Dispose();
            m_Tex_TallHistogram.Dispose();
            m_Tex_HDR.Dispose();
            if (m_Tex_CubeMap != null)
            {
                m_Tex_CubeMap.Dispose();
            }

            m_CB_AutoExposure.Dispose();
            m_CB_ToneMapping.Dispose();
            m_CB_Camera.Dispose();
            m_CB_Main.Dispose();

            m_Device.Exit();
            m_Device = null;
                        #endif

            base.OnFormClosing(e);
        }
예제 #10
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                }

                computeScanExclusiveShared.Dispose();
                computeScanExclusiveShared2.Dispose();
                computeUniformUpdate.Dispose();
            }

            isDisposed = true;
        }
예제 #11
0
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            if (m_Device == null)
            {
                return;
            }

            m_Prim_Cube.Dispose();
            m_Prim_Sphere.Dispose();
            m_Prim_Quad.Dispose();

            m_SB_Photons[1].Dispose();
            m_SB_Photons[0].Dispose();
            m_SB_PhotonInfos.Dispose();

            m_Tex_Noise4D.Dispose();
            m_Tex_Noise.Dispose();
            m_Tex_AccumPhoton3D.Dispose();
            m_Tex_AccumPhotonCube.Dispose();
            m_Tex_VolumeDensity.Dispose();
            m_Tex_Scattering.Dispose();
            m_Tex_HeightMap.Dispose();
            m_Tex_TempBackBuffer.Dispose();

            m_CB_PostProcess.Dispose();
            m_CB_RayMarch.Dispose();
            m_CB_RenderSphere.Dispose();
            m_CB_RenderRoom.Dispose();
            m_CB_TracePhotons.Dispose();
            m_CB_GenerateDensity.Dispose();
            m_CB_Camera.Dispose();
            m_CB_Global.Dispose();

            m_Shader_PostProcess.Dispose();
            m_Shader_RenderSphere.Dispose();
            m_Shader_RenderRoom.Dispose();
            m_Shader_RayMarcher.Dispose();
            m_Shader_TracePhotons.Dispose();
            m_Shader_InitPhotons.Dispose();
            m_Shader_ClearAccumulator.Dispose();
            m_shader_GenerateDensity.Dispose();
            m_Shader_UpdateHeightMap.Dispose();

            m_Device.Exit();

            base.OnFormClosed(e);
        }
예제 #12
0
        protected override void OnClosing(CancelEventArgs e)
        {
            try {
                m_SB_Rays.Dispose();
                m_CB_Display.Dispose();
                m_CB_Filter.Dispose();
                m_CB_Input.Dispose();

                m_PS_Display.Dispose();
                m_CS_GenerateSSBumpMap.Dispose();
                m_CS_BilateralFilter.Dispose();

                if (m_TextureTarget_CPU != null)
                {
                    m_TextureTarget_CPU.Dispose();
                }
                if (m_TextureTarget1 != null)
                {
                    m_TextureTarget1.Dispose();
                }
                if (m_TextureTarget0 != null)
                {
                    m_TextureTarget0.Dispose();
                }
                if (m_TextureSource != null)
                {
                    m_TextureSource.Dispose();
                }

                m_Device.Dispose();
                m_Device = null;
            } catch (Exception _e) {
                MessageBox("Failed to close:\r\n", _e);
            }

// FFS!!!
            System.Diagnostics.Process P = System.Diagnostics.Process.GetCurrentProcess();
            P.Kill();

            e.Cancel = false;
            base.OnClosing(e);
        }
예제 #13
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                }

                prefixScan.Dispose();
                computePositionWeightNoiseCube.Dispose();
                computeNormalAmbient.Dispose();
                computeMarchingCubesCases.Dispose();
                computeMarchingCubesVertices.Dispose();
                computePositionWeightNoiseCubeWarp.Dispose();
                computePositionWeightFormula.Dispose();
                constantBuffer.Dispose();
            }

            isDisposed = true;
        }
        public void Dispose()
        {
            m_texNoiseScoreCPU.Dispose();
            m_texNoiseScore2.Dispose();
            m_texNoiseScore.Dispose();
            m_texNoiseCPU.Dispose();
            m_texNoise1.Dispose();
            m_texNoise0.Dispose();

            m_SB_Mutations.Dispose();
            m_CB_Mips.Dispose();
            m_CB_Main.Dispose();

            m_CS_AccumulateScore2.Dispose();
            m_CS_AccumulateScore4.Dispose();
            m_CS_AccumulateScore8.Dispose();
            m_CS_AccumulateScore16.Dispose();
            m_CS_ComputeScore.Dispose();
            m_CS_Mutate.Dispose();
            m_CS_Copy.Dispose();
        }
예제 #15
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();

                m_tex_FontRectangle.Dispose();
                m_tex_FontAtlas.Dispose();
                m_SB_Text.Dispose();

                m_SB_HeatSum.Dispose();
                m_SB_HeatBarycentrics.Dispose();
                m_SB_HeatTarget.Dispose();
                m_SB_HeatSource.Dispose();

                m_tex_FalseColors1.Dispose();
                m_tex_FalseColors0.Dispose();

                m_SB_SourceIndices.Dispose();

                m_SB_LinkTargets.Dispose();
                m_SB_LinkSources.Dispose();
                m_SB_Nodes.Dispose();

                m_shader_RenderText.Dispose();
                m_shader_RenderGraphLink.Dispose();
                m_shader_RenderGraphNode.Dispose();

                m_compute_HeatDiffusion.Dispose();

                m_CB_Text.Dispose();
                m_CB_Main.Dispose();

                Device temp = m_device;
                m_device = null;
                temp.Dispose();
            }
            base.Dispose(disposing);
        }
예제 #16
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();

                m_tex_FontRectangle.Dispose();
                m_tex_FontAtlas.Dispose();
                m_SB_Text.Dispose();

                m_tex_FalseColors.Dispose();

                m_SB_Forces.Dispose();
                m_SB_NodeSims[1].Dispose();
                m_SB_NodeSims[0].Dispose();
                m_SB_Links.Dispose();
                m_SB_Nodes.Dispose();

                m_shader_RenderText.Dispose();
#if RENDER_GRAPH_PROPER
                m_shader_RenderGraphLink.Dispose();
                m_shader_RenderGraphNode.Dispose();
#else
                m_shader_RenderGraph.Dispose();
#endif
                m_shader_Simulate.Dispose();
                m_shader_ComputeForces.Dispose();

                m_CB_Text.Dispose();
                m_CB_Simulation.Dispose();
                m_CB_Main.Dispose();

                Device temp = m_device;
                m_device = null;
                temp.Dispose();
            }
            base.Dispose(disposing);
        }
예제 #17
0
        public void Dispose()
        {
            if (m_device == null)
            {
                return;                 // CPU version didn't allocate anything
            }
            m_texScoreCPU.Dispose();
            m_texScore1.Dispose();
            m_texScore0.Dispose();
            m_texDitheringArrayCPU.Dispose();
            m_texDitheringArray.Dispose();
            m_texBinaryPattern.Dispose();

            m_CB_Mips.Dispose();
            m_CB_Main.Dispose();

            m_CS_Splat.Dispose();
            m_CS_DownsampleScore2.Dispose();
            m_CS_DownsampleScore4.Dispose();
            m_CS_DownsampleScore8.Dispose();
            m_CS_DownsampleScore16.Dispose();
            m_CS_Filter.Dispose();
        }
예제 #18
0
		unsafe void	ComputeBRDFIntegral( System.IO.FileInfo _TableFileName, uint _TableSize ) {

//			ComputeShader	CS = new ComputeShader( m_Device, new System.IO.FileInfo( "Shaders/ComputeBRDFIntegral.hlsl" ), "CS", new ShaderMacro[0] );
			ComputeShader	CS = new ComputeShader( m_Device, new System.IO.FileInfo( "Shaders/ComputeBRDFIntegral.hlsl" ), "CS", new ShaderMacro[] { new ShaderMacro( "IMPORTANCE_SAMPLING", "1" ) } );

			Texture2D		TexTable = new Texture2D( m_Device, _TableSize, _TableSize, 1, 1, PIXEL_FORMAT.RG32_FLOAT, false, true, null );
			TexTable.SetCSUAV( 0 );
			CS.Use();
			CS.Dispatch( _TableSize >> 4, _TableSize >> 4, 1 );
			CS.Dispose();



			string	DDSFileName = System.IO.Path.GetFileNameWithoutExtension( _TableFileName.FullName ) + ".dds";
//			DirectXTexManaged.TextureCreator.CreateDDS( DDSFileName, TexTable );
throw new Exception( "Deprecated!" );


 
			Texture2D		TexTableStaging = new Texture2D( m_Device, _TableSize, _TableSize, 1, 1, PIXEL_FORMAT.RG32_FLOAT, true, false, null );
			TexTableStaging.CopyFrom( TexTable );
			TexTable.Dispose();

			// Write tables
			float2	Temp = new float2();
			float	F0_analytical;
			float	ambient_analytical;
			float	maxAbsoluteError_F0 = 0.0f;
			float	maxRelativeError_F0 = 0.0f;
			float	avgAbsoluteError_F0 = 0.0f;
			float	avgRelativeError_F0 = 0.0f;
			float	maxAbsoluteError_ambient = 0.0f;
			float	maxRelativeError_ambient = 0.0f;
			float	avgAbsoluteError_ambient = 0.0f;
			float	avgRelativeError_ambient = 0.0f;

			float2[]	Integral_SpecularReflectance = new float2[_TableSize];

			PixelsBuffer Buff = TexTableStaging.Map( 0, 0 );
			using ( System.IO.BinaryReader R = Buff.OpenStreamRead() )
				using ( System.IO.FileStream S = _TableFileName.Create() )
					using ( System.IO.BinaryWriter W = new System.IO.BinaryWriter( S ) )
						for ( int Y=0; Y < _TableSize; Y++ ) {
							float2	SumSpecularlyReflected = float2.Zero;
							for ( int X=0; X < _TableSize; X++ ) {
								Temp.x = R.ReadSingle();
								Temp.y = R.ReadSingle();
								W.Write( Temp.x );
								W.Write( Temp.y );

								SumSpecularlyReflected.x += Temp.x;
								SumSpecularlyReflected.y += Temp.y;

								// Check analytical solution
								float	NdotV = (float) X / (_TableSize-1);
								float	roughness = (float) Y / (_TableSize-1);
								AnalyticalBRDFIntegral_Order3( NdotV, roughness, out F0_analytical, out ambient_analytical );
//								AnalyticalBRDFIntegral_Order2( NdotV, roughness, out F0_analytical, out ambient_analytical );

								float	absoluteError_F0 = Math.Abs( F0_analytical - Temp.x );
								float	relativeError_F0 = F0_analytical > 1e-6f ? Temp.x / F0_analytical : 0.0f;
								maxAbsoluteError_F0 = Math.Max( maxAbsoluteError_F0, absoluteError_F0 );
								maxRelativeError_F0 = Math.Max( maxRelativeError_F0, relativeError_F0 );
								avgAbsoluteError_F0 += absoluteError_F0;
								avgRelativeError_F0 += relativeError_F0;

								float	absoluteError_ambient = Math.Abs( ambient_analytical - Temp.y );
								float	relativeError_ambient = ambient_analytical > 1e-6f ? Temp.x / ambient_analytical : 0.0f;
								maxAbsoluteError_ambient = Math.Max( maxAbsoluteError_ambient, absoluteError_ambient );
								maxRelativeError_ambient = Math.Max( maxRelativeError_ambient, relativeError_ambient );
								avgAbsoluteError_ambient += absoluteError_ambient;
								avgRelativeError_ambient += relativeError_ambient;
							}

							// Normalize and store "not specularly reflected" light
							SumSpecularlyReflected = SumSpecularlyReflected / _TableSize;

							float	sum_dielectric = 1.0f - (0.04f * SumSpecularlyReflected.x + SumSpecularlyReflected.y);
							float	sum_metallic = 1.0f - (SumSpecularlyReflected.x + SumSpecularlyReflected.y);

							Integral_SpecularReflectance[Y] = SumSpecularlyReflected;
						}
			TexTableStaging.UnMap( 0, 0 );

			avgAbsoluteError_F0 /= _TableSize*_TableSize;
			avgRelativeError_F0 /= _TableSize*_TableSize;
			avgAbsoluteError_ambient /= _TableSize*_TableSize;
			avgRelativeError_ambient /= _TableSize*_TableSize;

			string	TotalSpecularReflectionTableFileName = System.IO.Path.GetFileNameWithoutExtension( _TableFileName.FullName ) + ".table";
			using ( System.IO.FileStream S = new System.IO.FileInfo( TotalSpecularReflectionTableFileName ).Create() )
				using ( System.IO.BinaryWriter W = new System.IO.BinaryWriter( S ) )
					for ( int i=0; i < _TableSize; i++ ) {
						W.Write( Integral_SpecularReflectance[i].x );
						W.Write( Integral_SpecularReflectance[i].y );
					}
		}
예제 #19
0
        public void Dispose()
        {
            DisposeBuffers();

            if (BlendState != null)
            {
                BlendState.Dispose();
                BlendState = null;
            }
            if (SampleStateLinear != null)
            {
                SampleStateLinear.Dispose();
                SampleStateLinear = null;
            }
            if (SampleStatePoint != null)
            {
                SampleStatePoint.Dispose();
                SampleStatePoint = null;
            }
            if (FinalPSVars != null)
            {
                FinalPSVars.Dispose();
                FinalPSVars = null;
            }
            if (FilterVCSVars != null)
            {
                FilterVCSVars.Dispose();
                FilterVCSVars = null;
            }
            if (FilterBPHCSVars != null)
            {
                FilterBPHCSVars.Dispose();
                FilterBPHCSVars = null;
            }
            if (LumBlendCSVars != null)
            {
                LumBlendCSVars.Dispose();
                LumBlendCSVars = null;
            }
            if (ReduceCSVars != null)
            {
                ReduceCSVars.Dispose();
                ReduceCSVars = null;
            }
            if (FinalPassLayout != null)
            {
                FinalPassLayout.Dispose();
                FinalPassLayout = null;
            }
            if (FinalPassQuad != null)
            {
                FinalPassQuad.Dispose();
                FinalPassQuad = null;
            }
            if (FinalPassPS != null)
            {
                FinalPassPS.Dispose();
                FinalPassPS = null;
            }
            if (FinalPassVS != null)
            {
                FinalPassVS.Dispose();
                FinalPassVS = null;
            }
            if (CopyPixelsPS != null)
            {
                CopyPixelsPS.Dispose();
                CopyPixelsPS = null;
            }
            if (BloomFilterVCS != null)
            {
                BloomFilterVCS.Dispose();
                BloomFilterVCS = null;
            }
            if (BloomFilterBPHCS != null)
            {
                BloomFilterBPHCS.Dispose();
                BloomFilterBPHCS = null;
            }
            if (LumBlendCS != null)
            {
                LumBlendCS.Dispose();
                LumBlendCS = null;
            }
            if (ReduceTo0DCS != null)
            {
                ReduceTo0DCS.Dispose();
                ReduceTo0DCS = null;
            }
            if (ReduceTo1DCS != null)
            {
                ReduceTo1DCS.Dispose();
                ReduceTo1DCS = null;
            }
        }
예제 #20
0
        private void RunGPU(int dataLength)
        {
            float[] data = new float[dataLength];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = 2;
            }
            ComputeShader shader           = null;
            int           reductionPerCall = 64;
            var           codeBase         = Assembly.GetEntryAssembly().CodeBase.Replace("file:///", "");
            var           compile          = Task.Factory.StartNew(() =>
            {
                var fileName = Path.Combine(Path.GetDirectoryName(codeBase), "Modules", "James.UTDM.TestGPU.hlsl");
                shader       = Gpu.CompileComputeShader(fileName, "CSMain");
                if (shader == null)
                {
                    throw new XTMFRuntimeException("We were unable to compile the compute shader!");
                }
                shader.NumberOfXThreads = data.Length;
                shader.NumberOfYThreads = 1;
                shader.ThreadGroupSizeX = 64;
                shader.ThreadGroupSizeY = 1;
            });
            var constBuffer       = Gpu.CreateConstantBuffer(16);
            var originalBuffer    = Gpu.CreateBuffer(data.Length, sizeof(float), true);
            var destinationBuffer = Gpu.CreateBuffer((data.Length / reductionPerCall) + 1, sizeof(float), true);

            try
            {
                this.Gpu.Write(originalBuffer, data);
                // wait now until the gpu has finished compiling the data
                compile.Wait();
                // make sure the write has completed
                this.Gpu.Wait();
                var watch = new Stopwatch();
                watch.Start();
                int size      = data.Length;
                int remainder = 0;
                while (size > 0)
                {
                    remainder = size % reductionPerCall;
                    shader.NumberOfXThreads = size / reductionPerCall;
                    shader.RemoveAllBuffers();
                    shader.AddBuffer(constBuffer);
                    shader.AddBuffer(originalBuffer);
                    shader.AddBuffer(destinationBuffer);
                    // execute then flip the buffers
                    this.Gpu.ExecuteComputeShader(shader);
                    // compute the remainder
                    var temp = destinationBuffer;
                    destinationBuffer = originalBuffer;
                    originalBuffer    = temp;
                    size = 0;
                }
                if (remainder > 0)
                {
                }
                Gpu.Wait();
                watch.Stop();
                using (var writer = new StreamWriter("gpu.txt", true))
                {
                    writer.WriteLine("{0}", (watch.ElapsedTicks / 10000f));
                }
            }
            finally
            {
                this.Gpu.ReleaseBuffer(constBuffer);
                this.Gpu.ReleaseBuffer(originalBuffer);
                this.Gpu.ReleaseBuffer(destinationBuffer);
                if (shader != null)
                {
                    shader.Dispose();
                    shader = null;
                }
            }
        }
예제 #21
0
        private void GenerateHeightMaps()
        {
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initTerrain", "cs_5_0", Shader.ShaderFlags);
            ComputeShader  initTerrain    = new ComputeShader(_context.DirectX.Device, shaderByteCode);

            shaderByteCode.Dispose();
            shaderByteCode = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "initWater", "cs_5_0", Shader.ShaderFlags);
            ComputeShader initWater = new ComputeShader(_context.DirectX.Device, shaderByteCode);

            shaderByteCode.Dispose();
            shaderByteCode         = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "applyRandomDisplacement", "cs_5_0", Shader.ShaderFlags);
            _baseTerrainGeneration = new ComputeShader(_context.DirectX.Device, shaderByteCode);
            shaderByteCode.Dispose();
            shaderByteCode    = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "flowsCalculation", "cs_5_0", Shader.ShaderFlags);
            _flowsCalculation = new ComputeShader(_context.DirectX.Device, shaderByteCode);
            shaderByteCode.Dispose();
            shaderByteCode    = ShaderBytecode.CompileFromFile(@"Data/Shaders/TerrainCompute.hlsl", "updateWaterLevel", "cs_5_0", Shader.ShaderFlags);
            _updateWaterLevel = new ComputeShader(_context.DirectX.Device, shaderByteCode);
            shaderByteCode.Dispose();

            Texture2DDescription textureDescription = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource | BindFlags.UnorderedAccess,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R32_Float,
                Height            = TextureSize,
                Width             = TextureSize,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            };

            ConstantBuffer <ComputeData> computeBuffer = new ConstantBuffer <ComputeData>(_context);

            _context.DirectX.DeviceContext.ComputeShader.SetConstantBuffer(1, computeBuffer.Buffer);

            foreach (Face face in _faces)
            {
                Texture2D terrainTexture = new Texture2D(_context.DirectX.Device, textureDescription);
                face.TerrainSrv = new ShaderResourceView(_context.DirectX.Device, terrainTexture);
                face.TerrainUav = new UnorderedAccessView(_context.DirectX.Device, terrainTexture);
                terrainTexture.Dispose();

                Texture2D waterTexture = new Texture2D(_context.DirectX.Device, textureDescription);
                face.WaterSrv = new ShaderResourceView(_context.DirectX.Device, waterTexture);
                face.WaterUav = new UnorderedAccessView(_context.DirectX.Device, waterTexture);
                waterTexture.Dispose();

                Texture2D flowsTexture = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsLeftUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                flowsTexture     = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsTopUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                flowsTexture       = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsRightUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                flowsTexture        = new Texture2D(_context.DirectX.Device, textureDescription);
                face.FlowsBottomUav = new UnorderedAccessView(_context.DirectX.Device, flowsTexture);
                flowsTexture.Dispose();

                _context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(0, face.TerrainUav);
                _context.DirectX.DeviceContext.ComputeShader.SetUnorderedAccessView(1, face.WaterUav);

                _context.DirectX.DeviceContext.ComputeShader.Set(initTerrain);
                computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.0f));
                _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1);

                _context.DirectX.DeviceContext.ComputeShader.Set(initWater);
                computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, 0, 0, 0.05f));
                _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize, TextureSize / BatchSize, 1);

                _context.DirectX.DeviceContext.ComputeShader.Set(initTerrain);
                computeBuffer.Update(new ComputeData(TextureSize - 1 - BatchSize, BatchSize / 2, BatchSize / 2, 0.5f));
                _context.DirectX.DeviceContext.Dispatch(TextureSize / BatchSize - 1, TextureSize / BatchSize - 1, 1);
            }

            _planeBuffer = new ConstantBuffer <PlaneData>(_context);

            initTerrain.Dispose();
            computeBuffer.Dispose();
        }
예제 #22
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RenderForm form = new RenderForm("Kinect Simple filtered 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);

            ComputeShader computeShader = ShaderCompiler.CompileFromFile <ComputeShader>(device, "ColoredPointCloudFilter.fx", "CS_Filter");

            VertexShader vertexShader = ShaderCompiler.CompileFromFile <VertexShader>(device, "ColoredPointCloudView.fx", "VS_Indirect");
            PixelShader  pixelShader  = ShaderCompiler.CompileFromFile <PixelShader>(device, "ColoredPointCloudView.fx", "PS");


            DX11NullGeometry nullGeom = new DX11NullGeometry(device);

            nullGeom.Topology = SharpDX.Direct3D.PrimitiveTopology.PointList;
            InstancedIndirectBuffer indirectDrawBuffer = new InstancedIndirectBuffer(device);


            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 uploadBodyIndex = false;
            bool uploadRgb       = false;

            CameraRGBFrameData         rgbFrame            = 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) => { rgbFrame.Update(sensor.CoordinateMapper, args.DepthData); depthToColorFrame.Update(sensor.CoordinateMapper, args.DepthData); uploadCamera = true; };

            BodyIndexFrameData                 bodyIndexFrame    = null;
            DynamicBodyIndexTexture            bodyIndexTexture  = new DynamicBodyIndexTexture(device);
            KinectSensorBodyIndexFrameProvider bodyIndexProvider = new KinectSensorBodyIndexFrameProvider(sensor);

            bodyIndexProvider.FrameReceived += (sender, args) => { bodyIndexFrame = args.FrameData; uploadBodyIndex = 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; };

            CounterPointCloudBuffer pointCloudBuffer = new CounterPointCloudBuffer(device);
            ColorPointCloudBuffer   colorBuffer      = new ColorPointCloudBuffer(device);

            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, rgbFrame);
                    depthToColorTexture.Copy(context.Context, depthToColorFrame);
                    uploadCamera = false;
                }

                if (uploadBodyIndex)
                {
                    bodyIndexTexture.Copy(context.Context, bodyIndexFrame);
                    uploadBodyIndex = false;
                }

                if (uploadRgb)
                {
                    colorTexture.Copy(context.Context, colorFrame);
                    uploadRgb = false;
                }

                //Prepare compute shader
                context.Context.ComputeShader.Set(computeShader);
                context.Context.ComputeShader.SetShaderResource(0, cameraTexture.ShaderView);
                context.Context.ComputeShader.SetShaderResource(1, bodyIndexTexture.RawView); //Set raw view here, we do not sample
                context.Context.ComputeShader.SetShaderResource(2, colorTexture.ShaderView);
                context.Context.ComputeShader.SetShaderResource(3, depthToColorTexture.ShaderView);

                context.Context.ComputeShader.SetSampler(0, device.SamplerStates.LinearClamp);

                context.Context.ComputeShader.SetUnorderedAccessView(0, pointCloudBuffer.UnorderedView, 0); //Don't forget to set count to 0
                context.Context.ComputeShader.SetUnorderedAccessView(1, colorBuffer.UnorderedView);

                context.Context.Dispatch(Consts.DepthWidth / 8, Consts.DepthHeight / 8, 1); //No iDivUp here, since it's not needed
                context.Context.ComputeShader.SetUnorderedAccessView(0, null);              //Make runtime happy, and if we don't unbind we can't set as srv
                context.Context.ComputeShader.SetUnorderedAccessView(1, null);
                context.Context.CopyStructureCount(indirectDrawBuffer.ArgumentBuffer, 0, pointCloudBuffer.UnorderedView);

                //Draw filter buffer
                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, pointCloudBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(1, colorBuffer.ShaderView);
                context.Context.VertexShader.SetConstantBuffer(0, cameraBuffer.Buffer);

                nullGeom.Bind(context, null);
                context.Context.DrawInstancedIndirect(indirectDrawBuffer.ArgumentBuffer, 0);

                //Make runtime happy
                context.Context.VertexShader.SetShaderResource(0, null);
                context.Context.VertexShader.SetShaderResource(1, null);

                context.RenderTargetStack.Pop();
                swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            });

            swapChain.Dispose();
            context.Dispose();
            device.Dispose();

            cameraBuffer.Dispose();
            cameraTexture.Dispose();
            bodyIndexTexture.Dispose();

            provider.Dispose();
            bodyIndexProvider.Dispose();

            pointCloudBuffer.Dispose();
            colorBuffer.Dispose();

            colorTexture.Dispose();
            colorProvider.Dispose();

            depthToColorFrame.Dispose();
            depthToColorTexture.Dispose();

            computeShader.Dispose();
            pixelShader.Dispose();
            vertexShader.Dispose();
            sensor.Close();
        }
 public void Dispose()
 {
     _computeShader.Dispose();
 }
예제 #24
0
        public SparseTwinIndex <float> ProcessFlow(SparseArray <float> O, SparseArray <float> D)
        {
            float[] o          = O.GetFlatData();
            float[] d          = D.GetFlatData();
            var     oLength    = o.Length;
            var     dLength    = d.Length;
            var     squareSize = oLength * dLength;

            float[] flows     = new float[squareSize];
            float[] residules = new float[dLength];
            GPU     gpu       = new GPU();
            string  programPath;
            var     codeBase = Assembly.GetEntryAssembly().CodeBase;

            try
            {
                programPath = Path.GetFullPath(codeBase);
            }
            catch
            {
                programPath = codeBase.Replace("file:///", String.Empty);
            }
            // Since the modules are always located in the ~/Modules subdirectory for XTMF,
            // we can just go in there to find the script
            ComputeShader gravityModelShader = null;
            Task          compile            = new Task(delegate()
            {
                gravityModelShader = gpu.CompileComputeShader(Path.Combine(Path.GetDirectoryName(programPath), "Modules", "GravityModel.hlsl"), "CSMain");
                gravityModelShader.NumberOfXThreads = oLength;
                gravityModelShader.NumberOfYThreads = 1;
                gravityModelShader.ThreadGroupSizeX = 64;
                gravityModelShader.ThreadGroupSizeY = 1;
            });

            compile.Start();
            GPUBuffer flowsBuffer          = gpu.CreateBuffer(squareSize, 4, true);
            GPUBuffer attractionStarBuffer = gpu.CreateBuffer(oLength, 4, true);
            GPUBuffer balancedBuffer       = gpu.CreateBuffer(2, 4, true);
            GPUBuffer productionBuffer     = gpu.CreateBuffer(dLength, 4, false);
            GPUBuffer attractionBuffer     = gpu.CreateBuffer(oLength, 4, false);
            GPUBuffer frictionBuffer       = gpu.CreateBuffer(squareSize, 4, false);
            GPUBuffer parameters           = gpu.CreateConstantBuffer(16);

            float[] balanced   = new float[] { 0, this.Epsilon };
            int     iterations = 0;
            var     step1      = new int[] { oLength, 0, this.MaxIterations };
            var     step2      = new int[] { oLength, 1, this.MaxIterations };

            compile.Wait();
            Stopwatch watch = new Stopwatch();

            watch.Start();
            FillAndLoadBuffers(o, d, Friction, gpu, gravityModelShader, flowsBuffer,
                               attractionStarBuffer, balancedBuffer, productionBuffer, attractionBuffer, frictionBuffer, parameters, balanced);
            if (gravityModelShader == null)
            {
                throw new XTMF.XTMFRuntimeException("Unable to compile the GravityModel GPU Kernel!");
            }
            iterations = Balance(gpu, gravityModelShader, balancedBuffer, parameters, balanced, iterations, step1, step2);
            gpu.Read(flowsBuffer, flows);
            gravityModelShader.RemoveAllBuffers();
            watch.Stop();
            using (StreamWriter writer = new StreamWriter("GPUPerf.txt", true))
            {
                writer.Write("Iteraions:");
                writer.WriteLine(iterations);
                writer.Write("Time(ms):");
                writer.WriteLine(watch.ElapsedMilliseconds);
            }
            gravityModelShader.Dispose();
            gpu.Release();
            return(BuildDistribution(O, D, oLength, flows));
        }