Пример #1
0
 public MultiRunGPUGravityModel(int length, Action<float> progressCallback = null, float epsilon = 0.8f, int maxIterations = 100)
 {
     var programPath = Assembly.GetEntryAssembly().CodeBase.Replace( "file:///", String.Empty );
     try
     {
         this.gpu = new GPU();
     }
     catch
     {
         throw new XTMFRuntimeException( "Unable to create a connection to the GPU, please make sure you are using a DirectX11+ card!" );
     }
     Task initialize = new Task( delegate()
         {
             this.length = length;
             this.ProgressCallback = progressCallback;
             this.Epsilon = epsilon;
             this.MaxIterations = maxIterations;
             CreateBuffers();
         } );
     initialize.Start();
     // while everything else is being initialized, compile the shader
     this.gravityModelShader = gpu.CompileComputeShader( Path.Combine( Path.GetDirectoryName( programPath ), "Modules", "GravityModel.hlsl" ), "CSMain" );
     initialize.Wait();
     if ( this.gravityModelShader == null )
     {
         throw new XTMFRuntimeException( "Unable to compile GravityModel.hlsl!" );
     }
 }
 public DirectComputePrefixScan(Device graphicsDevice)
 {
     this.graphicsDevice = graphicsDevice;
     computeScanExclusiveShared = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "ScanExclusiveShared", "cs_5_0", ShaderFlags.None, EffectFlags.None));
     computeScanExclusiveShared2 = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "ScanExclusiveShared2", "cs_5_0", ShaderFlags.None, EffectFlags.None));
     computeUniformUpdate = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "UniformUpdate", "cs_5_0", ShaderFlags.None, EffectFlags.None));
 }
Пример #3
0
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_ComputeShader = new ComputeShader(GameEnvironment.Device, Bytecode);

				m_Disposed = false;
			}
		}
 private void Awake()
 {
     if (!msb.isCreated)
     {
         msb = new MStringBuilder(30);
     }
     msb.Clear();
     msb.Add("Assets/BinaryData/Irradiance/");
     msb.Add(probeName);
     msb.Add(".mpipe");
     if (!System.IO.File.Exists(msb.str))
     {
         Debug.LogError("Probe: " + probeName + "read Error! ");
         Destroy(gameObject);
         return;
     }
     else
     {
         using (System.IO.FileStream fs = new System.IO.FileStream(msb.str, System.IO.FileMode.Open, System.IO.FileAccess.Read))
         {
             byte[] arr = GetByteArray(fs.Length);
             fs.Read(arr, 0, (int)fs.Length);
             int3 *res = (int3 *)arr.Ptr();
             resolution = *res;
             if (resolution.x * resolution.y * resolution.z * sizeof(float3x3) != fs.Length - sizeof(int3))
             {
                 Debug.LogError("Data size incorrect!");
                 Destroy(gameObject);
                 return;
             }
             NativeArray <float3x3> allDatas = new NativeArray <float3x3>(resolution.x * resolution.y * resolution.z, Allocator.Temp);
             UnsafeUtility.MemCpy(allDatas.GetUnsafePtr(), res + 1, sizeof(float3x3) * allDatas.Length);
             RenderTextureDescriptor desc = new RenderTextureDescriptor
             {
                 colorFormat       = RenderTextureFormat.ARGBHalf,
                 dimension         = TextureDimension.Tex3D,
                 enableRandomWrite = true,
                 width             = resolution.x,
                 height            = resolution.y,
                 volumeDepth       = resolution.z,
                 msaaSamples       = 1
             };
             src0             = new RenderTexture(desc);
             src1             = new RenderTexture(desc);
             desc.colorFormat = RenderTextureFormat.RHalf;
             src2             = new RenderTexture(desc);
             shBuffer         = new ComputeBuffer(allDatas.Length, sizeof(float3x3));
             shBuffer.SetData(allDatas);
             ComputeShader shader = resources.shaders.occlusionProbeCalculate;
             int3 *        arrPtr = (int3 *)resolutionArray.Ptr();
             *arrPtr = resolution;
             shader.SetBuffer(2, "_SHBuffer", shBuffer);
             shader.SetTexture(2, "_Src0", src0);
             shader.SetTexture(2, "_Src1", src1);
             shader.SetTexture(2, "_Src2", src2);
             shader.SetInts("_Resolution", resolutionArray);
             shader.Dispatch(2, Mathf.CeilToInt(resolution.x / 4f), Mathf.CeilToInt(resolution.y / 4f), Mathf.CeilToInt(resolution.z / 4f));
             shBuffer.Dispose();
             allDatas.Dispose();
         }
     }
 }
Пример #5
0
        public ComputeShader GetComputeShader( string bytecode )
        {
            ComputeShader	shader;

            if (!csDictionary.TryGetValue( bytecode, out shader ) ) {
                shader = new ComputeShader( device, bytecode );
                csDictionary.Add( bytecode, shader );
            }

            return shader;
        }
Пример #6
0
		private static void INTERNAL_CALL_SetVector(ComputeShader self, string name, ref Vector4 val){}
Пример #7
0
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            m_Device.Init( viewportPanel.Handle, false, true );
            m_Device.Clear( m_Device.DefaultTarget, new RendererManaged.float4( Color.SkyBlue, 1 ) );

            Reg( m_CS = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/Test/TestCompute.hlsl" ) ), "CS", null ) );
            Reg( m_PS = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/DisplayDistanceField.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ) );
            Reg( m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 0 ) );
            Reg( m_CB_Render = new ConstantBuffer<CB_Render>( m_Device, 8 ) );

            Build3DNoise();

            //////////////////////////////////////////////////////////////////////////
            // Photon Shooter
            Reg( m_CS_PhotonShooter = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/PhotonShooter.hlsl" ) ), "CS", null ) );
            Reg( m_CB_PhotonShooterInput = new ConstantBuffer<CB_PhotonShooterInput>( m_Device, 8 ) );
            Reg( m_SB_PhotonOut = new StructuredBuffer<SB_PhotonOut>( m_Device, PHOTONS_COUNT, true ) );
            BuildPhaseQuantileBuffer( new System.IO.FileInfo( @"Mie65536x2.float" ) );
            BuildRandomBuffer();

            //////////////////////////////////////////////////////////////////////////
            // Photons Splatter
            Reg( m_PS_PhotonSplatter = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/SplatPhoton.hlsl" ) ), VERTEX_FORMAT.P3, "VS", "GS", "PS", null ) );
            Reg( m_PS_PhotonSplatter_Intensity = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/SplatPhoton.hlsl" ) ), VERTEX_FORMAT.P3, "VS", "GS", "PS_Intensity", null ) );

            Reg( m_CB_SplatPhoton = new ConstantBuffer<CB_SplatPhoton>( m_Device, 8 ) );
            Reg( m_Tex_Photons = new Texture2D( m_Device, 512, 512, -6*4, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null ) );

            // Build a single point that will be instanced as many times as there are photons
            {
                ByteBuffer	Point = new ByteBuffer( 3*System.Runtime.InteropServices.Marshal.SizeOf(typeof(float3)) );
                Reg( m_Prim_Point = new Primitive( m_Device, 1, Point, null, Primitive.TOPOLOGY.POINT_LIST, VERTEX_FORMAT.P3 ) );
            }

            //////////////////////////////////////////////////////////////////////////
            // Photons Smoother
            Reg( m_PS_PhotonsSmooth = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/SmoothPhotons.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null ) );
            Reg( m_PS_PhotonsUnsharpMask = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/SmoothPhotons.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS_HiFreq", null ) );
            Reg( m_CB_SmoothPhotons = new ConstantBuffer<CB_SmoothPhotons>( m_Device, 8 ) );

            Reg( m_Tex_PhotonsSmooth = new Texture2D( m_Device, 512, 512, 6*4, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null ) );
            Reg( m_Tex_PhotonsHiFreq = new Texture2D( m_Device, 512, 512, 6*4, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null ) );

            //////////////////////////////////////////////////////////////////////////
            // Photons Renderer
            Reg( m_PS_RenderCube = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/DisplayPhotonCube.hlsl" ) ), VERTEX_FORMAT.P3N3, "VS", null, "PS", null ) );
            BuildCube();
            Reg( m_PS_RenderWorldCube = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/DisplayWorldCube.hlsl" ) ), VERTEX_FORMAT.P3N3, "VS", null, "PS", null ) );

            //////////////////////////////////////////////////////////////////////////
            // Photon Vectors Renderer
            Reg( m_PS_RenderPhotonVectors = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/DisplayPhotonVector.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null ) );
            Reg( m_CB_RenderPhotonVector = new ConstantBuffer<CB_RenderPhotonVector>( m_Device, 8 ) );
            {
                ByteBuffer	Line = VertexP3.FromArray( new VertexP3[] { new VertexP3() { P = new float3( 0, 0, 0 ) }, new VertexP3() { P = new float3( 1, 0, 0 ) } } );
                Reg( m_Prim_Line = new Primitive( m_Device, 2, Line, null, Primitive.TOPOLOGY.LINE_LIST, VERTEX_FORMAT.P3 ) );
            }

            // Create the camera manipulator
            m_CB_Camera.m.Camera2World = float4x4.Identity;
            UpdateCameraProjection( 60.0f * (float) Math.PI / 180.0f, (float) viewportPanel.Width / viewportPanel.Height, 0.1f, 100.0f );

            m_Manipulator.Attach( viewportPanel );
            m_Manipulator.CameraTransformChanged += new CameraManipulator.UpdateCameraTransformEventHandler( Manipulator_CameraTransformChanged );
            m_Manipulator.InitializeCamera( new float3( 0.0f, 0.0f, 4.0f ), new float3( 0, 0, 0 ), new float3( 0, 1, 0 ) );
        }
Пример #8
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try {
                m_Device.Init( m_viewerForm.Handle, false, true );

                m_viewerForm.Init();

                // Create our compute shaders
                #if !DEBUG || BISOU
                    using ( ScopedForceMaterialsLoadFromBinary scope = new ScopedForceMaterialsLoadFromBinary() )
                #endif
                {
                    m_CS_BilateralFilter = new ComputeShader( m_Device, new System.IO.FileInfo( "./Shaders/BilateralFiltering.hlsl" ), "CS", null );
                    m_CS_GenerateVisibilityMap = new ComputeShader( m_Device, new System.IO.FileInfo( "./Shaders/GenerateVisibilityMap.hlsl" ), "CS", null );
                    m_CS_GenerateTranslucencyMap = new ComputeShader( m_Device, new System.IO.FileInfo( "./Shaders/GenerateTranslucencyMap.hlsl" ), "CS", null );
                    m_CS_Helper_Normalize = new ComputeShader( m_Device, new System.IO.FileInfo( "./Shaders/Helpers.hlsl" ), "CS_Finalize", null );
                    m_CS_Helper_Mix = new ComputeShader( m_Device, new System.IO.FileInfo( "./Shaders/Helpers.hlsl" ), "CS_Mix", null );
                }
            // 				m_CS_BilateralFilter = new ComputeShader( m_Device, new ShaderBinaryFile( new System.IO.FileInfo( "./Shaders/Binary/BilateralFiltering.fxbin" ) ), "CS" );
            // 				m_CS_GenerateVisibilityMap = new ComputeShader( m_Device, new ShaderBinaryFile( new System.IO.FileInfo( "./Shaders/Binary/GenerateVisibilityMap.fxbin" ) ), "CS" );
            // 				m_CS_GenerateTranslucencyMap = new ComputeShader( m_Device, new ShaderBinaryFile( new System.IO.FileInfo( "./Shaders/Binary/GenerateTranslucencyMap.fxbin" ) ), "CS" );
            // 				m_CS_Helper_Normalize = new ComputeShader( m_Device, new ShaderBinaryFile( new System.IO.FileInfo( "./Shaders/Helpers.hlsl" ) ), "CS_Finalize" );
            // 				m_CS_Helper_Mix = new ComputeShader( m_Device, new ShaderBinaryFile( new System.IO.FileInfo( "./Shaders/Helpers.hlsl" ) ), "CS_Mix" );

                // Create our constant buffers
                m_CB_Generate = new ConstantBuffer<CBGenerate>( m_Device, 0 );
                m_CB_Visibility = new ConstantBuffer<CBVisibility>( m_Device, 0 );
                m_CB_Filter = new ConstantBuffer<CBFilter>( m_Device, 0 );
                m_CB_Helper = new ConstantBuffer<CBHelper>( m_Device, 0 );

                // Create the rays
                integerTrackbarControlRaysCount_SliderDragStop( integerTrackbarControlRaysCount, 0 );

            } catch ( Exception _e ) {
                MessageBox( "Failed to create DX11 device and default shaders:\r\n", _e );
                Close();
            }

            // LoadThicknessMap( new System.IO.FileInfo( "Leaf_thickness.tga" ) );
            // LoadNormalMap( new System.IO.FileInfo( "Leaf_normal.tga" ) );
            // LoadAlbedoMap( new System.IO.FileInfo( "Leaf_albedo.tga" ) );
            // LoadTransmittanceMap( new System.IO.FileInfo( "Leaf_transmittance.tga" ) );

            //LoadResults( new System.IO.FileInfo( "Leaf_thickness.tga" ) );
        }
Пример #9
0
 public void SetBuffer(ComputeShader compute, int kernel)
 {
     compute.SetBuffer(kernel, ShaderConst.BUF_LIFE, Lifes);
 }
Пример #10
0
 public abstract void Set(ComputeShader cs, string kernel = null);
Пример #11
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 );
					}
		}
Пример #12
0
        private Task InitGPUSupportAsync()
        {
            // Make device
            device = new Device(DriverType.Hardware, DeviceCreationFlags.Debug, FeatureLevel.Level_11_0);

            // Compile compute shader
            return Task.Run(() => computeShader = GPGPUHelper.LoadComputeShader(device, "GPGPU/FilterObjects.compute", "Filter", out shaderByteCode));
        }
Пример #13
0
        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, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                return;
            }

            try {
                m_Shader_RenderScene = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/RenderScene.hlsl" ) ), VERTEX_FORMAT.P3N3G3B3T2, "VS", null, "PS", null );
            } catch ( Exception _e ) {
                MessageBox.Show( "Shader \"RenderScene\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                m_Shader_RenderScene = null;
            }

            try {
                m_Shader_PostProcess = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/PostProcess.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
            } catch ( Exception _e ) {
                MessageBox.Show( "Shader \"PostProcess\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                m_Shader_PostProcess = null;
            }

            #if DEBUG && !BISOU
                try {
                    m_Shader_ClearAccumulator = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil_Accumulate.hlsl" ) ), "CS_Clear", null );
                    m_Shader_SplatDepthStencil = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil_Accumulate.hlsl" ) ), "CS_Accumulate", null );
                    m_Shader_Reproject = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil_Reproject.hlsl" ) ), "CS", null );
                    m_Shader_FinalizeSplat = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil_Finalize.hlsl" ) ), "CS", null );
                } catch ( Exception _e ) {
                    MessageBox.Show( "Shader \"SplatDepthStencil\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    m_Shader_ClearAccumulator = null;
                    m_Shader_SplatDepthStencil = null;
                    m_Shader_FinalizeSplat = null;
                }

                try {
                    m_Shader_BuildDistanceField[0] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/BuildDistanceField_X.hlsl" ) ), "CS", null );
                    m_Shader_BuildDistanceField[1] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/BuildDistanceField_Y.hlsl" ) ), "CS", null );
                    m_Shader_BuildDistanceField[2] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/BuildDistanceField_Z.hlsl" ) ), "CS", null );
                } catch ( Exception _e ) {
                    MessageBox.Show( "Shader \"BuildDistanceField\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    m_Shader_BuildDistanceField[0] = null;
                    m_Shader_BuildDistanceField[1] = null;
                    m_Shader_BuildDistanceField[2] = null;
                }
            #else
                try {
                    m_Shader_ClearAccumulator = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/SplatDepthStencil_Accumulate.hlsl" ), "CS_Clear" );
                    m_Shader_SplatDepthStencil = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/SplatDepthStencil_Accumulate.hlsl" ), "CS_Accumulate" );
                    m_Shader_Reproject = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/SplatDepthStencil_Reproject.hlsl" ), "CS" );
                    m_Shader_FinalizeSplat = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/SplatDepthStencil_Finalize.hlsl" ), "CS" );
                } catch ( Exception _e ) {
                    MessageBox.Show( "Shader \"SplatDepthStencil\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    m_Shader_ClearAccumulator = null;
                    m_Shader_SplatDepthStencil = null;
                    m_Shader_Reproject = null;
                    m_Shader_FinalizeSplat = null;
                }

                try {
                    m_Shader_BuildDistanceField[0] = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "./Shaders/Binary/BuildDistanceField_X.fxbin" ), "CS" );
                    m_Shader_BuildDistanceField[1] = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "./Shaders/Binary/BuildDistanceField_Y.fxbin" ), "CS" );
                    m_Shader_BuildDistanceField[2] = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "./Shaders/Binary/BuildDistanceField_Z.fxbin" ), "CS" );
                } catch ( Exception _e ) {
                    MessageBox.Show( "Shader \"BuildDistanceField\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                    m_Shader_BuildDistanceField[0] = null;
                    m_Shader_BuildDistanceField[1] = null;
                    m_Shader_BuildDistanceField[2] = null;
                }
            #endif

            m_CB_Main = new ConstantBuffer<CB_Main>( m_Device, 0 );
            m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 1 );
            m_CB_Object = new ConstantBuffer<CB_Object>( m_Device, 2 );

            BuildPrimitives();

            // Allocate texture
            //			m_Tex_TempTarget = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 2, 1, PIXEL_FORMAT.RGBA8_UNORM_sRGB, false, false, null );
            m_Tex_TempTarget = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 2, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, false, null );

            // Allocate several 3D textures for depth-stencil reduction
            m_Tex_TempDepthAccumulatorRG = new Texture3D( m_Device, VOXELS_COUNT, VOXELS_COUNT, VOXELS_COUNT, 1, PIXEL_FORMAT.R32_UINT, false, true, null );
            m_Tex_TempDepthAccumulatorBA = new Texture3D( m_Device, VOXELS_COUNT, VOXELS_COUNT, VOXELS_COUNT, 1, PIXEL_FORMAT.R32_UINT, false, true, null );
            m_Tex_SplatDepthStencil[0] = new Texture3D( m_Device, VOXELS_COUNT, VOXELS_COUNT, VOXELS_COUNT, 1, PIXEL_FORMAT.RGBA8_UNORM, false, true, null );
            m_Tex_SplatDepthStencil[1] = new Texture3D( m_Device, VOXELS_COUNT, VOXELS_COUNT, VOXELS_COUNT, 1, PIXEL_FORMAT.RGBA8_UNORM, false, true, null );
            m_Tex_DistanceField[0] = new Texture3D( m_Device, VOXELS_COUNT, VOXELS_COUNT, VOXELS_COUNT, 6, PIXEL_FORMAT.R16_FLOAT, false, true, null );
            m_Tex_DistanceField[1] = new Texture3D( m_Device, VOXELS_COUNT, VOXELS_COUNT, VOXELS_COUNT, 6, PIXEL_FORMAT.R16_FLOAT, false, true, null );

            m_Device.Clear( m_Tex_SplatDepthStencil[0], float4.Zero );
            m_Device.Clear( m_Tex_SplatDepthStencil[1], float4.Zero );

            // 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 );
        }
Пример #14
0
        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, "Project 4D Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
                return;
            }

            m_CS_Simulator = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "./Shaders/Simulator.hlsl" ) ), "CS", null );
            m_CS_Project4D = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "./Shaders/Project4D.hlsl" ) ), "CS", null );
            m_PS_Display = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "./Shaders/Display.hlsl" ) ), VERTEX_FORMAT.T2, "VS", null, "PS", null );

            m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 1 );
            m_CB_Camera4D = new ConstantBuffer<CB_Camera4D>( m_Device, 2 );
            m_CB_Simulation = new ConstantBuffer<CB_Simulation>( m_Device, 3 );

            {
                VertexT2[]	Vertices = new VertexT2[4] {
                    new VertexT2() { UV = new float2( -1.0f, 1.0f ) },
                    new VertexT2() { UV = new float2( -1.0f, -1.0f ) },
                    new VertexT2() { UV = new float2(  1.0f, 1.0f ) },
                    new VertexT2() { UV = new float2(  1.0f, -1.0f ) },
                };
                m_PrimQuad = new Primitive( m_Device, 4, VertexT2.FromArray( Vertices ), null, Primitive.TOPOLOGY.TRIANGLE_STRIP, VERTEX_FORMAT.T2 );
            }

            /////////////////////////////////////////////////////////////////////////////////////
            // Create and fill the structured buffers with initial points lying on the surface of a hypersphere
            m_SB_Velocities4D = new StructuredBuffer<float4>( m_Device, POINTS_COUNT, true );
            m_SB_Points4D[0] = new StructuredBuffer<float4>( m_Device, POINTS_COUNT, true );
            m_SB_Points4D[1] = new StructuredBuffer<float4>( m_Device, POINTS_COUNT, true );
            m_SB_Points2D = new StructuredBuffer<float4>( m_Device, POINTS_COUNT, false );

            buttonInit_Click( buttonInit, EventArgs.Empty );

            /////////////////////////////////////////////////////////////////////////////////////
            // Setup camera
            m_Camera.CreatePerspectiveCamera( (float) (60.0 * Math.PI / 180.0), (float) panelOutput.Width / panelOutput.Height, 0.01f, 10.0f );
            m_Manipulator.Attach( panelOutput, m_Camera );
            m_Manipulator.InitializeCamera( new float3( 0, 0, 2 ), new float3( 0, 0, 0 ), float3.UnitY );
        }
Пример #15
0
        unsafe static void EVSMBlurMoments(RenderShadowsParameters parameters,
                                           RTHandle atlasRenderTexture,
                                           RTHandle[] momentAtlasRenderTextures,
                                           CommandBuffer cmd)
        {
            ComputeShader shadowBlurMomentsCS = parameters.evsmShadowBlurMomentsCS;

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderEVSMShadowMaps)))
            {
                int generateAndBlurMomentsKernel = shadowBlurMomentsCS.FindKernel("ConvertAndBlur");
                int blurMomentsKernel            = shadowBlurMomentsCS.FindKernel("Blur");
                int copyMomentsKernel            = shadowBlurMomentsCS.FindKernel("CopyMoments");

                cmd.SetComputeTextureParam(shadowBlurMomentsCS, generateAndBlurMomentsKernel, HDShaderIDs._DepthTexture, atlasRenderTexture);
                cmd.SetComputeVectorArrayParam(shadowBlurMomentsCS, HDShaderIDs._BlurWeightsStorage, evsmBlurWeights);

                // We need to store in which of the two moment texture a request will have its last version stored in for a final patch up at the end.
                var finalAtlasTexture = stackalloc int[parameters.shadowRequests.Count];

                int requestIdx = 0;
                foreach (var shadowRequest in parameters.shadowRequests)
                {
                    using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderEVSMShadowMapsBlur)))
                    {
                        int downsampledWidth  = Mathf.CeilToInt(shadowRequest.atlasViewport.width * 0.5f);
                        int downsampledHeight = Mathf.CeilToInt(shadowRequest.atlasViewport.height * 0.5f);

                        Vector2 DstRectOffset = new Vector2(shadowRequest.atlasViewport.min.x * 0.5f, shadowRequest.atlasViewport.min.y * 0.5f);

                        cmd.SetComputeTextureParam(shadowBlurMomentsCS, generateAndBlurMomentsKernel, HDShaderIDs._OutputTexture, momentAtlasRenderTextures[0]);
                        cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._SrcRect, new Vector4(shadowRequest.atlasViewport.min.x, shadowRequest.atlasViewport.min.y, shadowRequest.atlasViewport.width, shadowRequest.atlasViewport.height));
                        cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._DstRect, new Vector4(DstRectOffset.x, DstRectOffset.y, 1.0f / atlasRenderTexture.rt.width, 1.0f / atlasRenderTexture.rt.height));
                        cmd.SetComputeFloatParam(shadowBlurMomentsCS, HDShaderIDs._EVSMExponent, shadowRequest.evsmParams.x);

                        int dispatchSizeX = ((int)downsampledWidth + 7) / 8;
                        int dispatchSizeY = ((int)downsampledHeight + 7) / 8;

                        cmd.DispatchCompute(shadowBlurMomentsCS, generateAndBlurMomentsKernel, dispatchSizeX, dispatchSizeY, 1);

                        int currentAtlasMomentSurface = 0;

                        RTHandle GetMomentRT()
                        {
                            return(momentAtlasRenderTextures[currentAtlasMomentSurface]);
                        }

                        RTHandle GetMomentRTCopy()
                        {
                            return(momentAtlasRenderTextures[(currentAtlasMomentSurface + 1) & 1]);
                        }

                        cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._SrcRect, new Vector4(DstRectOffset.x, DstRectOffset.y, downsampledWidth, downsampledHeight));
                        for (int i = 0; i < shadowRequest.evsmParams.w; ++i)
                        {
                            currentAtlasMomentSurface = (currentAtlasMomentSurface + 1) & 1;
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, blurMomentsKernel, HDShaderIDs._InputTexture, GetMomentRTCopy());
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, blurMomentsKernel, HDShaderIDs._OutputTexture, GetMomentRT());

                            cmd.DispatchCompute(shadowBlurMomentsCS, blurMomentsKernel, dispatchSizeX, dispatchSizeY, 1);
                        }

                        finalAtlasTexture[requestIdx++] = currentAtlasMomentSurface;
                    }
                }

                // We patch up the atlas with the requests that, due to different count of blur passes, remained in the copy
                for (int i = 0; i < parameters.shadowRequests.Count; ++i)
                {
                    if (finalAtlasTexture[i] != 0)
                    {
                        using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderEVSMShadowMapsCopyToAtlas)))
                        {
                            var shadowRequest     = parameters.shadowRequests[i];
                            int downsampledWidth  = Mathf.CeilToInt(shadowRequest.atlasViewport.width * 0.5f);
                            int downsampledHeight = Mathf.CeilToInt(shadowRequest.atlasViewport.height * 0.5f);

                            cmd.SetComputeVectorParam(shadowBlurMomentsCS, HDShaderIDs._SrcRect, new Vector4(shadowRequest.atlasViewport.min.x * 0.5f, shadowRequest.atlasViewport.min.y * 0.5f, downsampledWidth, downsampledHeight));
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, copyMomentsKernel, HDShaderIDs._InputTexture, momentAtlasRenderTextures[1]);
                            cmd.SetComputeTextureParam(shadowBlurMomentsCS, copyMomentsKernel, HDShaderIDs._OutputTexture, momentAtlasRenderTextures[0]);

                            int dispatchSizeX = ((int)downsampledWidth + 7) / 8;
                            int dispatchSizeY = ((int)downsampledHeight + 7) / 8;

                            cmd.DispatchCompute(shadowBlurMomentsCS, copyMomentsKernel, dispatchSizeX, dispatchSizeY, 1);
                        }
                    }
                }
            }
        }
Пример #16
0
 public void GeneragteHizTexture(CommandBuffer cmd, RenderTargetIdentifier source, ComputeShader HizCS)
 {
     m_temporalTexHandle = new int[m_miplevel];
     for (int i = 0; i < m_miplevel; i++)
     {
         m_temporalTexHandle[i] = Shader.PropertyToID("tempory depth buffer" + i);
         int temporalsize = m_size >> i;
         temporalsize = Mathf.Max(temporalsize, 1);
         RenderTextureDescriptor temp_desc = new RenderTextureDescriptor()
         {
             width             = temporalsize,
             height            = temporalsize,
             autoGenerateMips  = false,
             useMipMap         = true,
             enableRandomWrite = true,
             colorFormat       = RenderTextureFormat.RFloat,
             dimension         = TextureDimension.Tex2D,
             bindMS            = false,
             msaaSamples       = 1,
         };
         cmd.GetTemporaryRT(m_temporalTexHandle[i], temp_desc, FilterMode.Point);
         cmd.SetComputeFloatParams(HizCS, "gRcpBufferDim", new float[] { 1.0f / temporalsize, 1.0f / temporalsize });
         if (i == 0)
         {
             // cmd.Blit(source, m_temporalTexHandle[i], hizGenerateMeterial, (int)Pass.Blit);
             int blitKernel = HizCS.FindKernel("Blit");
             cmd.SetComputeTextureParam(HizCS, blitKernel, "Input", source);
             cmd.SetComputeTextureParam(HizCS, blitKernel, "Output", m_temporalTexHandle[i]);
             cmd.DispatchCompute(HizCS, blitKernel, temporalsize / 8, temporalsize / 8, 1);
         }
         else
         {
             int gatherKernel = HizCS.FindKernel("Gather");
             cmd.SetComputeTextureParam(HizCS, gatherKernel, "Input", m_temporalTexHandle[i - 1]);
             cmd.SetComputeTextureParam(HizCS, gatherKernel, "Output", m_temporalTexHandle[i]);
             int groupSize = Mathf.Max(1, temporalsize / 8);
             cmd.DispatchCompute(HizCS, gatherKernel, groupSize, groupSize, 1);
             cmd.ReleaseTemporaryRT(m_temporalTexHandle[i - 1]);
         }
         cmd.CopyTexture(m_temporalTexHandle[i], 0, 0, m_hizTexture, 0, i);
     }
     cmd.ReleaseTemporaryRT(m_temporalTexHandle[m_miplevel - 1]);
 }
Пример #17
0
    public void Start()
    {
        // Verify that the particleCount is valid.
        if (particleCount < THREAD_GROUPS)
        {
            Debug.LogWarning("The GPU will spawn more thread groups than needed due to low particle count.");
        }

        if (particleCount < 1)
        {
            Debug.LogError("Particle count must be greater than zero.");
            return;
        }

        /* Instantiate the compute shader and find the kernel. Due to a Unity 2017.x bug, we must
         * instantiate the compute shader as a resource if we want to use multiple instances of
         * it in the same scene. */
        compute       = (ComputeShader)Instantiate(Resources.Load("particleCompute"));
        computeKernel = compute.FindKernel("CSMain");

        // Create a quad mesh to render our particles
        GameObject tmp = GameObject.CreatePrimitive(PrimitiveType.Quad);

        quad = tmp.GetComponent <MeshFilter>().mesh;
        Destroy(tmp);

        // create the Particle array, load it into the particle buffer and upload it to the GPU
        Particle[] particles = new Particle[particleCount];
        for (int i = 0; i < particleCount; i++)
        {
            Vector3 pos = Vector3.zero;
            Vector3 vel = Vector3.zero;
            GenerateRandomParameters(ref pos, ref vel);
            particles[i].position         = pos;
            particles[i].originalPosition = pos;
            particles[i].velocity         = vel;
            particles[i].originalVelocity = vel;
            particles[i].lifetime         = Random.Range(minimumLifetime, maximumLifetime);

            /* the initial age is set < 0 to allow us to set the particle rate, rather than
             * each particle spawning at the same time. this allows us to "reuse" dead particles
             * by resetting them, rather than removing them and adding new ones. */
            particles[i].age = -1f * Mathf.Floor(i / (float)particlesPer) * timeStep;
        }
        particleBuffer = new ComputeBuffer(particleCount, PARTICLE_SIZE);
        particleBuffer.SetData(particles);
        compute.SetBuffer(computeKernel, "particleBuffer", particleBuffer);
        particleMaterial.SetBuffer("particleBuffer", particleBuffer);

        // create the sphere collider array, load it into the buffer and upload it to the GPU
        if (sphereColliders.Length > 0)
        {
            sphereColliderBuffer = new ComputeBuffer(sphereColliders.Length, SPHERE_COLLIDER_SIZE);
            sphereColliderBuffer.SetData(sphereColliders);
            compute.SetBuffer(computeKernel, "sphereColliderBuffer", sphereColliderBuffer);
        }
        compute.SetInt("sphereColliderCount", sphereColliders.Length);



        // create the box collider array, load it into the buffer and upload it to the GPU
        if (boxColliders.Length > 0)
        {
            boxColliderBuffer = new ComputeBuffer(boxColliders.Length, BOX_COLLIDER_SIZE);
            boxColliderBuffer.SetData(boxColliders);
            compute.SetBuffer(computeKernel, "boxColliderBuffer", boxColliderBuffer);
        }
        compute.SetInt("boxColliderCount", boxColliders.Length);

        // warmup the shaders
        Shader.WarmupAllShaders();


        // create the Args array, and load it into the Arguments buffer, and save it for the Update() loop
        uint[] args = new uint[5] {
            (uint)quad.GetIndexCount(0), (uint)particleCount,
            (uint)quad.GetIndexStart(0), (uint)quad.GetBaseVertex(0), 0
        };
        argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments);
        argsBuffer.SetData(args);
    }
Пример #18
0
 public PathTracer()
 {
     TracerShader = new ComputeShader("PathTracer.compute.glsl");
     LightsSSBO = new ShaderStorageBuffer();
 }
 // Set an integer parameter.
 public void SetComputeIntParam(ComputeShader computeShader, string name, int val)
 {
     SetComputeIntParam(computeShader, Shader.PropertyToID(name), val);
 }
        private void Initialize()
        {
            constantBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = (int)Math.Ceiling(Marshal.SizeOf(typeof(DirectComputeConstantBuffer)) / 16.0) * 16,
                Usage = ResourceUsage.Dynamic
            });

            computePositionWeightNoiseCube = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "PositionWeightNoiseCube", "cs_5_0", ShaderFlags.None, EffectFlags.None));
            computeNormalAmbient = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "NormalAmbient", "cs_5_0", ShaderFlags.None, EffectFlags.None));
            computeMarchingCubesCases = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "MarchingCubesCases", "cs_5_0", ShaderFlags.None, EffectFlags.None));
            computeMarchingCubesVertices = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "MarchingCubesVertices", "cs_5_0", ShaderFlags.None, EffectFlags.None));
            computePositionWeightNoiseCubeWarp = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "PositionWeightNoiseCubeWarp", "cs_5_0", ShaderFlags.None, EffectFlags.None));
            computePositionWeightFormula = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "PositionWeightFormula", "cs_5_0", ShaderFlags.None, EffectFlags.None));

            prefixScan = new DirectComputePrefixScan(graphicsDevice);
        }
 // Set a vector parameter.
 public void SetComputeVectorParam(ComputeShader computeShader, string name, Vector4 val)
 {
     SetComputeVectorParam(computeShader, Shader.PropertyToID(name), val);
 }
Пример #22
0
 private static void FillAndLoadBuffers(float[] o, float[] d, float[] Friction, GPU gpu, ComputeShader gravityModelShader, GPUBuffer flowsBuffer, GPUBuffer attractionStarBuffer, GPUBuffer balancedBuffer, GPUBuffer productionBuffer, GPUBuffer attractionBuffer, GPUBuffer frictionBuffer, GPUBuffer parameters, float[] balanced)
 {
     gpu.Write( balancedBuffer, balanced );
     gpu.Write( productionBuffer, o );
     gpu.Write( attractionBuffer, d );
     gpu.Write( attractionStarBuffer, d );
     gpu.Write( frictionBuffer, Friction );
     // The order matters, needs to be the same as in the shader code!!!
     gravityModelShader.AddBuffer( parameters );
     gravityModelShader.AddBuffer( flowsBuffer );
     gravityModelShader.AddBuffer( attractionStarBuffer );
     gravityModelShader.AddBuffer( balancedBuffer );
     gravityModelShader.AddBuffer( productionBuffer );
     gravityModelShader.AddBuffer( attractionBuffer );
     gravityModelShader.AddBuffer( frictionBuffer );
 }
 // Set a vector array parameter.
 public void SetComputeVectorArrayParam(ComputeShader computeShader, string name, Vector4[] values)
 {
     SetComputeVectorArrayParam(computeShader, Shader.PropertyToID(name), values);
 }
Пример #24
0
        protected override void LoadResources()
        {
            CreateRenderTargets();

            camera = new Camera(WindowWidth, WindowHeight);

            // Fill vertex buffer.
            var generator = new Random();
            var randomPoints = new List<Vector3>();
            for (int i = 0; i < 1024; i++)
            {
                var rp = new Vector3
                (
                    (float)(generator.NextDouble() - 0.5) * 100.0f,
                    (float)(generator.NextDouble() - 0.5) * 100.0f,
                    (float)(generator.NextDouble() - 0.5) * 500.0f
                );
                randomPoints.Add(rp);
            }
            using (var stream = new DataStream(randomPoints.ToArray(), true, true))
            {
                positionBuffer = new Buffer(Device, stream, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = randomPoints.Count * 4 * 3,
                    Usage = ResourceUsage.Default
                });
            }

            streamOutBuffer = new Buffer(Device, new BufferDescription()
            {
                BindFlags = BindFlags.StreamOutput | BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = randomPoints.Count * Marshal.SizeOf(typeof(StreamOutData)) * 4,
                Usage = ResourceUsage.Default
            });

            // Compile shaders.
            var bytecode = ShaderBytecode.CompileFromFile("Shaders\\PointSystem.fx", "fx_5_0", ShaderFlags.Debug | ShaderFlags.OptimizationLevel0, EffectFlags.None);
            effect = new Effect(Device, bytecode);

            modelView = effect.GetVariableByName("ModelView").AsMatrix();
            inverseView = effect.GetVariableByName("InvView").AsMatrix();
            projection = effect.GetVariableByName("Projection").AsMatrix();
            modelViewProjection = effect.GetVariableByName("ModelViewProjection").AsMatrix();

            var particleTechnique = effect.GetTechniqueByName("RenderParticles");
            var depthPass = particleTechnique.GetPassByName("DepthPass");
            var densityPass = particleTechnique.GetPassByName("DensityPass");

            layout = new InputLayout(Device, depthPass.Description.Signature, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)
            });
            streamLayout = new InputLayout(Device, densityPass.Description.Signature, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0, 1),
                new InputElement("TEXCOORD", 1, Format.R32G32B32_Float, 0, 2)
            });

            var defines = new[]
            {
                new ShaderMacro("BLK_SIZE", "128")
            };
            bytecode = ShaderBytecode.CompileFromFile("Shaders\\BilateralFilter.hlsl", "CSBilateralH", "cs_5_0", ShaderFlags.Debug | ShaderFlags.OptimizationLevel0, EffectFlags.None, defines, null);
            blurH = new ComputeShader(Device, bytecode);

            bytecode = ShaderBytecode.CompileFromFile("Shaders\\BilateralFilter.hlsl", "CSBilateralV", "cs_5_0", ShaderFlags.Debug | ShaderFlags.OptimizationLevel0, EffectFlags.None, defines, null);
            blurV = new ComputeShader(Device, bytecode);

            bindings = new[]
            {
                new VertexBufferBinding(positionBuffer, 12, 0),
            };
            streamOutBindings = new[]
            {
                new StreamOutputBufferBinding(streamOutBuffer, 0)
            };
            streamInBindings = new[]
            {
                new VertexBufferBinding(streamOutBuffer, 36, 0),
            };
        }
 // Set a matrix parameter.
 public void SetComputeMatrixParam(ComputeShader computeShader, string name, Matrix4x4 val)
 {
     SetComputeMatrixParam(computeShader, Shader.PropertyToID(name), val);
 }
Пример #26
0
 protected virtual void Dispose(bool userCalled)
 {
     if ( this.gravityModelShader != null )
     {
         this.gravityModelShader.Dispose();
         this.gravityModelShader = null;
     }
     if ( this.gpu != null )
     {
         this.gpu.Dispose();
         this.gpu = null;
     }
 }
 // Set a matrix array parameter.
 public void SetComputeMatrixArrayParam(ComputeShader computeShader, string name, Matrix4x4[] values)
 {
     SetComputeMatrixArrayParam(computeShader, Shader.PropertyToID(name), values);
 }
Пример #28
0
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            try
            {
                m_Device.Init( panelOutput.Handle, false, false );
            }
            catch ( Exception _e )
            {
                m_Device = null;
                MessageBox.Show( "Failed to initialize DX device!\n\n" + _e.Message, "ShaderToy", MessageBoxButtons.OK, MessageBoxIcon.Error );
                return;
            }

            BuildQuad();

            try {
            //				m_ShaderDownsample = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/Downsample.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                m_ShaderLinearizeDepthCS = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/LinearizeCS.hlsl" ) ), "CS", null );
                m_ShaderDownsampleCS = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/DownsampleCS2.hlsl" ) ), "CS", null );
                m_ShaderPostProcess = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/PostProcess.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );

            //				m_Shader = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/Airlight.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
            //				m_Shader = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/VoronoiInterpolation.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
            //				m_Shader = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/Room.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );

            #if true
                m_Shader = Shader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/Binary/TestMSBRDF2.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS" );
                m_Shader_Glass = Shader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "Shaders/TestMSBRDF_Glass.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS" );
            #else
                m_Shader = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/TestMSBRDF2.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                m_Shader_Glass = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/TestMSBRDF_Glass.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
            #endif
            }
            catch ( Exception _e ) {
                MessageBox.Show( "Shader failed to compile!\n\n" + _e.Message, "ShaderToy", MessageBoxButtons.OK, MessageBoxIcon.Error );
                m_Shader = null;
            }

            m_CB_Main = new ConstantBuffer<CB_Main>( m_Device, 0 );
            m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 1 );
            m_CB_Downsample = new ConstantBuffer<CB_Downsample>( m_Device, 2 );
            m_CB_PostProcess = new ConstantBuffer<CB_PostProcess>( m_Device, 2 );

            m_Tex_TempBuffer = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 2, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, null );
            m_Tex_TempBuffer2 = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 2, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, false, null );

            // Build linear and downsampled depth buffers
            m_Tex_LinearDepth = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 1, 1, PIXEL_FORMAT.R32_FLOAT, false, true, null );
            int	safeWidth = ((panelOutput.Width + 15) & ~15) >> 1;
            int	safeHeight = ((panelOutput.Height + 15) & ~15) >> 1;
            m_Tex_DownsampledDepth = new Texture2D( m_Device, safeWidth, safeHeight, 1, 4, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null );

            // Initialize Voronoï neighbor positions
            m_CB_Main.m._MainPosition = new float2( 0.0f, 0.0f );
            m_CB_Main.m._NeighborPosition0 = new float2( -0.4f, -0.6f );
            m_CB_Main.m._NeighborPosition1 = new float2( 0.6f, -0.4f );
            m_CB_Main.m._NeighborPosition2 = new float2( -0.2f, 0.8f );
            m_CB_Main.m._NeighborPosition3 = new float2( -0.6f, 0.14f );
            m_CB_Main.m._MousePosition.Set( 0.5f, 0.5f );

            // 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, 0.5f, 2.5f ), new float3( 0, 0.5f, 0 ), float3.UnitY );
            m_Manipulator.InitializeCamera( new float3( 0.91f, 0.11f, 3.3f ), new float3( 0.91f, 0.11f, 3.3f ), float3.UnitY );

            // Start game time
            m_Ticks2Seconds = 1.0 / System.Diagnostics.Stopwatch.Frequency;
            m_StopWatch.Start();
            m_StartGameTime = GetGameTime();
        }
 // Set multiple consecutive integer parameters at once.
 public void SetComputeIntParams(ComputeShader computeShader, string name, params int[] values)
 {
     Internal_SetComputeInts(computeShader, Shader.PropertyToID(name), values);
 }
Пример #30
0
        public void init(IntTensorFactory _factory,
                         int[] _shape,
                         int[] _data = null,
                         ComputeBuffer _dataBuffer  = null,
                         ComputeBuffer _shapeBuffer = null,
                         ComputeShader _shader      = null,
                         bool _copyData             = true,
                         bool _dataOnGpu            = false,
                         bool _autograd             = false,
                         bool _keepgrads            = false,
                         string _creation_op        = null)
        {
            factory     = _factory;
            dataOnGpu   = _dataOnGpu;
            creation_op = _creation_op;

            // First: check that shape is valid.
            if (_shape == null || _shape.Length == 0)
            {
                throw new InvalidOperationException("Tensor shape can't be an empty array.");
            }

            // Second: since shape is valid, let's save it
            shape = (int[])_shape.Clone();

            setStridesAndCheckShape();

            // Third: let's see what kind of data we've got. We should either have
            // a GPU ComputeBuffer or a data[] object.
            if (_data != null && _shapeBuffer == null && _dataBuffer == null)
            {
                InitCpu(_data: _data, _copyData: _copyData);
            }
            else if (_dataBuffer != null && _shapeBuffer != null && SystemInfo.supportsComputeShaders && _data == null)
            {
                // looks like we have GPU data being passed in... initialize a GPU tensor.

                InitGpu(_shader, _dataBuffer, _shapeBuffer, _copyData);
            }
            else
            {
                // no data seems to be passed in... or its got missing stuff

                // if CPU works... go with that
                if (_data != null)
                {
                    InitCpu(_data, _copyData);
                }
                else if (_dataBuffer != null && _shader != null)
                {
                    if (SystemInfo.supportsComputeShaders)
                    {
                        // seems i'm just missing a shape buffer - no biggie
                        shapeBuffer = new ComputeBuffer(shape.Length, sizeof(int));
                        shapeBuffer.SetData(shape);

                        InitGpu(_shader, _dataBuffer, _shapeBuffer, _copyData);
                        initShaderKernels();
                    }
                    else
                    {
                        throw new InvalidOperationException(
                                  "You seem to be trying to create a GPU tensor without having access to a GPU...");
                    }
                }
                else
                {
                    // nothing else seems to work - i suppose i'm just supposed to initialize an empty tensor.
                    long acc = 1;
                    for (var i = shape.Length - 1; i >= 0; --i)
                    {
                        acc *= shape[i];
                    }

                    if (_dataOnGpu)
                    {
                        _shapeBuffer = new ComputeBuffer(shape.Length, sizeof(int));
                        _shapeBuffer.SetData(shape);

                        _dataBuffer = new ComputeBuffer(size, sizeof(float));

                        InitGpu(_shader: _shader, _dataBuffer: _dataBuffer, _shapeBuffer: _shapeBuffer,
                                _copyData: false);
                        initShaderKernels();
                        this.Zero_();
                    }
                    else
                    {
                        _data = new int[acc];

                        InitCpu(_data, false);
                    }
                }
            }

            // Lastly: let's set the ID of the tensor.
            // IDEs might show a warning, but ref and volatile seems to be working with Interlocked API.

            #pragma warning disable 420
            id = System.Threading.Interlocked.Increment(ref nCreated);

            if (SystemInfo.supportsComputeShaders && shader == null)
            {
                shader = factory.GetShader();
                initShaderKernels();
            }
        }
 public void SetComputeIntParams(ComputeShader computeShader, int nameID, params int[] values)
 {
     Internal_SetComputeInts(computeShader, nameID, values);
 }
Пример #32
0
        static void IMBlurMoment(RenderShadowsParameters parameters,
                                 RTHandle atlas,
                                 RTHandle atlasMoment,
                                 RTHandle intermediateSummedAreaTexture,
                                 RTHandle summedAreaTexture,
                                 CommandBuffer cmd)
        {
            // If the target kernel is not available
            ComputeShader momentCS = parameters.imShadowBlurMomentsCS;

            if (momentCS == null)
            {
                return;
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RenderMomentShadowMaps)))
            {
                int computeMomentKernel        = momentCS.FindKernel("ComputeMomentShadows");
                int summedAreaHorizontalKernel = momentCS.FindKernel("MomentSummedAreaTableHorizontal");
                int summedAreaVerticalKernel   = momentCS.FindKernel("MomentSummedAreaTableVertical");

                // First of all let's clear the moment shadow map
                CoreUtils.SetRenderTarget(cmd, atlasMoment, ClearFlag.Color, Color.black);
                CoreUtils.SetRenderTarget(cmd, intermediateSummedAreaTexture, ClearFlag.Color, Color.black);
                CoreUtils.SetRenderTarget(cmd, summedAreaTexture, ClearFlag.Color, Color.black);


                // Alright, so the thing here is that for every sub-shadow map of the atlas, we need to generate the moment shadow map
                foreach (var shadowRequest in parameters.shadowRequests)
                {
                    // Let's bind the resources of this
                    cmd.SetComputeTextureParam(momentCS, computeMomentKernel, HDShaderIDs._ShadowmapAtlas, atlas);
                    cmd.SetComputeTextureParam(momentCS, computeMomentKernel, HDShaderIDs._MomentShadowAtlas, atlasMoment);
                    cmd.SetComputeVectorParam(momentCS, HDShaderIDs._MomentShadowmapSlotST, new Vector4(shadowRequest.atlasViewport.width, shadowRequest.atlasViewport.height, shadowRequest.atlasViewport.min.x, shadowRequest.atlasViewport.min.y));

                    // First of all we need to compute the moments
                    int numTilesX = Math.Max((int)shadowRequest.atlasViewport.width / 8, 1);
                    int numTilesY = Math.Max((int)shadowRequest.atlasViewport.height / 8, 1);
                    cmd.DispatchCompute(momentCS, computeMomentKernel, numTilesX, numTilesY, 1);

                    // Do the horizontal pass of the summed area table
                    cmd.SetComputeTextureParam(momentCS, summedAreaHorizontalKernel, HDShaderIDs._SummedAreaTableInputFloat, atlasMoment);
                    cmd.SetComputeTextureParam(momentCS, summedAreaHorizontalKernel, HDShaderIDs._SummedAreaTableOutputInt, intermediateSummedAreaTexture);
                    cmd.SetComputeFloatParam(momentCS, HDShaderIDs._IMSKernelSize, shadowRequest.kernelSize);
                    cmd.SetComputeVectorParam(momentCS, HDShaderIDs._MomentShadowmapSize, new Vector2((float)atlasMoment.referenceSize.x, (float)atlasMoment.referenceSize.y));

                    int numLines = Math.Max((int)shadowRequest.atlasViewport.width / 64, 1);
                    cmd.DispatchCompute(momentCS, summedAreaHorizontalKernel, numLines, 1, 1);

                    // Do the horizontal pass of the summed area table
                    cmd.SetComputeTextureParam(momentCS, summedAreaVerticalKernel, HDShaderIDs._SummedAreaTableInputInt, intermediateSummedAreaTexture);
                    cmd.SetComputeTextureParam(momentCS, summedAreaVerticalKernel, HDShaderIDs._SummedAreaTableOutputInt, summedAreaTexture);
                    cmd.SetComputeVectorParam(momentCS, HDShaderIDs._MomentShadowmapSize, new Vector2((float)atlasMoment.referenceSize.x, (float)atlasMoment.referenceSize.y));
                    cmd.SetComputeFloatParam(momentCS, HDShaderIDs._IMSKernelSize, shadowRequest.kernelSize);

                    int numColumns = Math.Max((int)shadowRequest.atlasViewport.height / 64, 1);
                    cmd.DispatchCompute(momentCS, summedAreaVerticalKernel, numColumns, 1, 1);

                    // Push the global texture
                    cmd.SetGlobalTexture(HDShaderIDs._SummedAreaTableInputInt, summedAreaTexture);
                }
            }
        }
 public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, int nameID, RenderTargetIdentifier rt)
 {
     Internal_SetComputeTextureParam(computeShader, kernelIndex, nameID, ref rt, 0, RenderTextureSubElement.Default);
 }
Пример #34
0
        /// <summary>
        /// Dispatches compute work.
        /// </summary>
        /// <param name="state">Current GPU state</param>
        /// <param name="argument">Method call argument</param>
        public void Dispatch(GpuState state, int argument)
        {
            uint qmdAddress = (uint)state.Get <int>(MethodOffset.DispatchParamsAddress);

            var qmd = _context.MemoryAccessor.Read <ComputeQmd>((ulong)qmdAddress << 8);

            GpuVa shaderBaseAddress = state.Get <GpuVa>(MethodOffset.ShaderBaseAddress);

            ulong shaderGpuVa = shaderBaseAddress.Pack() + (uint)qmd.ProgramOffset;

            int localMemorySize = qmd.ShaderLocalMemoryLowSize + qmd.ShaderLocalMemoryHighSize;

            int sharedMemorySize = Math.Min(qmd.SharedMemorySize, _context.Capabilities.MaximumComputeSharedMemorySize);

            ComputeShader cs = ShaderCache.GetComputeShader(
                shaderGpuVa,
                qmd.CtaThreadDimension0,
                qmd.CtaThreadDimension1,
                qmd.CtaThreadDimension2,
                localMemorySize,
                sharedMemorySize);

            _context.Renderer.Pipeline.SetProgram(cs.HostProgram);

            var samplerPool = state.Get <PoolState>(MethodOffset.SamplerPoolState);

            TextureManager.SetComputeSamplerPool(samplerPool.Address.Pack(), samplerPool.MaximumId, qmd.SamplerIndex);

            var texturePool = state.Get <PoolState>(MethodOffset.TexturePoolState);

            TextureManager.SetComputeTexturePool(texturePool.Address.Pack(), texturePool.MaximumId);

            TextureManager.SetComputeTextureBufferIndex(state.Get <int>(MethodOffset.TextureBufferIndex));

            ShaderProgramInfo info = cs.Shader.Program.Info;

            uint sbEnableMask = 0;
            uint ubEnableMask = 0;

            for (int index = 0; index < Constants.TotalCpUniformBuffers; index++)
            {
                if (!qmd.ConstantBufferValid(index))
                {
                    continue;
                }

                ubEnableMask |= 1u << index;

                ulong gpuVa = (uint)qmd.ConstantBufferAddrLower(index) | (ulong)qmd.ConstantBufferAddrUpper(index) << 32;
                ulong size  = (ulong)qmd.ConstantBufferSize(index);

                BufferManager.SetComputeUniformBuffer(index, gpuVa, size);
            }

            for (int index = 0; index < info.CBuffers.Count; index++)
            {
                BufferDescriptor cb = info.CBuffers[index];

                // NVN uses the "hardware" constant buffer for anything that is less than 8,
                // and those are already bound above.
                // Anything greater than or equal to 8 uses the emulated constant buffers.
                // They are emulated using global memory loads.
                if (cb.Slot < 8)
                {
                    continue;
                }

                ubEnableMask |= 1u << cb.Slot;

                ulong cbDescAddress = BufferManager.GetComputeUniformBufferAddress(0);

                int cbDescOffset = 0x260 + cb.Slot * 0x10;

                cbDescAddress += (ulong)cbDescOffset;

                ReadOnlySpan <byte> cbDescriptorData = _context.PhysicalMemory.GetSpan(cbDescAddress, 0x10);

                SbDescriptor cbDescriptor = MemoryMarshal.Cast <byte, SbDescriptor>(cbDescriptorData)[0];

                BufferManager.SetComputeUniformBuffer(cb.Slot, cbDescriptor.PackAddress(), (uint)cbDescriptor.Size);
            }

            for (int index = 0; index < info.SBuffers.Count; index++)
            {
                BufferDescriptor sb = info.SBuffers[index];

                sbEnableMask |= 1u << sb.Slot;

                ulong sbDescAddress = BufferManager.GetComputeUniformBufferAddress(0);

                int sbDescOffset = 0x310 + sb.Slot * 0x10;

                sbDescAddress += (ulong)sbDescOffset;

                ReadOnlySpan <byte> sbDescriptorData = _context.PhysicalMemory.GetSpan(sbDescAddress, 0x10);

                SbDescriptor sbDescriptor = MemoryMarshal.Cast <byte, SbDescriptor>(sbDescriptorData)[0];

                BufferManager.SetComputeStorageBuffer(sb.Slot, sbDescriptor.PackAddress(), (uint)sbDescriptor.Size);
            }

            ubEnableMask = 0;

            for (int index = 0; index < info.CBuffers.Count; index++)
            {
                ubEnableMask |= 1u << info.CBuffers[index].Slot;
            }

            BufferManager.SetComputeStorageBufferEnableMask(sbEnableMask);
            BufferManager.SetComputeUniformBufferEnableMask(ubEnableMask);

            var textureBindings = new TextureBindingInfo[info.Textures.Count];

            for (int index = 0; index < info.Textures.Count; index++)
            {
                var descriptor = info.Textures[index];

                Target target = GetTarget(descriptor.Type);

                if (descriptor.IsBindless)
                {
                    textureBindings[index] = new TextureBindingInfo(target, descriptor.CbufOffset, descriptor.CbufSlot);
                }
                else
                {
                    textureBindings[index] = new TextureBindingInfo(target, descriptor.HandleIndex);
                }
            }

            TextureManager.SetComputeTextures(textureBindings);

            var imageBindings = new TextureBindingInfo[info.Images.Count];

            for (int index = 0; index < info.Images.Count; index++)
            {
                var descriptor = info.Images[index];

                Target target = GetTarget(descriptor.Type);

                imageBindings[index] = new TextureBindingInfo(target, descriptor.HandleIndex);
            }

            TextureManager.SetComputeImages(imageBindings);

            BufferManager.CommitComputeBindings();
            TextureManager.CommitComputeBindings();

            _context.Renderer.Pipeline.DispatchCompute(
                qmd.CtaRasterWidth,
                qmd.CtaRasterHeight,
                qmd.CtaRasterDepth);

            UpdateShaderState(state);
        }
 public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, string name, RenderTargetIdentifier rt, int mipLevel, RenderTextureSubElement element)
 {
     Internal_SetComputeTextureParam(computeShader, kernelIndex, Shader.PropertyToID(name), ref rt, mipLevel, element);
 }
Пример #36
0
        internal DeviceChild GetOrCompileShader(EffectShaderType shaderType, int index, int soRasterizedStream, StreamOutputElement[] soElements, out string profileError)
        {
            DeviceChild shader = null;

            profileError = null;
            lock (sync)
            {
                shader = compiledShadersGroup[(int)shaderType][index];
                if (shader == null)
                {
                    if (RegisteredShaders[index].Level > graphicsDevice.Features.Level)
                    {
                        profileError = string.Format("{0}", RegisteredShaders[index].Level);
                        return(null);
                    }

                    var bytecodeRaw = RegisteredShaders[index].Bytecode;
                    switch (shaderType)
                    {
                    case EffectShaderType.Vertex:
                        shader = new VertexShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Domain:
                        shader = new DomainShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Hull:
                        shader = new HullShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Geometry:
                        if (soElements != null)
                        {
                            // Calculate the strides
                            var soStrides = new List <int>();
                            foreach (var streamOutputElement in soElements)
                            {
                                for (int i = soStrides.Count; i < (streamOutputElement.Stream + 1); i++)
                                {
                                    soStrides.Add(0);
                                }

                                soStrides[streamOutputElement.Stream] += streamOutputElement.ComponentCount * sizeof(float);
                            }
                            shader = new GeometryShader(graphicsDevice, bytecodeRaw, soElements, soStrides.ToArray(), soRasterizedStream);
                        }
                        else
                        {
                            shader = new GeometryShader(graphicsDevice, bytecodeRaw);
                        }
                        break;

                    case EffectShaderType.Pixel:
                        shader = new PixelShader(graphicsDevice, bytecodeRaw);
                        break;

                    case EffectShaderType.Compute:
                        shader = new ComputeShader(graphicsDevice, bytecodeRaw);
                        break;
                    }
                    compiledShadersGroup[(int)shaderType][index] = ToDispose(shader);
                }
            }
            return(shader);
        }
 public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, int nameID, RenderTargetIdentifier rt, int mipLevel, RenderTextureSubElement element)
 {
     Internal_SetComputeTextureParam(computeShader, kernelIndex, nameID, ref rt, mipLevel, element);
 }
Пример #38
0
        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 );
                return;
            }

            m_CB_Main = new ConstantBuffer<CB_Main>( m_Device, 0 );
            m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 1 );
            m_CB_ComputeBeckmann = new ConstantBuffer<CB_ComputeBeckmann>( m_Device, 10 );
            m_CB_RayTrace = new ConstantBuffer<CB_RayTrace>( m_Device, 10 );
            m_CB_Finalize = new ConstantBuffer<CB_Finalize>( m_Device, 10 );
            m_CB_Render = new ConstantBuffer<CB_Render>( m_Device, 10 );
            m_CB_RenderLobe = new ConstantBuffer<CB_RenderLobe>( m_Device, 10 );
            m_CB_RenderCylinder = new ConstantBuffer<CB_RenderCylinder>( m_Device, 10 );

            try {
                m_Shader_ComputeBeckmannSurface = new ComputeShader( m_Device, new ShaderFile( new FileInfo( "Shaders/ComputeBeckmannSurface.hlsl" ) ), "CS", null );
                m_Shader_RayTraceSurface_Conductor = new ComputeShader( m_Device, new ShaderFile( new FileInfo( "Shaders/RayTraceSurface.hlsl" ) ), "CS_Conductor", null );
                m_Shader_RayTraceSurface_Dielectric = new ComputeShader( m_Device, new ShaderFile( new FileInfo( "Shaders/RayTraceSurface.hlsl" ) ), "CS_Dielectric", null );
                m_Shader_RayTraceSurface_Diffuse = new ComputeShader( m_Device, new ShaderFile( new FileInfo( "Shaders/RayTraceSurface.hlsl" ) ), "CS_Diffuse", null );
                m_Shader_AccumulateOutgoingDirections = new ComputeShader( m_Device, new ShaderFile( new FileInfo( "Shaders/AccumulateOutgoingDirections.hlsl" ) ), "CS", null );
                m_Shader_FinalizeOutgoingDirections = new ComputeShader( m_Device, new ShaderFile( new FileInfo( "Shaders/AccumulateOutgoingDirections.hlsl" ) ), "CS_Finalize", null );
                m_Shader_RenderHeightField = new Shader( m_Device, new ShaderFile( new FileInfo( "Shaders/RenderHeightField.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null );
                m_Shader_RenderLobe = new Shader( m_Device, new ShaderFile( new FileInfo( "Shaders/RenderLobe.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null );
                m_Shader_RenderCylinder = new Shader( m_Device, new ShaderFile( new FileInfo( "Shaders/RenderCylinder.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null );
            } catch ( Exception _e ) {
                MessageBox( "Shader \"RenderHeightField\" failed to compile!\n\n" + _e.Message );
            }

            BuildPrimHeightfield();
            BuildPrimLobe();
            BuildPrimCylinder();

            m_SB_Beckmann = new StructuredBuffer<SB_Beckmann>( m_Device, 1024, true );

            BuildRandomTexture();
            BuildBeckmannSurfaceTexture( floatTrackbarControlBeckmannRoughness.Value );

            m_Tex_OutgoingDirections_Reflected = new Texture2D( m_Device, HEIGHTFIELD_SIZE, HEIGHTFIELD_SIZE, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, true, null );
            m_Tex_OutgoingDirections_Transmitted = new Texture2D( m_Device, HEIGHTFIELD_SIZE, HEIGHTFIELD_SIZE, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, true, null );
            m_Tex_LobeHistogram_Reflected_Decimal = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_UINT, false, true, null );
            m_Tex_LobeHistogram_Reflected_Integer = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_UINT, false, true, null );
            m_Tex_LobeHistogram_Transmitted_Decimal = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_UINT, false, true, null );
            m_Tex_LobeHistogram_Transmitted_Integer = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_UINT, false, true, null );
            m_Tex_LobeHistogram_Reflected = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_FLOAT, false, true, null );
            m_Tex_LobeHistogram_Transmitted = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_FLOAT, false, true, null );
            m_Tex_LobeHistogram_CPU = new Texture2D( m_Device, LOBES_COUNT_PHI, LOBES_COUNT_THETA, MAX_SCATTERING_ORDER, 1, PIXEL_FORMAT.R32_FLOAT, true, false, 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, 3, 6 ), new float3( 0, 2, 0 ), float3.UnitY );

            // Perform a simple initial trace
            try {
                buttonRayTrace_Click( buttonRayTrace, EventArgs.Empty );
            } catch ( Exception ) {
                m_Device = null;
            }
        }
 public void SetComputeBufferParam(ComputeShader computeShader, int kernelIndex, string name, ComputeBuffer buffer)
 {
     SetComputeBufferParam(computeShader, kernelIndex, Shader.PropertyToID(name), buffer);
 }
        private void Generate(ComputeShader computePositionWeight, int width, int height, int depth)
        {
            int count = width * height * depth;
            int widthD = width - 1;
            int heightD = height - 1;
            int depthD = depth - 1;
            int countD = widthD * heightD * depthD;

            int nearestW = NearestPowerOfTwo(widthD);
            int nearestH = NearestPowerOfTwo(heightD);
            int nearestD = NearestPowerOfTwo(depthD);
            int nearestCount = nearestW * nearestH * nearestD;

            Vector3 gridDim = new Vector3((float)Math.Ceiling(width / 8.0f), (float)Math.Ceiling(height / 8.0f), (float)Math.Ceiling(depth / 8.0f));
            Vector3 gridDimD = new Vector3((float)Math.Ceiling(widthD / 8.0f), (float)Math.Ceiling(heightD / 8.0f), (float)Math.Ceiling(depthD / 8.0f));

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width = 16,
                Height = 16,
                Depth = 16,
                Seed = (int)DateTime.Now.Ticks
            };

            DirectComputeNoiseCube noiseCube = new DirectComputeNoiseCube(graphicsDevice);

            ShaderResourceView noiseSRV = noiseCube.GenerateNoiseTexture(constantBuffer, constantBufferContainer);

            Buffer voxelsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(Voxel)) * count,
                StructureByteStride = Marshal.SizeOf(typeof(Voxel))
            });

            UnorderedAccessView voxelsUAV = new UnorderedAccessView(graphicsDevice, voxelsBuffer);

            constantBufferContainer = new DirectComputeConstantBuffer()
            {
                Width = width,
                Height = height,
                Depth = depth,
                AmbientRayWidth = container.Settings.AmbientRayWidth,
                AmbientSamplesCount = container.Settings.AmbientSamplesCount,
                NearestWidth = nearestW,
                NearestHeight = nearestH,
                NearestDepth = nearestD
            };

            DataBox data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
            data.Data.Write<DirectComputeConstantBuffer>(constantBufferContainer);
            graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computePositionWeight);
            graphicsDevice.ImmediateContext.ComputeShader.SetConstantBuffer(constantBuffer, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(voxelsUAV, 0);
            graphicsDevice.ImmediateContext.ComputeShader.SetShaderResource(noiseSRV, 0);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeNormalAmbient);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDim.X, (int)gridDim.Y, (int)gridDim.Z);

            Buffer offsetsBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * countD,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView offsetsUAV = new UnorderedAccessView(graphicsDevice, offsetsBuffer);

            Buffer trisCountBuffer = new Buffer(graphicsDevice, new BufferDescription()
            {
                BindFlags = BindFlags.UnorderedAccess,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.StructuredBuffer,
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(int)) * nearestCount,
                StructureByteStride = Marshal.SizeOf(typeof(int))
            });

            UnorderedAccessView trisCountUAV = new UnorderedAccessView(graphicsDevice, trisCountBuffer);

            graphicsDevice.ImmediateContext.ClearUnorderedAccessView(trisCountUAV, new int[] { 0, 0, 0, 0 });

            graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesCases);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(offsetsUAV, 1);
            graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);

            graphicsDevice.ImmediateContext.Dispatch((int)gridDimD.X, (int)gridDimD.Y, (int)gridDimD.Z);

            UnorderedAccessView prefixSumsUAV = prefixScan.PrefixSumArray(constantBuffer, trisCountUAV);

            int lastTrisCount = DirectComputeBufferHelper.CopyBuffer<int>(graphicsDevice, trisCountBuffer, nearestCount - 1, 1)[0];

            int lastPrefixSum = DirectComputeBufferHelper.CopyBuffer<int>(graphicsDevice, prefixSumsUAV.Resource, nearestCount - 1, 1)[0];

            int totalVerticesCount = (lastTrisCount + lastPrefixSum) * 3;

            if (totalVerticesCount > 0)
            {
                if (container.Geometry != null)
                    container.Geometry.Dispose();

                container.VertexCount = totalVerticesCount;

                container.Geometry = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    Usage = ResourceUsage.Default
                });

                Buffer verticesBuffer = new Buffer(graphicsDevice, new BufferDescription()
                {
                    BindFlags = BindFlags.UnorderedAccess,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.StructuredBuffer,
                    Usage = ResourceUsage.Default,
                    SizeInBytes = Marshal.SizeOf(typeof(VoxelMeshVertex)) * totalVerticesCount,
                    StructureByteStride = Marshal.SizeOf(typeof(VoxelMeshVertex))
                });

                UnorderedAccessView verticesUAV = new UnorderedAccessView(graphicsDevice, verticesBuffer);

                constantBufferContainer = new DirectComputeConstantBuffer()
                {
                    Width = width,
                    Height = height,
                    Depth = depth,
                    NearestWidth = nearestW,
                    NearestHeight = nearestH,
                    NearestDepth = nearestD
                };

                data = graphicsDevice.ImmediateContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, MapFlags.None);
                data.Data.Write<DirectComputeConstantBuffer>(constantBufferContainer);
                graphicsDevice.ImmediateContext.UnmapSubresource(constantBuffer, 0);

                graphicsDevice.ImmediateContext.ComputeShader.Set(computeMarchingCubesVertices);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(trisCountUAV, 2);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(prefixSumsUAV, 3);
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(verticesUAV, 5);

                graphicsDevice.ImmediateContext.Dispatch((int)gridDimD.X, (int)gridDimD.Y, (int)gridDimD.Z);

                graphicsDevice.ImmediateContext.CopyResource(verticesBuffer, container.Geometry);

                verticesUAV.Dispose();
                verticesBuffer.Dispose();
            }
            else
            {
                container.VertexCount = 0;

                if (container.Geometry != null)
                    container.Geometry.Dispose();
            }

            for (int i = 0; i <= 5; i++)
            {
                graphicsDevice.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, i);
            }

            prefixSumsUAV.Resource.Dispose();
            prefixSumsUAV.Dispose();
            noiseCube.Dispose();
            noiseSRV.Resource.Dispose();
            noiseSRV.Dispose();
            voxelsBuffer.Dispose();
            voxelsUAV.Dispose();
            offsetsBuffer.Dispose();
            offsetsUAV.Dispose();
            trisCountBuffer.Dispose();
            trisCountUAV.Dispose();
        }
 // Execute a compute shader.
 public void DispatchCompute(ComputeShader computeShader, int kernelIndex, int threadGroupsX, int threadGroupsY, int threadGroupsZ)
 {
     Internal_DispatchCompute(computeShader, kernelIndex, threadGroupsX, threadGroupsY, threadGroupsZ);
 }
Пример #42
0
        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 ShaderFile( new System.IO.FileInfo( "Shaders/UpdateHeightMap.hlsl" ) ), "CS", null );
                m_shader_GenerateDensity = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/GenerateDensity.hlsl" ) ), "CS", null );
                m_Shader_ClearAccumulator = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/TracePhotons.hlsl" ) ), "CS_ClearAccumulator", null );
                m_Shader_InitPhotons = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/TracePhotons.hlsl" ) ), "CS_InitPhotons", null );
                m_Shader_TracePhotons = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/TracePhotons.hlsl" ) ), "CS_TracePhotons", null );

                m_Shader_RenderRoom = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/RenderRoom.hlsl" ) ), VERTEX_FORMAT.P3N3G3T2, "VS", null, "PS", null );
                m_Shader_RenderSphere = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/RenderSphere.hlsl" ) ), VERTEX_FORMAT.P3N3G3T2, "VS", null, "PS", null );
                m_Shader_RayMarcher = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/RayMarch.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                m_Shader_PostProcess = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/PostProcess.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );

            //				m_ShaderDownsample = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/Downsample.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
            }
            catch ( Exception _e ) {
                MessageBox.Show( "Shader failed to compile!\n\n" + _e.Message, "ShaderToy", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }

            int	W = panelOutput.Width;
            int	H = 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, 2 );

            m_Tex_TempBackBuffer = new Texture2D( m_Device, W, H, 1, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, false, null );
            m_Tex_HeightMap = new Texture2D( m_Device, HEIGHTMAP_SIZE, HEIGHTMAP_SIZE, 1, 1,  PIXEL_FORMAT.RG16_FLOAT, false, true, null );
            m_Tex_Scattering = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 2, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, false, null );
            m_Tex_VolumeDensity = new Texture3D( m_Device, VOLUME_SIZE, VOLUME_SIZE, VOLUME_SIZE, 1, PIXEL_FORMAT.R8_UNORM, false, true, null );;
            m_Tex_AccumPhotonCube = new Texture2D( m_Device, 256, 256, -6, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null );;
            m_Tex_AccumPhoton3D = new Texture3D( m_Device, VOLUME_SIZE, VOLUME_SIZE, VOLUME_SIZE, 1, PIXEL_FORMAT.R32_UINT, false, true, null );;
            BuildNoiseTextures();

            // 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();
        }
 public void DispatchCompute(ComputeShader computeShader, int kernelIndex, ComputeBuffer indirectBuffer, uint argsOffset)
 {
     Internal_DispatchComputeIndirect(computeShader, kernelIndex, indirectBuffer, argsOffset);
 }
Пример #44
0
		protected override void OnLoad( EventArgs e )
		{
			base.OnLoad( e );

			m_Device.Init( viewportPanel.Handle, false, true );
			m_Device.Clear( m_Device.DefaultTarget, new RendererManaged.float4( Color.SkyBlue, 1 ) );

			Reg( m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 0 ) );
			Reg( m_CB_Render = new ConstantBuffer<CB_Render>( m_Device, 8 ) );

			//////////////////////////////////////////////////////////////////////////
			// Photon Shooter
#if DEBUG_INFOS
			ShaderMacro[]	Macros = new ShaderMacro[] {
				new ShaderMacro( "DEBUG", "" )
			};
#else
			ShaderMacro[]	Macros = null;
#endif


			Reg( m_CS_PhotonShooter = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/LayeredRenderer/PhotonShooter.hlsl" ) ), "CS", Macros ) );
			Reg( m_CB_PhotonShooterInput = new ConstantBuffer<CB_PhotonShooterInput>( m_Device, 8 ) );

			BuildPhaseQuantileBuffer( new System.IO.FileInfo( @"Mie65536x2.float" ) );
			BuildRandomBuffer();

			Reg( m_SB_Photons = new StructuredBuffer<SB_Photon>( m_Device, PHOTONS_COUNT, true ) );

			Reg( m_SB_PhotonLayerIndices = new StructuredBuffer<uint>( m_Device, PHOTONS_COUNT, true ) );
			Reg( m_SB_ProcessedPhotonsCounter = new StructuredBuffer<uint>( m_Device, 1, true ) );

			Build3DDensityField();


			//////////////////////////////////////////////////////////////////////////
			// Photons Splatter
			Reg( m_PS_PhotonSplatter = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/LayeredRenderer/SplatPhoton.hlsl" ) ), VERTEX_FORMAT.P3, "VS", "GS", "PS", Macros ) );

			Reg( m_CB_SplatPhoton = new ConstantBuffer<CB_SplatPhoton>( m_Device, 8 ) );

			Reg( m_Tex_PhotonLayers_Flux = new Texture3D( m_Device, 512, 512, LAYERS_COUNT+1, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null ) );
			Reg( m_Tex_PhotonLayers_Direction = new Texture3D( m_Device, 512, 512, LAYERS_COUNT+1, 1, PIXEL_FORMAT.RGBA16_FLOAT, false, true, null ) );

			// Build a single point that will be instanced as many times as there are photons
			{
				ByteBuffer	Point = new ByteBuffer( 3*System.Runtime.InteropServices.Marshal.SizeOf(typeof(float3)) );
				Reg( m_Prim_Point = new Primitive( m_Device, 1, Point, null, Primitive.TOPOLOGY.POINT_LIST, VERTEX_FORMAT.P3 ) );
			}


			//////////////////////////////////////////////////////////////////////////
			// Photons Renderer
			Reg( m_PS_RenderLayer = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/LayeredRenderer/DisplayPhotonLayer.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null ) );
			Reg( m_PS_RenderWorldCube = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/DisplayWorldCube.hlsl" ) ), VERTEX_FORMAT.P3N3, "VS", null, "PS", null ) );

			BuildQuad();
			BuildCube();


// 			//////////////////////////////////////////////////////////////////////////
// 			// Photon Vectors Renderer
// 			Reg( m_PS_RenderPhotonVectors = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( @"Shaders/CanonicalCubeRenderer/DisplayPhotonVector.hlsl" ) ), VERTEX_FORMAT.P3, "VS", null, "PS", null ) );
// 			Reg( m_CB_RenderPhotonVector = new ConstantBuffer<CB_RenderPhotonVector>( m_Device, 8 ) );
// 			{
// 				ByteBuffer	Line = VertexP3.FromArray( new VertexP3[] { new VertexP3() { P = new float3( 0, 0, 0 ) }, new VertexP3() { P = new float3( 1, 0, 0 ) } } );
// 				Reg( m_Prim_Line = new Primitive( m_Device, 2, Line, null, Primitive.TOPOLOGY.LINE_LIST, VERTEX_FORMAT.P3 ) );
// 			}

			// Create the camera manipulator
			m_CB_Camera.m.Camera2World = float4x4.Identity;
			UpdateCameraProjection( 60.0f * (float) Math.PI / 180.0f, (float) viewportPanel.Width / viewportPanel.Height, 0.1f, 100.0f );

			m_Manipulator.Attach( viewportPanel );
			m_Manipulator.CameraTransformChanged += new CameraManipulator.UpdateCameraTransformEventHandler( Manipulator_CameraTransformChanged );
			m_Manipulator.InitializeCamera( new float3( 0.0f, 0.0f, 4.0f ), new float3( 0, 0, 0 ), new float3( 0, 1, 0 ) );

	
			integerTrackbarControlLayerDisplayStart.RangeMax = LAYERS_COUNT;
			integerTrackbarControlLayerDisplayStart.VisibleRangeMax = LAYERS_COUNT;
			integerTrackbarControlLayerDisplayEnd.RangeMax = LAYERS_COUNT+1;
			integerTrackbarControlLayerDisplayEnd.VisibleRangeMax = LAYERS_COUNT+1;
			integerTrackbarControlLayerDisplayEnd.Value = LAYERS_COUNT+1;
		}
    private bool CreateCoordMapperShader(KinectInterop.SensorData sensorData, bool bColor2Depth)
    {
        if (_depthCameraIntrinsics == null || _colorCameraIntrinsics == null || _coordinateMapper == null)
        {
            return(false);
        }

        System.Numerics.Matrix4x4?matrix = !bColor2Depth ? _coordinateMapper.DepthToColorMatrix : _coordinateMapper.ColorToDepthMatrix;
        if (_coordMapperShader == null)
        {
            _coordMapperShader = matrix.HasValue ? Resources.Load("CoordMapper") as ComputeShader : null;
        }

        if (_coordMapperShader)
        {
            _depth2colorKernel = _coordMapperShader.FindKernel("MapDepthFrame2ColorFrame");
            _color2depthKernel = _coordMapperShader.FindKernel("MapColorSpace2DepthFrame");

            float[] depthFocalLength      = new float[] { _depthCameraIntrinsics.FocalLengthX, _depthCameraIntrinsics.FocalLengthY };
            float[] depthPrincipalPoint   = new float[] { _depthCameraIntrinsics.PrincipalPointX, _depthCameraIntrinsics.PrincipalPointY };
            float[] depthRadialDistortion = new float[] { _depthCameraIntrinsics.RadialDistortionSecondOrder, _depthCameraIntrinsics.RadialDistortionFourthOrder, _depthCameraIntrinsics.RadialDistortionSixthOrder };

            _coordMapperShader.SetFloats("depthFocalLength", depthFocalLength);
            _coordMapperShader.SetFloats("depthPrincipalPoint", depthPrincipalPoint);
            _coordMapperShader.SetFloats("depthRadialDistortion", depthRadialDistortion);

            float[] colorFocalLength      = new float[] { _colorCameraIntrinsics.FocalLengthX, _colorCameraIntrinsics.FocalLengthY };
            float[] colorPrincipalPoint   = new float[] { _colorCameraIntrinsics.PrincipalPointX, _colorCameraIntrinsics.PrincipalPointY };
            float[] colorRadialDistortion = new float[] { _colorCameraIntrinsics.RadialDistortionSecondOrder, _colorCameraIntrinsics.RadialDistortionFourthOrder, _colorCameraIntrinsics.RadialDistortionSixthOrder };

            _coordMapperShader.SetFloats("colorFocalLength", colorFocalLength);
            _coordMapperShader.SetFloats("colorPrincipalPoint", colorPrincipalPoint);
            _coordMapperShader.SetFloats("colorRadialDistortion", colorRadialDistortion);

            float[] space2spaceMat = new float[] {
                matrix.Value.M11, matrix.Value.M12, matrix.Value.M13, matrix.Value.M14,
                matrix.Value.M21, matrix.Value.M22, matrix.Value.M23, matrix.Value.M24,
                matrix.Value.M31, matrix.Value.M32, matrix.Value.M33, matrix.Value.M34,
                matrix.Value.M41, matrix.Value.M42, matrix.Value.M43, matrix.Value.M44
            };

            if (!bColor2Depth)
            {
                _coordMapperShader.SetFloats("depth2colorMat", space2spaceMat);
            }
            else
            {
                _coordMapperShader.SetFloats("color2depthMat", space2spaceMat);
            }

            // compute buffers
            int depthImageLength = sensorData.depthImageWidth * sensorData.depthImageHeight;

            if (_depthDepthValuesBuf == null)
            {
                _depthDepthValuesBuf = new ComputeBuffer(depthImageLength, sizeof(int));
                _coordMapperShader.SetBuffer(_depth2colorKernel, "depthDepthValues", _depthDepthValuesBuf);
            }

            if (!bColor2Depth)
            {
                _depthPlaneCoordsBuf = new ComputeBuffer(depthImageLength, 2 * sizeof(float));
                _colorPlaneCoordsBuf = new ComputeBuffer(depthImageLength, 2 * sizeof(float));

                // set plane coords
                Vector2[] depthPlaneCoords = new Vector2[depthImageLength];
                for (int dy = 0, di = 0; dy < sensorData.depthImageHeight; dy++)
                {
                    for (int dx = 0; dx < sensorData.depthImageWidth; dx++)
                    {
                        depthPlaneCoords[di] = new Vector2(dx, dy);
                        di++;
                    }
                }

                _depthPlaneCoordsBuf.SetData(depthPlaneCoords);
                _coordMapperShader.SetBuffer(_depth2colorKernel, "depthPlaneCoords", _depthPlaneCoordsBuf);
                _coordMapperShader.SetBuffer(_depth2colorKernel, "colorPlaneCoords", _colorPlaneCoordsBuf);
            }
            else
            {
                int colorImageLength = sensorData.colorImageWidth * sensorData.colorImageHeight;

                _colorSpaceCoordsBuf = new ComputeBuffer(colorImageLength, 3 * sizeof(float));
                _colorDepthCoordsBuf = new ComputeBuffer(colorImageLength, 2 * sizeof(float));

                _coordMapperShader.SetBuffer(_color2depthKernel, "colorSpaceCoords", _colorSpaceCoordsBuf);
                _coordMapperShader.SetBuffer(_color2depthKernel, "colorDepthCoords", _colorDepthCoordsBuf);
            }
        }

        return(_coordMapperShader != null);
    }
Пример #46
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - Conway's game of life Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);
            var bytecode = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, bytecode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);
            String errors;
            var computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
            var compute = new ComputeShader(device, computeByteCode);

            // shader variable handles
            var conwayResourceH = effect.GetVariableByName("tex").AsResource();
            var resolutionInvH = effect.GetVariableByName("resolutionInv").AsVector();
            resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
            EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();

            // create texture, fill it with random data
            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                CpuAccessFlags = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                BindFlags = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
                Format = Format.R32_Float
            };

            var random = new Random();
            var data = new float[form.ClientSize.Width * form.ClientSize.Height];
            for (int i = 0; i < form.ClientSize.Width; ++i)
            {
                for (int j = 0; j < form.ClientSize.Height; ++j)
                    data[i * form.ClientSize.Height + j] = (float)random.Next(2);
            }

            DataStream ds = new DataStream(data, true, false);
            DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);

            Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);

            // Create SRV and UAV over the same texture
            UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
            ShaderResourceView conwaySRV = new ShaderResourceView(device, conwayTex);

            // On the more typical setup where you switch shaders, 
            // you will have to set the texture after every
            conwayResourceH.SetResource(conwaySRV);

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            Vector2 lightPosSS;
            float angle = 0;

            MessagePump.Run(form, () =>
            {
                // this does the light rotation
                angle += 0.002f;
                lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
                lightPosSSH.Set(lightPosSS);

                device.ImmediateContext.ComputeShader.Set(compute);
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
                device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);

                // After running the CS you have to unset UAV from the shader, so you can use it as SRV
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);

                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    // No vertices are send as they are created in the vertex shader on the fly.
                    device.ImmediateContext.Draw(4, 0);
                }

                swapChain.Present(0, PresentFlags.None);
            });

            computeByteCode.Dispose();
            conwayUAV.Dispose();
            conwaySRV.Dispose();
            conwayTex.Dispose();
            ds.Dispose();
            bytecode.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
 public VectorscopeMonitor()
 {
     m_ComputeShader = EditorResources.Load <ComputeShader>("Monitors/VectorscopeCompute.compute");
 }
Пример #48
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try {
                m_device.Init( m_viewerForm.Handle, false, true );

                // Create our compute shaders
                #if !DEBUG
                    using ( ScopedForceMaterialsLoadFromBinary scope = new ScopedForceMaterialsLoadFromBinary() )
                #endif
                {
                    m_CS_BilateralFilter = new ComputeShader( m_device, new System.IO.FileInfo( "./Shaders/BilateralFiltering.hlsl" ), "CS", null );
                    m_CS_GenerateSSBumpMap = new ComputeShader( m_device, new System.IO.FileInfo( "./Shaders/GenerateSSBumpMap.hlsl" ), "CS", null );
                    m_PS_Display = new Shader( m_device, new System.IO.FileInfo( "./Shaders/Display.hlsl" ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
                }

                // Create our constant buffers
                m_CB_Input = new ConstantBuffer<CBInput>( m_device, 0 );
                m_CB_Filter = new ConstantBuffer<CBFilter>( m_device, 0 );

                m_CB_Display = new ConstantBuffer<CBDisplay>( m_device, 0 );
                m_CB_Display.m._Width = (uint) m_viewerForm.Width;
                m_CB_Display.m._Height = (uint) m_viewerForm.Height;

                // Create our structured buffer containing the rays
                m_SB_Rays = new StructuredBuffer<float3>( m_device, 3*MAX_THREADS, true );
                integerTrackbarControlRaysCount_SliderDragStop( integerTrackbarControlRaysCount, 0 );

            //				LoadHeightMap( new System.IO.FileInfo( "eye_generic_01_disp.png" ) );
            //				LoadHeightMap( new System.IO.FileInfo( "10 - Smooth.jpg" ) );

            } catch ( Exception _e ) {
                MessageBox( "Failed to create DX11 device and default shaders:\r\n", _e );
                Close();
            }
        }
        void RenderIndirectDiffusePerformance(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, int frameCount)
        {
            // Fetch the required resources
            var       settings  = hdCamera.volumeStack.GetComponent <GlobalIllumination>();
            BlueNoise blueNoise = GetBlueNoiseManager();

            // Fetch all the settings
            LightCluster       lightClusterSettings = hdCamera.volumeStack.GetComponent <LightCluster>();
            RayTracingSettings rtSettings           = hdCamera.volumeStack.GetComponent <RayTracingSettings>();

            ComputeShader indirectDiffuseCS = m_Asset.renderPipelineRayTracingResources.indirectDiffuseRaytracingCS;

            // Request the intermediate texture we will be using
            RTHandle directionBuffer     = GetRayTracingBuffer(InternalRayTracingBuffers.Direction);
            RTHandle intermediateBuffer1 = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA1);

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingIntegrateIndirectDiffuse)))
            {
                // Fetch the new sample kernel
                int currentKernel = indirectDiffuseCS.FindKernel(settings.fullResolution ? "RaytracingIndirectDiffuseFullRes" : "RaytracingIndirectDiffuseHalfRes");

                // Inject the ray-tracing sampling data
                blueNoise.BindDitheredRNGData8SPP(cmd);

                // Bind all the required textures
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());

                // Bind the output buffers
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer);

                // Texture dimensions
                int texWidth  = settings.fullResolution ? hdCamera.actualWidth : hdCamera.actualWidth / 2;
                int texHeight = settings.fullResolution ? hdCamera.actualHeight : hdCamera.actualHeight / 2;

                // Evaluate the dispatch parameters
                int areaTileSize = 8;
                int numTilesXHR  = (texWidth + (areaTileSize - 1)) / areaTileSize;
                int numTilesYHR  = (texHeight + (areaTileSize - 1)) / areaTileSize;

                // Compute the directions
                cmd.DispatchCompute(indirectDiffuseCS, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount);

                // Prepare the components for the deferred lighting
                DeferredLightingRTParameters deferredParamters = PrepareIndirectDiffuseDeferredLightingRTParameters(hdCamera);
                DeferredLightingRTResources  deferredResources = PrepareDeferredLightingRTResources(hdCamera, directionBuffer, m_IndirectDiffuseBuffer0);

                // Evaluate the deferred lighting
                RenderRaytracingDeferredLighting(cmd, deferredParamters, deferredResources);
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RaytracingFilterIndirectDiffuse)))
            {
                // Fetch the right filter to use
                int currentKernel = indirectDiffuseCS.FindKernel(settings.fullResolution ? "IndirectDiffuseIntegrationUpscaleFullRes" : "IndirectDiffuseIntegrationUpscaleHalfRes");

                // Inject all the parameters for the compute
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._IndirectDiffuseTexture, m_IndirectDiffuseBuffer0);
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._RaytracingDirectionBuffer, directionBuffer);
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._BlueNoiseTexture, blueNoise.textureArray16RGB);
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._UpscaledIndirectDiffuseTextureRW, intermediateBuffer1);
                cmd.SetComputeTextureParam(indirectDiffuseCS, currentKernel, HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex);
                cmd.SetComputeIntParam(indirectDiffuseCS, HDShaderIDs._SpatialFilterRadius, settings.upscaleRadius);

                // Texture dimensions
                int texWidth  = hdCamera.actualWidth;
                int texHeight = hdCamera.actualHeight;

                // Evaluate the dispatch parameters
                int areaTileSize = 8;
                int numTilesXHR  = (texWidth + (areaTileSize - 1)) / areaTileSize;
                int numTilesYHR  = (texHeight + (areaTileSize - 1)) / areaTileSize;

                // Compute the texture
                cmd.DispatchCompute(indirectDiffuseCS, currentKernel, numTilesXHR, numTilesYHR, hdCamera.viewCount);

                // Copy the data back to the right buffer
                HDUtils.BlitCameraTexture(cmd, intermediateBuffer1, m_IndirectDiffuseBuffer0);

                // Denoise if required
                if (settings.denoise)
                {
                    DenoiseIndirectDiffuseBuffer(hdCamera, cmd, settings);
                }
            }
        }
Пример #50
0
        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>
        /// The Init method precomputes the atmosphere textures. It first allocates the
        /// temporary resources it needs, then calls Precompute to do the
        /// actual precomputations, and finally destroys the temporary resources.
        ///
        /// Note that there are two precomputation modes here, depending on whether we
        /// want to store precomputed irradiance or illuminance values:
        ///
        /// In precomputed irradiance mode, we simply need to call
        /// Precompute with the 3 wavelengths for which we want to precompute
        /// irradiance, namely kLambdaR, kLambdaG, kLambdaB(with the identity matrix for
        /// luminance_from_radiance, since we don't want any conversion from radiance to luminance).
        ///
        /// In precomputed illuminance mode, we need to precompute irradiance for
        /// num_precomputed_wavelengths, and then integrate the results,
        /// multiplied with the 3 CIE xyz color matching functions and the XYZ to sRGB
        /// matrix to get sRGB illuminance values.
        /// A naive solution would be to allocate temporary textures for the
        /// intermediate irradiance results, then perform the integration from irradiance
        /// to illuminance and store the result in the final precomputed texture. In
        /// pseudo-code (and assuming one wavelength per texture instead of 3):
        ///
        ///  create n temporary irradiance textures
        ///  for each wavelength lambda in the n wavelengths:
        ///     precompute irradiance at lambda into one of the temporary textures
        ///  initializes the final illuminance texture with zeros
        ///  for each wavelength lambda in the n wavelengths:
        ///     accumulate in the final illuminance texture the product of the
        ///     precomputed irradiance at lambda (read from the temporary textures)
        ///     with the value of the 3 sRGB color matching functions at lambda
        ///     (i.e. the product of the XYZ to sRGB matrix with the CIE xyz color matching functions).
        ///
        /// However, this be would waste GPU memory. Instead, we can avoid allocating
        /// temporary irradiance textures, by merging the two above loops:
        ///
        ///   for each wavelength lambda in the n wavelengths:
        ///     accumulate in the final illuminance texture (or, for the first
        ///     iteration, set this texture to) the product of the precomputed
        ///     irradiance at lambda (computed on the fly) with the value of the 3
        ///     sRGB color matching functions at lambda.
        ///
        /// This is the method we use below, with 3 wavelengths per iteration instead
        /// of 1, using Precompute to compute 3 irradiances values per
        /// iteration, and luminance_from_radiance to multiply 3 irradiances
        /// with the values of the 3 sRGB color matching functions at 3 different
        /// wavelengths (yielding a 3x3 matrix).
        ///
        /// This yields the following implementation:
        /// </summary>
        public void Init(ComputeShader compute, int num_scattering_orders)
        {
            // The precomputations require temporary textures, in particular to store the
            // contribution of one scattering order, which is needed to compute the next
            // order of scattering (the final precomputed textures store the sum of all
            // the scattering orders). We allocate them here, and destroy them at the end
            // of this method.
            TextureBuffer buffer = new TextureBuffer(HalfPrecision);

            buffer.Clear(compute);

            // The actual precomputations depend on whether we want to store precomputed
            // irradiance or illuminance values.
            if (NumPrecomputedWavelengths <= 3)
            {
                Precompute(compute, buffer, null, null, false, num_scattering_orders);
            }
            else
            {
                int    num_iterations = (NumPrecomputedWavelengths + 2) / 3;
                double dlambda        = (kLambdaMax - kLambdaMin) / (3.0 * num_iterations);

                for (int i = 0; i < num_iterations; ++i)
                {
                    double[] lambdas = new double[]
                    {
                        kLambdaMin + (3 * i + 0.5) * dlambda,
                        kLambdaMin + (3 * i + 1.5) * dlambda,
                        kLambdaMin + (3 * i + 2.5) * dlambda
                    };

                    double[] luminance_from_radiance = new double[]
                    {
                        Coeff(lambdas[0], 0) * dlambda, Coeff(lambdas[1], 0) * dlambda, Coeff(lambdas[2], 0) * dlambda,
                        Coeff(lambdas[0], 1) * dlambda, Coeff(lambdas[1], 1) * dlambda, Coeff(lambdas[2], 1) * dlambda,
                        Coeff(lambdas[0], 2) * dlambda, Coeff(lambdas[1], 2) * dlambda, Coeff(lambdas[2], 2) * dlambda
                    };

                    bool blend = i > 0;
                    Precompute(compute, buffer, lambdas, luminance_from_radiance, blend, num_scattering_orders);
                }

                // After the above iterations, the transmittance texture contains the
                // transmittance for the 3 wavelengths used at the last iteration. But we
                // want the transmittance at kLambdaR, kLambdaG, kLambdaB instead, so we
                // must recompute it here for these 3 wavelengths:
                int compute_transmittance = compute.FindKernel("ComputeTransmittance");
                BindToCompute(compute, null, null);
                compute.SetTexture(compute_transmittance, "transmittanceWrite", buffer.TransmittanceArray[WRITE]);
                compute.SetVector("blend", new Vector4(0, 0, 0, 0));

                int NUM = CONSTANTS.NUM_THREADS;
                compute.Dispatch(compute_transmittance, CONSTANTS.TRANSMITTANCE_WIDTH / NUM, CONSTANTS.TRANSMITTANCE_HEIGHT / NUM, 1);
                Swap(buffer.TransmittanceArray);
            }

            //Grab ref to textures and mark as null in buffer so they are not released.
            TransmittanceTexture            = buffer.TransmittanceArray[READ];
            buffer.TransmittanceArray[READ] = null;

            ScatteringTexture            = buffer.ScatteringArray[READ];
            buffer.ScatteringArray[READ] = null;

            IrradianceTexture            = buffer.IrradianceArray[READ];
            buffer.IrradianceArray[READ] = null;

            if (CombineScatteringTextures)
            {
                OptionalSingleMieScatteringTexture = null;
            }
            else
            {
                OptionalSingleMieScatteringTexture            = buffer.OptionalSingleMieScatteringArray[READ];
                buffer.OptionalSingleMieScatteringArray[READ] = null;
            }

            // Delete the temporary resources allocated at the begining of this method.
            buffer.Release();
        }
 private void Initialize()
 {
     computeFillNoiseTexture = new ComputeShader(graphicsDevice, ShaderPrecompiler.PrecompileOrLoad(@"Shaders\TerrainGenerator.hlsl", "FillNoiseTexture", "cs_5_0", ShaderFlags.None, EffectFlags.None));
 }
        /// <summary>
        /// Bind to a compute shader for precomutation of textures.
        /// </summary>
        private void BindToCompute(ComputeShader compute, double[] lambdas, double[] luminance_from_radiance)
        {
            if (lambdas == null)
            {
                lambdas = new double[] { kLambdaR, kLambdaG, kLambdaB }
            }
            ;

            if (luminance_from_radiance == null)
            {
                luminance_from_radiance = new double[] { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }
            }
            ;

            compute.SetInt("TRANSMITTANCE_TEXTURE_WIDTH", CONSTANTS.TRANSMITTANCE_WIDTH);
            compute.SetInt("TRANSMITTANCE_TEXTURE_HEIGHT", CONSTANTS.TRANSMITTANCE_HEIGHT);
            compute.SetInt("SCATTERING_TEXTURE_R_SIZE", CONSTANTS.SCATTERING_R);
            compute.SetInt("SCATTERING_TEXTURE_MU_SIZE", CONSTANTS.SCATTERING_MU);
            compute.SetInt("SCATTERING_TEXTURE_MU_S_SIZE", CONSTANTS.SCATTERING_MU_S);
            compute.SetInt("SCATTERING_TEXTURE_NU_SIZE", CONSTANTS.SCATTERING_NU);
            compute.SetInt("SCATTERING_TEXTURE_WIDTH", CONSTANTS.SCATTERING_WIDTH);
            compute.SetInt("SCATTERING_TEXTURE_HEIGHT", CONSTANTS.SCATTERING_HEIGHT);
            compute.SetInt("SCATTERING_TEXTURE_DEPTH", CONSTANTS.SCATTERING_DEPTH);
            compute.SetInt("IRRADIANCE_TEXTURE_WIDTH", CONSTANTS.IRRADIANCE_WIDTH);
            compute.SetInt("IRRADIANCE_TEXTURE_HEIGHT", CONSTANTS.IRRADIANCE_HEIGHT);

            Vector3 skySpectralRadianceToLuminance, sunSpectralRadianceToLuminance;

            SkySunRadianceToLuminance(out skySpectralRadianceToLuminance, out sunSpectralRadianceToLuminance);

            compute.SetVector("SKY_SPECTRAL_RADIANCE_TO_LUMINANCE", skySpectralRadianceToLuminance);
            compute.SetVector("SUN_SPECTRAL_RADIANCE_TO_LUMINANCE", sunSpectralRadianceToLuminance);

            Vector3 solarIrradiance = ToVector(Wavelengths, SolarIrradiance, lambdas, 1.0);

            compute.SetVector("solar_irradiance", solarIrradiance);

            Vector3 rayleighScattering = ToVector(Wavelengths, RayleighScattering, lambdas, LengthUnitInMeters);

            BindDensityLayer(compute, RayleighDensity);
            compute.SetVector("rayleigh_scattering", rayleighScattering);

            Vector3 mieScattering = ToVector(Wavelengths, MieScattering, lambdas, LengthUnitInMeters);
            Vector3 mieExtinction = ToVector(Wavelengths, MieExtinction, lambdas, LengthUnitInMeters);

            BindDensityLayer(compute, MieDensity);
            compute.SetVector("mie_scattering", mieScattering);
            compute.SetVector("mie_extinction", mieExtinction);

            Vector3 absorptionExtinction = ToVector(Wavelengths, AbsorptionExtinction, lambdas, LengthUnitInMeters);

            BindDensityLayer(compute, AbsorptionDensity[0]);
            BindDensityLayer(compute, AbsorptionDensity[1]);
            compute.SetVector("absorption_extinction", absorptionExtinction);

            Vector3 groundAlbedo = ToVector(Wavelengths, GroundAlbedo, lambdas, 1.0);

            compute.SetVector("ground_albedo", groundAlbedo);

            compute.SetFloats("luminanceFromRadiance", ToMatrix(luminance_from_radiance));
            compute.SetFloat("sun_angular_radius", (float)SunAngularRadius);
            compute.SetFloat("bottom_radius", (float)(BottomRadius / LengthUnitInMeters));
            compute.SetFloat("top_radius", (float)(TopRadius / LengthUnitInMeters));
            compute.SetFloat("mie_phase_function_g", (float)MiePhaseFunctionG);
            compute.SetFloat("mu_s_min", (float)Math.Cos(MaxSunZenithAngle));
        }
Пример #54
0
 private int Balance(GPU gpu, ComputeShader gravityModelShader, GPUBuffer balancedBuffer, GPUBuffer parameters, float[] balanced, int iterations, int[] step1, int[] step2)
 {
     do
     {
         if ( this.ProgressCallback != null )
         {
             this.ProgressCallback( (float)iterations / this.MaxIterations );
         }
         gpu.Write( parameters, step1 );
         // Compute Flows
         gpu.ExecuteComputeShader( gravityModelShader );
         gpu.Write( parameters, step2 );
         // Compute Residues and check to see if we are all balanced
         gpu.ExecuteComputeShader( gravityModelShader );
         gpu.Read( balancedBuffer, balanced );
     } while ( ( ++iterations ) < this.MaxIterations && balanced[0] == 0 );
     if ( this.ProgressCallback != null )
     {
         this.ProgressCallback( 1f );
     }
     return iterations;
 }
        /// <summary>
        /// Finally, we provide the actual implementation of the precomputation algorithm
        /// described in Algorithm 4.1 of
        /// <a href="https://hal.inria.fr/inria-00288758/en">our paper</a>. Each step is
        /// explained by the inline comments below.
        /// </summary>
        void Precompute(
            ComputeShader compute,
            TextureBuffer buffer,
            double[] lambdas,
            double[] luminance_from_radiance,
            bool blend,
            int num_scattering_orders)
        {
            int BLEND       = blend ? 1 : 0;
            int NUM_THREADS = CONSTANTS.NUM_THREADS;

            BindToCompute(compute, lambdas, luminance_from_radiance);

            int compute_transmittance       = compute.FindKernel("ComputeTransmittance");
            int compute_direct_irradiance   = compute.FindKernel("ComputeDirectIrradiance");
            int compute_single_scattering   = compute.FindKernel("ComputeSingleScattering");
            int compute_scattering_density  = compute.FindKernel("ComputeScatteringDensity");
            int compute_indirect_irradiance = compute.FindKernel("ComputeIndirectIrradiance");
            int compute_multiple_scattering = compute.FindKernel("ComputeMultipleScattering");

            // Compute the transmittance, and store it in transmittance_texture
            compute.SetTexture(compute_transmittance, "transmittanceWrite", buffer.TransmittanceArray[WRITE]);
            compute.SetVector("blend", new Vector4(0, 0, 0, 0));
            compute.Dispatch(compute_transmittance, CONSTANTS.TRANSMITTANCE_WIDTH / NUM_THREADS, CONSTANTS.TRANSMITTANCE_HEIGHT / NUM_THREADS, 1);
            Swap(buffer.TransmittanceArray);

            // Compute the direct irradiance, store it in delta_irradiance_texture and,
            // depending on 'blend', either initialize irradiance_texture_ with zeros or
            // leave it unchanged (we don't want the direct irradiance in
            // irradiance_texture_, but only the irradiance from the sky).
            compute.SetTexture(compute_direct_irradiance, "deltaIrradianceWrite", buffer.DeltaIrradianceTexture); //0
            compute.SetTexture(compute_direct_irradiance, "irradianceWrite", buffer.IrradianceArray[WRITE]);      //1
            compute.SetTexture(compute_direct_irradiance, "irradianceRead", buffer.IrradianceArray[READ]);
            compute.SetTexture(compute_direct_irradiance, "transmittanceRead", buffer.TransmittanceArray[READ]);
            compute.SetVector("blend", new Vector4(0, BLEND, 0, 0));
            compute.Dispatch(compute_direct_irradiance, CONSTANTS.IRRADIANCE_WIDTH / NUM_THREADS, CONSTANTS.IRRADIANCE_HEIGHT / NUM_THREADS, 1);
            Swap(buffer.IrradianceArray);

            // Compute the rayleigh and mie single scattering, store them in
            // delta_rayleigh_scattering_texture and delta_mie_scattering_texture, and
            // either store them or accumulate them in scattering_texture_ and
            // optional_single_mie_scattering_texture_.
            compute.SetTexture(compute_single_scattering, "deltaRayleighScatteringWrite", buffer.DeltaRayleighScatteringTexture);      //0
            compute.SetTexture(compute_single_scattering, "deltaMieScatteringWrite", buffer.DeltaMieScatteringTexture);                //1
            compute.SetTexture(compute_single_scattering, "scatteringWrite", buffer.ScatteringArray[WRITE]);                           //2
            compute.SetTexture(compute_single_scattering, "scatteringRead", buffer.ScatteringArray[READ]);
            compute.SetTexture(compute_single_scattering, "singleMieScatteringWrite", buffer.OptionalSingleMieScatteringArray[WRITE]); //3
            compute.SetTexture(compute_single_scattering, "singleMieScatteringRead", buffer.OptionalSingleMieScatteringArray[READ]);
            compute.SetTexture(compute_single_scattering, "transmittanceRead", buffer.TransmittanceArray[READ]);
            compute.SetVector("blend", new Vector4(0, 0, BLEND, BLEND));

            for (int layer = 0; layer < CONSTANTS.SCATTERING_DEPTH; ++layer)
            {
                compute.SetInt("layer", layer);
                compute.Dispatch(compute_single_scattering, CONSTANTS.SCATTERING_WIDTH / NUM_THREADS, CONSTANTS.SCATTERING_HEIGHT / NUM_THREADS, 1);
            }
            Swap(buffer.ScatteringArray);
            Swap(buffer.OptionalSingleMieScatteringArray);

            // Compute the 2nd, 3rd and 4th order of scattering, in sequence.
            for (int scattering_order = 2; scattering_order <= num_scattering_orders; ++scattering_order)
            {
                // Compute the scattering density, and store it in
                // delta_scattering_density_texture.
                compute.SetTexture(compute_scattering_density, "deltaScatteringDensityWrite", buffer.DeltaScatteringDensityTexture); //0
                compute.SetTexture(compute_scattering_density, "transmittanceRead", buffer.TransmittanceArray[READ]);
                compute.SetTexture(compute_scattering_density, "singleRayleighScatteringRead", buffer.DeltaRayleighScatteringTexture);
                compute.SetTexture(compute_scattering_density, "singleMieScatteringRead", buffer.DeltaMieScatteringTexture);
                compute.SetTexture(compute_scattering_density, "multipleScatteringRead", buffer.DeltaMultipleScatteringTexture);
                compute.SetTexture(compute_scattering_density, "irradianceRead", buffer.DeltaIrradianceTexture);
                compute.SetInt("scatteringOrder", scattering_order);
                compute.SetVector("blend", new Vector4(0, 0, 0, 0));

                for (int layer = 0; layer < CONSTANTS.SCATTERING_DEPTH; ++layer)
                {
                    compute.SetInt("layer", layer);
                    compute.Dispatch(compute_scattering_density, CONSTANTS.SCATTERING_WIDTH / NUM_THREADS, CONSTANTS.SCATTERING_HEIGHT / NUM_THREADS, 1);
                }

                // Compute the indirect irradiance, store it in delta_irradiance_texture and
                // accumulate it in irradiance_texture_.
                compute.SetTexture(compute_indirect_irradiance, "deltaIrradianceWrite", buffer.DeltaIrradianceTexture); //0
                compute.SetTexture(compute_indirect_irradiance, "irradianceWrite", buffer.IrradianceArray[WRITE]);      //1
                compute.SetTexture(compute_indirect_irradiance, "irradianceRead", buffer.IrradianceArray[READ]);
                compute.SetTexture(compute_indirect_irradiance, "singleRayleighScatteringRead", buffer.DeltaRayleighScatteringTexture);
                compute.SetTexture(compute_indirect_irradiance, "singleMieScatteringRead", buffer.DeltaMieScatteringTexture);
                compute.SetTexture(compute_indirect_irradiance, "multipleScatteringRead", buffer.DeltaMultipleScatteringTexture);
                compute.SetInt("scatteringOrder", scattering_order - 1);
                compute.SetVector("blend", new Vector4(0, 1, 0, 0));

                compute.Dispatch(compute_indirect_irradiance, CONSTANTS.IRRADIANCE_WIDTH / NUM_THREADS, CONSTANTS.IRRADIANCE_HEIGHT / NUM_THREADS, 1);
                Swap(buffer.IrradianceArray);

                // Compute the multiple scattering, store it in
                // delta_multiple_scattering_texture, and accumulate it in
                // scattering_texture_.
                compute.SetTexture(compute_multiple_scattering, "deltaMultipleScatteringWrite", buffer.DeltaMultipleScatteringTexture); //0
                compute.SetTexture(compute_multiple_scattering, "scatteringWrite", buffer.ScatteringArray[WRITE]);                      //1
                compute.SetTexture(compute_multiple_scattering, "scatteringRead", buffer.ScatteringArray[READ]);
                compute.SetTexture(compute_multiple_scattering, "transmittanceRead", buffer.TransmittanceArray[READ]);
                compute.SetTexture(compute_multiple_scattering, "deltaScatteringDensityRead", buffer.DeltaScatteringDensityTexture);
                compute.SetVector("blend", new Vector4(0, 1, 0, 0));

                for (int layer = 0; layer < CONSTANTS.SCATTERING_DEPTH; ++layer)
                {
                    compute.SetInt("layer", layer);
                    compute.Dispatch(compute_multiple_scattering, CONSTANTS.SCATTERING_WIDTH / NUM_THREADS, CONSTANTS.SCATTERING_HEIGHT / NUM_THREADS, 1);
                }
                Swap(buffer.ScatteringArray);
            }

            return;
        }
Пример #56
0
 protected virtual void SetParametersOnce(int kernelID, ComputeShader shader)
 {
 }
Пример #57
0
		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, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
				return;
			}

			try {
				m_Shader_RenderScene = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/RenderScene.hlsl" ) ), VERTEX_FORMAT.P3N3G3B3T2, "VS", null, "PS", null );
			} catch ( Exception _e ) {
				MessageBox.Show( "Shader \"RenderScene\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
				m_Shader_RenderScene = null;
			}

			try {
				m_Shader_PostProcess = new Shader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/PostProcess.hlsl" ) ), VERTEX_FORMAT.Pt4, "VS", null, "PS", null );
			} catch ( Exception _e ) {
				MessageBox.Show( "Shader \"PostProcess\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
				m_Shader_PostProcess = null;
			}

			try {
//				m_Shader_BuildDistanceField[0] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/BuildDistanceField.hlsl" ) ), "CS_X", null );
			} catch ( Exception _e ) {
				MessageBox.Show( "Shader \"BuildDistanceField\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
				m_Shader_PostProcess = null;
			}

			#if DEBUG && !BISOU
				try {
					m_Shader_SplatDepthStencil[0] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil.hlsl" ) ), "CS0", null );
					m_Shader_SplatDepthStencil[1] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil.hlsl" ) ), "CS1", null );
					m_Shader_SplatDepthStencil[2] = new ComputeShader( m_Device, new ShaderFile( new System.IO.FileInfo( "Shaders/SplatDepthStencil.hlsl" ) ), "CS2", null );
				} catch ( Exception _e ) {
					MessageBox.Show( "Shader \"SplatDepthStencil\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
					m_Shader_SplatDepthStencil[0] = null;
					m_Shader_SplatDepthStencil[1] = null;
					m_Shader_SplatDepthStencil[2] = null;
				}
			#else
				try {
					m_Shader_SplatDepthStencil[0] = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "./Shaders/Binary/SplatDepthStencil.fxbin" ), "CS0" );
					m_Shader_SplatDepthStencil[1] = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "./Shaders/Binary/SplatDepthStencil.fxbin" ), "CS1" );
					m_Shader_SplatDepthStencil[2] = ComputeShader.CreateFromBinaryBlob( m_Device, new System.IO.FileInfo( "./Shaders/Binary/SplatDepthStencil.fxbin" ), "CS2" );
				} catch ( Exception _e ) {
					MessageBox.Show( "Shader \"SplatDepthStencil\" failed to compile!\n\n" + _e.Message, "Distance Field Test", MessageBoxButtons.OK, MessageBoxIcon.Error );
					m_Shader_SplatDepthStencil[0] = null;
					m_Shader_SplatDepthStencil[1] = null;
					m_Shader_SplatDepthStencil[2] = null;
				}
			#endif

			m_CB_Main = new ConstantBuffer<CB_Main>( m_Device, 0 );
			m_CB_Camera = new ConstantBuffer<CB_Camera>( m_Device, 1 );
			m_CB_Object = new ConstantBuffer<CB_Object>( m_Device, 2 );
			m_CB_DistanceField = new ConstantBuffer<CB_Distance>( m_Device, 2 );

			BuildPrimitives();

			// Allocate texture
			m_Tex_TempTarget = new Texture2D( m_Device, panelOutput.Width, panelOutput.Height, 1, 1, PIXEL_FORMAT.RGBA8_UNORM_sRGB, false, false, null );

			// Allocate several 3D textures for depth-stencil reduction
			int	W = (panelOutput.Width + 7) & ~7;
			int	H = (panelOutput.Height + 7) & ~7;
			int	D = 1;
			for ( int depthLevel=0; depthLevel < 3; depthLevel++ ) {

				// On every level, resolution is reduced by 2 and depth gets multiplied by 4
				W >>= 1;
				H >>= 1;
				D <<= 2;

				m_Tex_TempDepth3D[depthLevel] = new Texture3D( m_Device, W, H, D, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, true, null );
			}
			m_Tex_TempDepth3D[3] = new Texture3D( m_Device, W, H, D, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, true, null );

// 			int	cellsCountX = (panelOutput.Width + 7) >> 3;
// 			int	cellsCountY = (panelOutput.Height + 7) >> 3;
// 			int	cellsCountZ = 64;
// 			m_Tex_DistanceField = new Texture3D( m_Device, cellsCountX, cellsCountY, cellsCountZ, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, true, null );	// TODO: Use mips to smooth stuff up?
//			m_Tex_DistanceField = new Texture3D( m_Device, W, H, D, 1, PIXEL_FORMAT.RGBA32_FLOAT, false, true, null );	// TODO: Use mips to smooth stuff up?

			// 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 );
		}