/// <summary> /// Load stuff here /// </summary> protected override void Initialize() { var device = GraphicsDevice; base.Initialize(); vb = new VertexBuffer(device, typeof(Vertex), 6); cb = new ConstantBuffer(GraphicsDevice, typeof(ConstData)); instDataGpu = new StructuredBuffer(device, typeof(InstData), InstanceCount, StructuredBufferFlags.None); instDataCpu = new InstData[InstanceCount]; var rand = new Random(); for (int i = 0; i < InstanceCount; i++) { instDataCpu[i].Offset = rand.NextVector2(new Vector2(-2.5f, -2f), new Vector2(2.5f, 2f)); instDataCpu[i].Scale = rand.NextFloat(0, 0.7f); instDataCpu[i].Rotation = rand.NextFloat(0, MathUtil.TwoPi); instDataCpu[i].Color = rand.NextVector4(Vector4.Zero, Vector4.One * 0.7f); instDataCpu[i].TexId = rand.Next(4); } Reloading += InstancingDemo_Reloading; InstancingDemo_Reloading(this, EventArgs.Empty); }
/// <summary> /// /// </summary> void ApplyVTState() { if (physicalSizeDirty) { Log.Message("VT state changes: new size {0}", physicalSize); SafeDispose(ref PhysicalPages0); SafeDispose(ref PhysicalPages1); SafeDispose(ref PhysicalPages2); SafeDispose(ref PageTable); SafeDispose(ref PageData); SafeDispose(ref Params); int tableSize = VTConfig.VirtualPageCount; int physSize = physicalSize; int physPages = physicalSize / VTConfig.PageSizeBordered; int maxTiles = physPages * physPages; PhysicalPages0 = new Texture2D(rs.Device, physSize, physSize, ColorFormat.Rgba8_sRGB, false, true); PhysicalPages1 = new Texture2D(rs.Device, physSize, physSize, ColorFormat.Rgba8, false, false); PhysicalPages2 = new Texture2D(rs.Device, physSize, physSize, ColorFormat.Rgba8, false, false); PageTable = new RenderTarget2D(rs.Device, ColorFormat.Rgba32F, tableSize, tableSize, true, true); PageData = new StructuredBuffer(rs.Device, typeof(PageGpu), maxTiles, StructuredBufferFlags.None); Params = new ConstantBuffer(rs.Device, 16); tileCache = new VTTileCache(physPages, physicalSize); PageScaleRCP = VTConfig.PageSize / (float)physSize; physicalSizeDirty = false; } }
public void Scan(ComputeBufferBase <int> buffer, int count) { uint gx, gy, gz; shader.GetKernelThreadGroupSizes(scanKernel, out gx, out gy, out gz); int numGroupsX = Mathf.CeilToInt((float)count / gx); shader.SetInt("count", count); shader.SetInt("lane_stride", LANE_STRIDE); shader.SetBuffer(scanKernel, "data", buffer.Buffer); shader.Dispatch(scanKernel, numGroupsX, 1, 1); // If we can't complete the scan within a single group. if (count > LANE_STRIDE * gx) { using (var groupData = new StructuredBuffer <int>((int)gx)) { shader.SetBuffer(scanGroupResultsKernel, "data", buffer.Buffer); shader.SetBuffer(scanGroupResultsKernel, "group_data", groupData.Buffer); shader.Dispatch(scanGroupResultsKernel, 1, 1, 1); shader.SetBuffer(addGroupResultsKernel, "data", buffer.Buffer); shader.SetBuffer(addGroupResultsKernel, "group_data", groupData.Buffer); shader.Dispatch(addGroupResultsKernel, numGroupsX, 1, 1); } } shader.SetBuffer(inclusiveToExclusiveKernel, "data", buffer.Buffer); shader.Dispatch(inclusiveToExclusiveKernel, 1, 1, 1); }
public void TestCompact(int count) { int[] data = new int[count]; int[] selected = new int[count]; for (int i = 0; i < count; i++) { data[i] = i; selected[i] = i % 2; } using (StructuredBuffer <int> buffer = new StructuredBuffer <int>(count)) using (StructuredBuffer <int> keys = new StructuredBuffer <int>(count)) { buffer.SetData(data); keys.SetData(selected); ScanCompact compactor = new ScanCompact(); compactor.Compact(buffer, keys, buffer.Count); int[] result = buffer.GetData(); for (int i = 0; i < count / 2; i++) { Assert.AreEqual(result[i], 2 * i + 1); } } }
/// <summary> /// Called when the first frame rendering is started, and D3DDevice is properly started and functional /// </summary> private void RenderDeviceStarted() { // TODO pre-compile shader Shader raymarchShader = Shader.CompileFromFiles(@"Shaders\Raymarch"); raymarchRenderPlane = Mesh.CreateQuad(); // Set as current shaders // TODO what's inputlayout? deviceContext.InputAssembler.InputLayout = raymarchShader.InputLayout; deviceContext.VertexShader.Set(raymarchShader.VertexShader); deviceContext.PixelShader.Set(raymarchShader.PixelShader); raymarchShaderBuffer = new ConstantBuffer <RaymarchShaderBufferData>(device); // Create buffers for different types of shapes. Combine later? primitivesBuffer = new StructuredBuffer <PrimitiveBufferData> [8]; for (int i = 0; i < primitivesBuffer.Length; i++) { primitivesBuffer[i] = new StructuredBuffer <PrimitiveBufferData>(device, i); } noiseTextureBuffer = new TextureBuffer <Color>(device, CreateNoise(1024), 1024, Format.R8G8B8A8_UNorm, 1); }
public void TestContains() { int count = 100; int[] testData = new int[count]; for (int i = 0; i < count; i++) { testData[i] = i; } using (var set = new HashSet(count)) using (var input = new StructuredBuffer <int>(count)) using (var results = new StructuredBuffer <int>(count)) { input.SetData(testData); // Nothing should be found. set.Contains(input, results); var data = results.GetData(); for (int i = 0; i < count; i++) { Assert.AreEqual(data[i], 0); } // Now insert. All elements should be found. set.Insert(input, results); set.Contains(input, results); data = results.GetData(); for (int i = 0; i < count; i++) { Assert.AreEqual(data[i], 1); } } }
public unsafe Font(FontContent font) { Content = font; Sources = new StructuredBuffer <GlyphSource>(BufferTarget.ShaderStorageBuffer, font.Characters.Count, font.Name + " Glyph Sources"); GL.BindTexture(TextureTarget.Texture2D, Atlas); var data = font.Atlas.Pin(); for (int mipLevel = 0; mipLevel < font.Atlas.MipLevels; ++mipLevel) { GL.TexImage2D(TextureTarget.Texture2D, mipLevel, PixelInternalFormat.R8Snorm, font.Atlas.Width >> mipLevel, font.Atlas.Height >> mipLevel, 0, PixelFormat.Red, PixelType.Byte, new IntPtr(data + font.Atlas.GetMipStartIndex(mipLevel))); } font.Atlas.Unpin(); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMaxLevel, font.Atlas.MipLevels - 1); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.BindTexture(TextureTarget.Texture2D, 0); int nextSourceId = 0; var sourcesData = new GlyphSource[font.Characters.Count]; foreach (var character in font.Characters) { sourceIds.Add(character.Key, nextSourceId); sourcesData[nextSourceId] = new GlyphSource { Minimum = new Vector2(character.Value.SourceMinimum.X, character.Value.SourceMinimum.Y), PackedSpan = character.Value.SourceSpan.X | (character.Value.SourceSpan.Y << 16), DistanceScale = character.Value.DistanceScale }; ++nextSourceId; } Sources.Update(sourcesData); }
public void TestRemove() { int count = 100; int[] testData = new int[count]; for (int i = 0; i < count; i++) { testData[i] = i; } using (var set = new HashSet(count)) using (var input = new StructuredBuffer <int>(count)) using (var results = new StructuredBuffer <int>(count)) { input.SetData(testData); // Empty set - all removes should fail. set.Remove(input, results); var data = results.GetData(); for (int i = 0; i < count; i++) { Assert.AreEqual(data[i], 0); } // Now insert. All removes should succeed. set.Insert(input, results); set.Remove(input, results); data = results.GetData(); for (int i = 0; i < count; i++) { Assert.AreEqual(data[i], 1); } } }
public void TestOverflow() { int diff = 10; int count = 100; int[] testData = new int[count]; for (int i = 0; i < count; i++) { testData[i] = i; } using (var set = new HashSet(count - diff)) using (var input = new StructuredBuffer <int>(count)) using (var results = new StructuredBuffer <int>(count)) { input.SetData(testData); // # failures should be difference between set size // and input size. int numFailures = 0; set.Insert(input, results); var data = results.GetData(); for (int i = 0; i < count; i++) { if (data[i] == 0) { numFailures++; } } Assert.AreEqual(numFailures, diff); } }
public void TestInsert() { int count = 100; int[] testData = new int[count]; for (int i = 0; i < count; i++) { testData[i] = i; } using (var set = new HashSet(count)) using (var input = new StructuredBuffer <int>(count)) using (var results = new StructuredBuffer <int>(count)) { input.SetData(testData); // First insertion should succeed. set.Insert(input, results); var data = results.GetData(); for (int i = 0; i < count; i++) { Assert.AreEqual(data[i], 1); } // Second insertion should fail because elements // already exist. set.Insert(input, results); data = results.GetData(); for (int i = 0; i < count; i++) { Assert.AreEqual(data[i], 0); } } }
/// <summary> /// /// </summary> void SwapParticleBuffers() { var temp = simulationBufferDst; simulationBufferDst = simulationBufferSrc; simulationBufferSrc = temp; }
/// <summary> /// /// </summary> /// <param name="rs"></param> internal ParticleSystem(RenderSystem rs, RenderWorld renderWorld) { this.rs = rs; this.Game = rs.Game; this.renderWorld = renderWorld; Gravity = Vector3.Down * 9.80665f; paramsCB = new ConstantBuffer(Game.GraphicsDevice, typeof(PrtParams)); imagesCB = new ConstantBuffer(Game.GraphicsDevice, typeof(Vector4), MaxImages); injectionBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(Particle), MaxInjectingParticles, StructuredBufferFlags.None); simulationBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(Particle), MaxSimulatedParticles, StructuredBufferFlags.None); particleLighting = new StructuredBuffer(Game.GraphicsDevice, typeof(Vector4), MaxSimulatedParticles, StructuredBufferFlags.None); sortParticlesBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(Vector2), MaxSimulatedParticles, StructuredBufferFlags.None); deadParticlesIndices = new StructuredBuffer(Game.GraphicsDevice, typeof(uint), MaxSimulatedParticles, StructuredBufferFlags.Append); rs.Game.Reloading += LoadContent; LoadContent(this, EventArgs.Empty); // initialize dead list : var device = Game.GraphicsDevice; device.SetCSRWBuffer(1, deadParticlesIndices, 0); device.PipelineState = factory[(int)Flags.INITIALIZE]; device.Dispatch(MathUtil.IntDivUp(MaxSimulatedParticles, BlockSize)); }
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); }
/// <summary> /// Reads the contents of a <see cref="UploadBuffer{T}"/> instance and writes them into a target <see cref="StructuredBuffer{T}"/> instance. /// </summary> /// <typeparam name="T">The type of items stored on the buffer.</typeparam> /// <param name="source">The input <see cref="UploadBuffer{T}"/> instance to read data from.</param> /// <param name="destination">The target <see cref="StructuredBuffer{T}"/> instance to write data to.</param> public static void CopyTo <T>(this UploadBuffer <T> source, StructuredBuffer <T> destination) where T : unmanaged { Guard.IsNotNull(source); Guard.IsNotNull(destination); destination.CopyFrom(source, 0, 0, source.Length); }
/// <summary> /// Reads the contents of a <see cref="UploadBuffer{T}"/> instance and writes them into a target <see cref="StructuredBuffer{T}"/> instance. /// </summary> /// <typeparam name="T">The type of items stored on the buffer.</typeparam> /// <param name="source">The input <see cref="UploadBuffer{T}"/> instance to read data from.</param> /// <param name="destination">The target <see cref="StructuredBuffer{T}"/> instance to write data to.</param> /// <param name="sourceOffset">The offset to start reading data from.</param> /// <param name="destinationOffset">The starting offset within <paramref name="destination"/> to write data to.</param> /// <param name="count">The number of items to read.</param> public static void CopyTo <T>(this UploadBuffer <T> source, StructuredBuffer <T> destination, int sourceOffset, int destinationOffset, int count) where T : unmanaged { Guard.IsNotNull(source); Guard.IsNotNull(destination); destination.CopyFrom(source, sourceOffset, destinationOffset, count); }
/// <summary> /// Reads the contents of a <see cref="StructuredBuffer{T}"/> instance and writes them into a target <see cref="ReadBackBuffer{T}"/> instance. /// </summary> /// <typeparam name="T">The type of items stored on the buffer.</typeparam> /// <param name="source">The input <see cref="StructuredBuffer{T}"/> instance to read data from.</param> /// <param name="destination">The target <see cref="ReadBackBuffer{T}"/> instance to write data to.</param> public static void CopyTo <T>(this StructuredBuffer <T> source, ReadBackBuffer <T> destination) where T : unmanaged { Guard.IsNotNull(source); Guard.IsNotNull(destination); source.CopyTo(destination, 0, 0, source.Length); }
/// <summary> /// Reads the contents of a <see cref="StructuredBuffer{T}"/> instance and writes them into a target <see cref="ReadBackBuffer{T}"/> instance. /// </summary> /// <typeparam name="T">The type of items stored on the buffer.</typeparam> /// <param name="source">The input <see cref="StructuredBuffer{T}"/> instance to read data from.</param> /// <param name="destination">The target <see cref="ReadBackBuffer{T}"/> instance to write data to.</param> /// <param name="sourceOffset">The offset to start reading data from.</param> /// <param name="destinationOffset">The starting offset within <paramref name="destination"/> to write data to.</param> /// <param name="count">The number of items to read.</param> public static void CopyTo <T>(this StructuredBuffer <T> source, ReadBackBuffer <T> destination, int sourceOffset, int destinationOffset, int count) where T : unmanaged { Guard.IsNotNull(source); Guard.IsNotNull(destination); source.CopyTo(destination, sourceOffset, destinationOffset, count); }
private static void CreateBuffers(GraphicsDevice device, float[] array, out StructuredBuffer <float> sourceBufferView, out WriteableStructuredBuffer <float> destinationBufferView) { GraphicsResource sourceBuffer = GraphicsResource.CreateBuffer <float>(device, array, ResourceFlags.None); GraphicsResource destinationBuffer = GraphicsResource.CreateBuffer <float>(device, array.Length * 2, ResourceFlags.AllowUnorderedAccess); sourceBufferView = new StructuredBuffer <float>(ShaderResourceView.FromBuffer <float>(sourceBuffer)); destinationBufferView = new WriteableStructuredBuffer <float>(UnorderedAccessView.FromBuffer <float>(destinationBuffer)); }
/// <summary> /// Initializes Filter service /// </summary> public override void Initialize() { // create structured buffers and shaders : buffer2 = new StructuredBuffer( device, typeof(Vector2), NumberOfElements , StructuredBufferFlags.None ); paramsCB = new ConstantBuffer( device, typeof(Params) ); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
private static ShaderGenerator CreateShaderGeneratorWithDelegate(StructuredBuffer <float> sourceBuffer, WriteableStructuredBuffer <float> destinationBuffer) { Action <CSInput> action = input => { destinationBuffer[input.DispatchThreadId.X] = Math.Max(sourceBuffer[input.DispatchThreadId.X], 45); }; return(new ShaderGenerator(action, new ShaderAttribute("compute"), new NumThreadsAttribute(100, 1, 1))); }
public MeshRenderer(MeshCache meshCache, ContentArchive content, int maximumInstancesPerDraw = 2048) : base( content.Load <GLSLContent>(@"ShapeDrawing\RenderMeshes.glvs").Source, content.Load <GLSLContent>(@"ShapeDrawing\RenderMeshes.glfs").Source ) { this.meshCache = meshCache; instances = new StructuredBuffer <MeshInstance>(BufferTarget.ShaderStorageBuffer, maximumInstancesPerDraw, $"Mesh Instances"); vertexConstants = new ConstantsBuffer <RasterizedVertexConstants>(BufferTarget.UniformBuffer, debugName: $"Mesh Renderer Vertex Constants"); }
public GlyphRenderer(ContentArchive content, int maximumGlyphsPerDraw = 2048) : base( content.Load <GLSLContent>(@"UI\RenderGlyphs.glvs").Source, content.Load <GLSLContent>(@"UI\RenderGlyphs.glfs").Source ) { instances = new StructuredBuffer <GlyphInstance>(BufferTarget.ShaderStorageBuffer, maximumGlyphsPerDraw, "Glyph Instances"); indices = new IndexBuffer(Helpers.GetQuadIndices(maximumGlyphsPerDraw), "Glyph Indices"); vertexConstants = new ConstantsBuffer <VertexConstants>(BufferTarget.UniformBuffer, debugName: "Glyph Renderer Vertex Constants"); }
public void RemoveAllSparks() { sparkList.Clear(); if (sparkBuffer != null) { sparkBuffer.Dispose(); sparkBuffer = null; } }
/// <summary> /// Initializes Filter service /// </summary> public override void Initialize() { // create structured buffers and shaders : buffer2 = new StructuredBuffer(device, typeof(Vector2), NumberOfElements, StructuredBufferFlags.None); paramsCB = new ConstantBuffer(device, typeof(Params)); LoadContent(); Game.Reloading += (s, e) => LoadContent(); }
public MeshRenderer(Device device, MeshCache meshCache, ShaderCache cache, int maximumInstancesPerDraw = 2048) { this.meshCache = meshCache; instances = new StructuredBuffer <MeshInstance>(device, maximumInstancesPerDraw, $"Mesh Instances"); vertexConstants = new ConstantsBuffer <RasterizedVertexConstants>(device, debugName: $"Mesh Renderer Vertex Constants"); vertexShader = new VertexShader(device, cache.GetShader(@"ShapeDrawing\RenderMeshes.hlsl.vshader")); pixelShader = new PixelShader(device, cache.GetShader(@"ShapeDrawing\RenderMeshes.hlsl.pshader")); }
public RasterizedRenderer(ContentArchive content, string shaderPath, int maximumInstancesPerDraw = 2048) : base( content.Load <GLSLContent>($"{shaderPath}.glvs").Source, content.Load <GLSLContent>($"{shaderPath}.glfs").Source ) { string instanceTypeName = typeof(TInstance).Name; instances = new StructuredBuffer <TInstance>(BufferTarget.ShaderStorageBuffer, maximumInstancesPerDraw, $"{instanceTypeName} Instances"); vertexConstants = new ConstantsBuffer <RasterizedVertexConstants>(BufferTarget.UniformBuffer, debugName: $"{instanceTypeName} Renderer Vertex Constants"); }
private void BuildRandomBuffer() { Reg(m_SB_Random = new StructuredBuffer <float4>(m_Device, RANDOM_TABLE_SIZE, true)); for (int i = 0; i < RANDOM_TABLE_SIZE; i++) { // m_SB_Random.m[i] = new float4( (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform() ); m_SB_Random.m[i] = new float4((float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform(), -(float)Math.Log(1e-3 + (1.0 - 1e-3) * SimpleRNG.GetUniform())); } m_SB_Random.Write(); }
public UILineRenderer(Device device, ShaderCache cache, int maximumLinesPerDraw = 2048) { instances = new StructuredBuffer <UILineInstance>(device, maximumLinesPerDraw, "UI Line Instances"); indices = new IndexBuffer(Helpers.GetQuadIndices(maximumLinesPerDraw), device, "UI Line Indices"); vertexConstants = new ConstantsBuffer <VertexConstants>(device, debugName: "UI Line Renderer Vertex Constants"); vertexShader = new VertexShader(device, cache.GetShader(@"UI\RenderUILines.hlsl.vshader")); pixelShader = new PixelShader(device, cache.GetShader(@"UI\RenderUILines.hlsl.pshader")); }
public LineRenderer(Device device, ShaderCache cache, int maximumInstancesPerDraw = 16384) { instances = new StructuredBuffer <LineInstance>(device, maximumInstancesPerDraw, "Line Instances"); indices = new IndexBuffer(Helpers.GetBoxIndices(maximumInstancesPerDraw), device, "Line Quad Indices"); vertexConstants = new ConstantsBuffer <VertexConstants>(device, debugName: "Line Renderer Vertex Constants"); vertexShader = new VertexShader(device, cache.GetShader(@"Constraints\RenderLines.hlsl.vshader")); pixelShader = new PixelShader(device, cache.GetShader(@"Constraints\RenderLines.hlsl.pshader")); }
public RasterizedRenderer(Device device, ShaderCache cache, string shaderPath, int maximumInstancesPerDraw = 2048) { string instanceTypeName = typeof(TInstance).Name; instances = new StructuredBuffer <TInstance>(device, maximumInstancesPerDraw, $"{instanceTypeName} Instances"); vertexConstants = new ConstantsBuffer <RasterizedVertexConstants>(device, debugName: $"{instanceTypeName} Renderer Vertex Constants"); vertexShader = new VertexShader(device, cache.GetShader($"{shaderPath}.vshader")); pixelShader = new PixelShader(device, cache.GetShader($"{shaderPath}.pshader")); }
public MeshCache(Device device, BufferPool pool, int initialSizeInVertices = 1 << 22) { Pool = pool; pool.TakeAtLeast(initialSizeInVertices, out vertices); TriangleBuffer = new StructuredBuffer <Vector3>(device, initialSizeInVertices, "Mesh Cache Vertex Buffer"); allocator = new Allocator(initialSizeInVertices, pool); pendingUploads = new QuickList <UploadRequest>(128, pool); requestedIds = new QuickList <ulong>(128, pool); previouslyAllocatedIds = new QuickSet <ulong, PrimitiveComparer <ulong> >(256, pool); }
/// <summary> /// Add services : /// </summary> protected override void Initialize () { // initialize services : base.Initialize(); // create structured buffers and shaders : argA = new StructuredBuffer( GraphicsDevice, typeof(float), BufferSize , StructuredBufferFlags.None ); argB = new StructuredBuffer( GraphicsDevice, typeof(float), BufferSize , StructuredBufferFlags.None ); result = new StructuredBuffer( GraphicsDevice, typeof(Result), BufferSize , StructuredBufferFlags.None ); paramsCB = new ConstantBuffer( GraphicsDevice, typeof(Params) ); shader = Content.Load<Ubershader>("test"); factory = new StateFactory( shader, typeof(ShaderFlags), Primitive.TriangleList, VertexInputElement.Empty ); // write data : var rand = new Random(); var a = Enumerable.Range(0, BufferSize).Select( i => rand.NextFloat(-1000,1000) ).ToArray(); var b = Enumerable.Range(0, BufferSize).Select( i => rand.NextFloat(-1000,1000) ).ToArray(); var r = Enumerable.Range(0, BufferSize).Select( i => new Result() ).ToArray(); argA.SetData( a ); argB.SetData( b ); paramsCB.SetData( new Params(){ Size = BufferSize } ); // bind objects : GraphicsDevice.SetCSRWBuffer( 0, argA ); GraphicsDevice.SetCSRWBuffer( 1, argB ); GraphicsDevice.SetCSRWBuffer( 2, result ); GraphicsDevice.ComputeShaderConstants[0] = paramsCB ; // set compute shader and dispatch threadblocks : GraphicsDevice.PipelineState = factory[0]; GraphicsDevice.Dispatch( MathUtil.IntDivUp(BufferSize,256) ); // get data : result.GetData( r ); Log.Message(" id : Sum Product gID gtID dtID gIdx"); for (int i=0; i<BufferSize; i++) { Log.Message("[{0,4}] : {1}", i, r[i] ); } // add keyboard handler : InputDevice.KeyDown += InputDevice_KeyDown; }
/// <summary> /// Add services : /// </summary> protected override void Initialize () { // initialize services : base.Initialize(); // create structured buffers and shaders : buffer1 = new StructuredBuffer( GraphicsDevice, typeof(Vector2), NumberOfElements , StructuredBufferFlags.None ); buffer2 = new StructuredBuffer( GraphicsDevice, typeof(Vector2), NumberOfElements , StructuredBufferFlags.None ); paramsCB = new ConstantBuffer( GraphicsDevice, typeof(Params) ); shader = Content.Load<Ubershader>("test"); factory = new StateFactory( shader, typeof(ShaderFlags), Primitive.TriangleList, VertexInputElement.Empty ); // // Create and write data : // var rand = new Random(); var input = Enumerable.Range(0, NumberOfElements).Select( i => new Vector2( rand.NextFloat(0,100), i ) ).ToArray(); buffer1.SetData( input ); // add keyboard handler : InputDevice.KeyDown += InputDevice_KeyDown; }
private void GenerateRays( int _raysCount, StructuredBuffer<float3> _target ) { _raysCount = Math.Min( MAX_THREADS, _raysCount ); // Half-Life 2 basis float3[] HL2Basis = new float3[] { new float3( (float) Math.Sqrt( 2.0 / 3.0 ), 0.0f, (float) Math.Sqrt( 1.0 / 3.0 ) ), new float3( -(float) Math.Sqrt( 1.0 / 6.0 ), (float) Math.Sqrt( 1.0 / 2.0 ), (float) Math.Sqrt( 1.0 / 3.0 ) ), new float3( -(float) Math.Sqrt( 1.0 / 6.0 ), -(float) Math.Sqrt( 1.0 / 2.0 ), (float) Math.Sqrt( 1.0 / 3.0 ) ) }; float centerTheta = (float) Math.Acos( HL2Basis[0].z ); float[] centerPhi = new float[] { (float) Math.Atan2( HL2Basis[0].y, HL2Basis[0].x ), (float) Math.Atan2( HL2Basis[1].y, HL2Basis[1].x ), (float) Math.Atan2( HL2Basis[2].y, HL2Basis[2].x ), }; for ( int rayIndex=0; rayIndex < _raysCount; rayIndex++ ) { double phi = (Math.PI / 3.0) * (2.0 * SimpleRNG.GetUniform() - 1.0); // Stratified version double theta = (Math.Acos( Math.Sqrt( (rayIndex + SimpleRNG.GetUniform()) / _raysCount ) )); // // Don't give a shit version (a.k.a. melonhead version) // // double Theta = Math.Acos( Math.Sqrt(WMath.SimpleRNG.GetUniform() ) ); // double Theta = 0.5 * Math.PI * WMath.SimpleRNG.GetUniform(); theta = Math.Min( 0.499f * Math.PI, theta ); double cosTheta = Math.Cos( theta ); double sinTheta = Math.Sin( theta ); double lengthFactor = 1.0 / sinTheta; // The ray is scaled so we ensure we always walk at least a texel in the texture cosTheta *= lengthFactor; sinTheta *= lengthFactor; // Yeah, yields 1... :) _target.m[0*MAX_THREADS+rayIndex].Set( (float) (Math.Cos( centerPhi[0] + phi ) * sinTheta), (float) (Math.Sin( centerPhi[0] + phi ) * sinTheta), (float) cosTheta ); _target.m[1*MAX_THREADS+rayIndex].Set( (float) (Math.Cos( centerPhi[1] + phi ) * sinTheta), (float) (Math.Sin( centerPhi[1] + phi ) * sinTheta), (float) cosTheta ); _target.m[2*MAX_THREADS+rayIndex].Set( (float) (Math.Cos( centerPhi[2] + phi ) * sinTheta), (float) (Math.Sin( centerPhi[2] + phi ) * sinTheta), (float) cosTheta ); } _target.Write(); }
/// <summary> /// /// </summary> public override void Initialize() { base.Initialize(); lightingCB = new ConstantBuffer( Game.GraphicsDevice, typeof(LightingParams) ); omniLightBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(OmniLightGPU), MaxOmniLights, StructuredBufferFlags.None ); spotLightBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(SpotLightGPU), MaxSpotLights, StructuredBufferFlags.None ); CreateShadowMaps(); CreateGBuffer(); Game.GraphicsDevice.DisplayBoundsChanged += (s,e) => CreateGBuffer(); LoadContent(); Game.Reloading += (s,e) => LoadContent(); }
public void SelectPath(ICollection<int> nodeIndices) { Deselect(); if (selectedNodesBuffer != null) { selectedNodesBuffer.Dispose(); } if (selectedEdgesBuffer != null) { selectedEdgesBuffer.Dispose(); } List<int> selEdges = new List<int>(); //nodeIndices = nodeIndices.Distinct().ToArray(); for(int i=0; i<nodeIndices.Count-1; i++) { int index1 = nodeIndices.ElementAt(i); int index2 = nodeIndices.ElementAt(i + 1); foreach (var indexEdge in edgeIndexLists[index1]) { if (edgeList[indexEdge].par1 == index1 && edgeList[indexEdge].par2 == index2 || edgeList[indexEdge].par2 == index1 && edgeList[indexEdge].par1 == index2) { selEdges.Add(indexEdge); } } } if (selEdges.Count() < 1) { return; } selectedNodesBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(int), nodeIndices.Count, StructuredBufferFlags.Counter); selectedEdgesBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(int), selEdges.Count, StructuredBufferFlags.Counter); selectedNodesBuffer.SetData(nodeIndices.ToArray()); selectedEdgesBuffer.SetData(selEdges.ToArray()); numSelectedNodes = nodeIndices.Count; numSelectedEdges = selEdges.Count; }
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(); } }
public override void Initialize() { base.Initialize(); plStruct = new PointLightStruct[maxLights]; pLightBuffer = new StructuredBuffer<PointLightStruct>(maxLights, false, true); string path = @"R:\Users\Rox Cox\Documents\Visual Studio 2013\Projects\LightingEngine_v2\LightingEngine_v2\LightingD3D11\HLSL\"; using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(path + "gbuffer.hlsl", "GBufferPS", "ps_5_0", ShaderFlags.Debug, EffectFlags.None, null, new IncludeFX(path))) { PS_GBuffer = new PixelShader(Renderer.Device, bytecode); } InitializeGBuffer(); }
public void Select(ICollection<int> nodeIndices) { Deselect(); if (selectedNodesBuffer != null) { selectedNodesBuffer.Dispose(); } if (selectedEdgesBuffer != null) { selectedEdgesBuffer.Dispose(); } List<int> selEdges = new List<int>(); foreach (var ind in nodeIndices) { foreach (var l in edgeIndexLists[ind]) { selEdges.Add(l); } } selectedNodesBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(int), nodeIndices.Count, StructuredBufferFlags.Counter); selectedEdgesBuffer = new StructuredBuffer(Game.GraphicsDevice, typeof(int), selEdges.Count, StructuredBufferFlags.Counter); selectedNodesBuffer.SetData(nodeIndices.ToArray()); selectedEdgesBuffer.SetData(selEdges.ToArray()); numSelectedNodes = nodeIndices.Count; numSelectedEdges = selEdges.Count; }
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> /// Fills structured buffer with given values /// </summary> /// <param name="buffer"></param> /// <param name="values"></param> public void Clear ( StructuredBuffer buffer, Int4 values ) { lock (deviceContext) { deviceContext.ClearUnorderedAccessView( buffer.UAV, SharpDXHelper.Convert( values ) ); } }
/// <summary> /// This function calculates the following values: /// 1. Total energy at (k+1)th iteration (from nextStateBuffer). /// 2. Dot product of kth descent vector and (k+1)th energy gradient (which equals minus (k+1)th descent vector) /// </summary> /// <param name="device"></param> /// <param name="currentStateBuffer"></param> /// <param name="nextStateBuffer"></param> /// <param name="outputValues"></param> /// <param name="parameters"></param> /// <param name="energy"></param> /// <param name="pTgradE"></param> public void CalcTotalEnergyAndDotProduct(StructuredBuffer currentStateBuffer, StructuredBuffer nextStateBuffer, StructuredBuffer outputValues, ComputeParams parameters, out float energy, out float pTgradE, out float checkSum) { parameters.MaxParticles = (uint)ParticleCount; energy = 0; pTgradE = 0; checkSum = 0; if (UseGPU) { // preform reduction on GPU: paramsCB.SetData(parameters); device.ComputeShaderConstants[0] = paramsCB; device.ComputeShaderResources[0] = currentStateBuffer; device.ComputeShaderResources[1] = nextStateBuffer; device.SetCSRWBuffer(1, outputValues, MathUtil.IntDivUp((int)parameters.MaxParticles, BlockSize)); device.PipelineState = factory[(int)ComputeFlags.COMPUTE | (int)ComputeFlags.REDUCTION]; device.Dispatch(MathUtil.IntDivUp((int)parameters.MaxParticles, BlockSize)); // perform final summation: Vector4[] valueBufferCPU = new Vector4[MathUtil.IntDivUp((int)parameters.MaxParticles, BlockSize)]; outputValues.GetData(valueBufferCPU); foreach (var value in valueBufferCPU) { energy += value.X; pTgradE += value.Y; checkSum += value.Z; } } else // if not use GPU { // perform summation on CPU: Particle3d[] currentBufferCPU = new Particle3d[parameters.MaxParticles]; Particle3d[] nextBufferCPU = new Particle3d[parameters.MaxParticles]; currentStateBuffer.GetData(currentBufferCPU); nextStateBuffer.GetData(nextBufferCPU); for (int i = 0; i < parameters.MaxParticles; ++i) { Vector3 force1 = currentBufferCPU[i].Force; Vector3 force2 = nextBufferCPU[i].Force; pTgradE += -1.0f * Vector3.Dot(force1, force2); energy += nextBufferCPU[i].Energy; checkSum += nextBufferCPU[i].Mass; } } energy /= 2; // because each pair is counted 2 times }
public void HighlightNodes(ICollection<int> nodeIndices, Color color) { if (!(nodeIndices.Count > 0)) { return; } StructuredBuffer buf = new StructuredBuffer( Game.GraphicsDevice, typeof(int), nodeIndices.Count, StructuredBufferFlags.Counter ); HighlightParams hParam = new HighlightParams{ color = color, number = nodeIndices.Count }; buf.SetData(nodeIndices.ToArray()); highlightNodesList.Add( new Tuple<StructuredBuffer,HighlightParams> (buf, hParam) ); }
/// <summary> /// This function takes vertices from the source buffer and moves them by /// descent vector times stepLength (Pk*stepLength). /// Then it writes them into the destination buffer with new positions. /// This function does not change data in the source buffer. /// </summary> /// <param name="device"></param> /// <param name="srcVertexBuffer"></param> /// <param name="dstVertexBuffer"></param> /// <param name="parameters"></param> public void MoveVertices(StructuredBuffer srcVertexBuffer, StructuredBuffer dstVertexBuffer, ComputeParams parameters) { parameters.MaxParticles = (uint)ParticleCount; paramsCB.SetData(parameters); device.ComputeShaderConstants[0] = paramsCB; device.ComputeShaderResources[0] = srcVertexBuffer; device.SetCSRWBuffer(0, dstVertexBuffer, (int)parameters.MaxParticles); device.PipelineState = factory[(int)(ComputeFlags.COMPUTE | ComputeFlags.MOVE)]; device.Dispatch(MathUtil.IntDivUp((int)parameters.MaxParticles, BlockSize)); device.ResetStates(); }
public void RefreshSparks() { if (sparkBuffer != null) { sparkBuffer.Dispose(); sparkBuffer = null; } if (sparkList.Count > 0) { sparkBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(Spark), sparkList.Count, StructuredBufferFlags.Counter ); sparkBuffer.SetData(sparkList.ToArray()); } }
/// <summary> /// /// </summary> /// <param name="register"></param> /// <param name="buffer"></param> /// <param name="initialCount">An array of append and consume buffer offsets. /// A value of -1 indicates to keep the current offset. /// Any other values set the hidden counter for that appendable and consumable UAV. </param> public void SetPSRWBuffer ( int register, StructuredBuffer buffer, int initialCount = -1 ) { if (register>8) { throw new GraphicsException("Could not bind RW buffer at register " + register.ToString() + " (max 8)"); } lock (deviceContext) { DeviceContext.OutputMerger.SetUnorderedAccessView ( register, buffer==null?null:buffer.UAV, initialCount ); } }
/// <summary> /// Load stuff here /// </summary> protected override void Initialize() { var device = GraphicsDevice; base.Initialize(); vb = new VertexBuffer(device, typeof(Vertex), 6 ); cb = new ConstantBuffer(GraphicsDevice, typeof(ConstData) ); instDataGpu = new StructuredBuffer( device, typeof(InstData), InstanceCount, StructuredBufferFlags.None ); instDataCpu = new InstData[ InstanceCount ]; var rand = new Random(); for (int i=0; i<InstanceCount; i++) { instDataCpu[ i ].Offset = rand.NextVector2( new Vector2(-2.5f,-2f), new Vector2( 2.5f,2f) ); instDataCpu[ i ].Scale = rand.NextFloat( 0, 0.7f); instDataCpu[ i ].Rotation = rand.NextFloat( 0, MathUtil.TwoPi ); instDataCpu[ i ].Color = rand.NextVector4( Vector4.Zero, Vector4.One * 0.7f ); instDataCpu[ i ].TexId = rand.Next(4); } Reloading += InstancingDemo_Reloading; InstancingDemo_Reloading ( this, EventArgs.Empty ); }
private void BuildRandomBuffer() { Reg( m_SB_Random = new StructuredBuffer<float4>( m_Device, RANDOM_TABLE_SIZE, true ) ); for ( int i=0; i < RANDOM_TABLE_SIZE; i++ ) // m_SB_Random.m[i] = new float4( (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform() ); m_SB_Random.m[i] = new float4( (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), -(float) Math.Log( 1e-3 + (1.0-1e-3) * SimpleRNG.GetUniform() ) ); m_SB_Random.Write(); }
public override void Initialize() { base.Initialize(); plStruct = new PointLightStruct[maxLights]; pLightBuffer = new StructuredBuffer<PointLightStruct>(maxLights, false, true); cBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 32, ShaderType.PixelShader, 0); cBuffer.Semantics.Add(Semantic.Projection); cBuffer.Semantics.Add(Semantic.CameraNearFar); GBuffer = new GBuffer(Renderer); BlendStateDescription disabledBlendDesc = States.BlendDefault(); BlendStateDescription additiveDesc = States.BlendDefault(); additiveDesc.RenderTargets[0] = new RenderTargetBlendDescription() { BlendEnable = true, SourceBlend = BlendOption.One, DestinationBlend = BlendOption.One, BlendOperation = BlendOperation.Add, SourceBlendAlpha = BlendOption.One, DestinationBlendAlpha = BlendOption.One, BlendOperationAlpha = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.All, }; DepthStencilStateDescription defaultDepthDesc = States.DepthDefault(); defaultDepthDesc.DepthComparison = Comparison.GreaterEqual; DepthStencilStateDescription equalDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.GreaterEqual, IsStencilEnabled = true, StencilWriteMask = 0xFF, StencilReadMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal, }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal, } }; DepthStencilStateDescription writeDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.GreaterEqual, IsStencilEnabled = true, StencilWriteMask = 0xFF, StencilReadMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Replace, DepthFailOperation = StencilOperation.Replace, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always, }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Replace, DepthFailOperation = StencilOperation.Replace, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always, } }; RasterizerStateDescription rsDesc = States.RasterizerDefault(); mGeometryBlendState = BlendState.FromDescription(Renderer.Device, disabledBlendDesc); mLightingBlendState = BlendState.FromDescription(Renderer.Device, additiveDesc); mDepthState = DepthStencilState.FromDescription(Renderer.Device, defaultDepthDesc); mEqualStencilState = DepthStencilState.FromDescription(Renderer.Device, equalDesc); mWriteStencilState = DepthStencilState.FromDescription(Renderer.Device, writeDesc); mRasterizerState = RasterizerState.FromDescription(Renderer.Device, rsDesc); InitializeBuffers(); InitializeShaders(); }
/// <summary> /// /// </summary> /// <param name="rs"></param> internal ParticleSystem ( RenderSystem rs, RenderWorld renderWorld ) { this.rs = rs; this.Game = rs.Game; this.renderWorld = renderWorld; Gravity = Vector3.Down * 9.80665f; paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(PrtParams) ); imagesCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Vector4), MaxImages ); injectionBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(Particle), MaxInjectingParticles, StructuredBufferFlags.None ); simulationBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(Particle), MaxSimulatedParticles, StructuredBufferFlags.None ); particleLighting = new StructuredBuffer( Game.GraphicsDevice, typeof(Vector4), MaxSimulatedParticles, StructuredBufferFlags.None ); sortParticlesBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(Vector2), MaxSimulatedParticles, StructuredBufferFlags.None ); deadParticlesIndices = new StructuredBuffer( Game.GraphicsDevice, typeof(uint), MaxSimulatedParticles, StructuredBufferFlags.Append ); rs.Game.Reloading += LoadContent; LoadContent(this, EventArgs.Empty); // initialize dead list : var device = Game.GraphicsDevice; device.SetCSRWBuffer( 1, deadParticlesIndices, 0 ); device.PipelineState = factory[ (int)Flags.INITIALIZE ]; device.Dispatch( MathUtil.IntDivUp( MaxSimulatedParticles, BlockSize ) ); }
void Application_Idle( object sender, EventArgs e ) { if ( m_Device == null || m_closing ) return; if ( m_Tex_CubeMap == null ) return; m_CB_Main.m._Resolution = new float3( panelOutput.Width, panelOutput.Height, 0 ); DateTime Now = DateTime.Now; float DeltaTime = (float) (Now - m_lastTime).TotalSeconds; m_lastTime = Now; m_CB_Main.m._GlobalTime = (float) (Now - m_startTime).TotalSeconds; m_CB_Main.UpdateData(); m_Device.SetRenderStates( RASTERIZER_STATE.CULL_NONE, DEPTHSTENCIL_STATE.DISABLED, BLEND_STATE.DISABLED ); ////////////////////////////////////////////////////////////////////////// // 1] Render to the HDR buffer if ( m_Shader_RenderHDR.Use() ) { m_Device.SetRenderTarget( m_Tex_HDR, null ); if ( m_Tex_CubeMap != null ) m_Tex_CubeMap.SetPS( 0 ); m_Device.RenderFullscreenQuad( m_Shader_RenderHDR ); } ////////////////////////////////////////////////////////////////////////// // 2] Compute auto-exposure if ( m_Shader_ComputeTallHistogram.Use() ) { // Build a 128xH "tall histogram" m_Device.RemoveRenderTargets(); m_Tex_HDR.SetCS( 0 ); m_Tex_TallHistogram.SetCSUAV( 0 ); m_Shader_ComputeTallHistogram.Dispatch( 1, m_Tex_TallHistogram.Height, 1 ); } if ( m_Shader_FinalizeHistogram.Use() ) { // Build the 128x1 standard histogram m_Tex_Histogram.SetCSUAV( 0 ); m_Tex_TallHistogram.SetCS( 0 ); m_Shader_FinalizeHistogram.Dispatch( 128, 1, 1 ); } if ( m_Shader_ComputeAutoExposure.Use() ) { // Compute auto-exposure from histogram and last value m_Buffer_AutoExposureSource.SetInput( 0 ); m_Buffer_AutoExposureTarget.SetOutput( 0 ); m_Tex_Histogram.SetCS( 1 ); float EV = floatTrackbarControlExposure.Value; m_CB_AutoExposure.m._delta_time = Math.Max( 0.01f, Math.Min( 1.0f, DeltaTime ) ); if ( checkBoxEnable.Checked && checkBoxAutoExposureUseWhiteLevel.Checked ) { m_CB_AutoExposure.m._white_level = tabControlToneMappingTypes.SelectedIndex == 0 ? floatTrackbarControlIG_WhitePoint.Value : floatTrackbarControlWhitePoint.Value; } else m_CB_AutoExposure.m._white_level = 1.0f; m_CB_AutoExposure.m._clip_shadows = 0.0f; // (0.0) Shadow cropping in histogram (first buckets will be ignored, leading to brighter image) m_CB_AutoExposure.m._clip_highlights = 1.0f; // (1.0) Highlights cropping in histogram (last buckets will be ignored, leading to darker image) m_CB_AutoExposure.m._EV = EV; // (0.0) Your typical EV setting m_CB_AutoExposure.m._fstop_bias = 0.0f; // (0.0) F-stop number bias to override automatic computation (NOTE: This will NOT change exposure, only the F number) m_CB_AutoExposure.m._reference_camera_fps = 30.0f; // (30.0) Default camera at 30 FPS m_CB_AutoExposure.m._adapt_min_luminance = m_advancedParmsForm.floatTrackbarControlMinLuminance.Value; // (0.03) Prevents the auto-exposure to adapt to luminances lower than this m_CB_AutoExposure.m._adapt_max_luminance = m_advancedParmsForm.floatTrackbarControlMaxLuminance.Value; // (2000.0) Prevents the auto-exposure to adapt to luminances higher than this m_CB_AutoExposure.m._adapt_speed_up = m_advancedParmsForm.floatTrackbarControlAdaptationSpeedBright.Value; // (0.99) Adaptation speed from low to high luminances m_CB_AutoExposure.m._adapt_speed_down = m_advancedParmsForm.floatTrackbarControlAdaptationSpeedDark.Value; // (0.99) Adaptation speed from high to low luminances m_CB_AutoExposure.UpdateData(); m_Shader_ComputeAutoExposure.Dispatch( 1, 1, 1 ); // Swap source & target for next frame StructuredBuffer<autoExposure_t> temp = m_Buffer_AutoExposureSource; m_Buffer_AutoExposureSource = m_Buffer_AutoExposureTarget; m_Buffer_AutoExposureTarget = temp; } ////////////////////////////////////////////////////////////////////////// // 3] Apply tone mapping if ( m_Shader_ToneMapping.Use() ) { m_Device.SetRenderTarget( m_Device.DefaultTarget, null ); float mouseU = 1.0f; float mouseV = 0.0f; Point clientMousePos = panelOutput.PointToClient( Control.MousePosition ); if ( clientMousePos.X >= 0 && clientMousePos.X < panelOutput.Width && clientMousePos.Y >= 0 && clientMousePos.Y < panelOutput.Height ) { mouseU = (float) clientMousePos.X / panelOutput.Width; mouseV = (float) clientMousePos.Y / panelOutput.Height; } m_CB_ToneMapping.m._Exposure = 1.0f;//(float) Math.Pow( 2, floatTrackbarControlExposure.Value ); m_CB_ToneMapping.m._Flags = (checkBoxEnable.Checked ? 1U : 0U) | (checkBoxDebugLuminanceLevel.Checked ? 2U : 0U) | (checkBoxShowHistogram.Checked ? 4U : 0U) | (tabControlToneMappingTypes.SelectedIndex == 0 ? 0U : 8U) | (checkBoxLuminanceOnly.Checked ? 16U : 0U); if ( tabControlToneMappingTypes.SelectedIndex == 0 ) { m_CB_ToneMapping.m._WhitePoint = floatTrackbarControlIG_WhitePoint.Value; m_CB_ToneMapping.m._A = floatTrackbarControlIG_BlackPoint.Value; m_CB_ToneMapping.m._B = Math.Min( m_CB_ToneMapping.m._WhitePoint-1e-3f, floatTrackbarControlIG_JunctionPoint.Value ); m_CB_ToneMapping.m._C = ComputeToeStrength();// floatTrackbarControlIG_ToeStrength.Value; m_CB_ToneMapping.m._D = ComputeShoulderStrength();// floatTrackbarControlIG_ShoulderStrength.Value; // Compute junction factor float b = m_CB_ToneMapping.m._A; float w = m_CB_ToneMapping.m._WhitePoint; float t = m_CB_ToneMapping.m._C; float s = m_CB_ToneMapping.m._D; float c = m_CB_ToneMapping.m._B; m_CB_ToneMapping.m._E = (1.0f - t) * (c - b) / ((1.0f - s) * (w - c) + (1.0f - t) * (c - b)); } else { // Hable Filmic m_CB_ToneMapping.m._WhitePoint = floatTrackbarControlWhitePoint.Value; m_CB_ToneMapping.m._A = floatTrackbarControlA.Value; m_CB_ToneMapping.m._B = floatTrackbarControlB.Value; m_CB_ToneMapping.m._C = floatTrackbarControlC.Value; m_CB_ToneMapping.m._D = floatTrackbarControlD.Value; m_CB_ToneMapping.m._E = floatTrackbarControlE.Value; m_CB_ToneMapping.m._F = floatTrackbarControlF.Value; } m_CB_ToneMapping.m._DebugLuminanceLevel = floatTrackbarControlDebugLuminanceLevel.Value; m_CB_ToneMapping.m._MouseU = mouseU; m_CB_ToneMapping.m._MouseV = mouseV; m_CB_ToneMapping.UpdateData(); m_Buffer_AutoExposureSource.SetInput( 0 ); m_Tex_Histogram.SetPS( 1 ); m_Tex_HDR.SetPS( 2 ); m_Tex_TallHistogram.SetPS( 3 ); m_Device.RenderFullscreenQuad( m_Shader_ToneMapping ); m_Tex_TallHistogram.RemoveFromLastAssignedSlots(); m_Tex_Histogram.RemoveFromLastAssignedSlots(); m_Tex_HDR.RemoveFromLastAssignedSlots(); } // Show! m_Device.Present( false ); }
private void BuildPhaseQuantileBuffer( System.IO.FileInfo _PhaseQuantileFileName ) { const int QUANTILES_COUNT = 65536; Reg( m_SB_PhaseQuantile = new StructuredBuffer<float>( m_Device, 2*QUANTILES_COUNT, true ) ); using ( System.IO.FileStream S = _PhaseQuantileFileName.OpenRead() ) using ( System.IO.BinaryReader R = new System.IO.BinaryReader( S ) ) { for ( int i=0; i < m_SB_PhaseQuantile.m.Length; i++ ) m_SB_PhaseQuantile.m[i] = R.ReadSingle(); } m_SB_PhaseQuantile.Write(); }
/// <summary> /// This function calculates two values: /// 1. Energy E for every vertex (N floats) /// 2. Descent vector which equals -grad(E) (3*N floats) /// Values are overwritten into the same buffer /// </summary> /// <param name="device"></param> /// <param name="rwVertexBuffer"></param> /// <param name="parameters"></param> public void CalcDescentVector(StructuredBuffer rwVertexBuffer, ComputeParams parameters) { parameters.MaxParticles = (uint)ParticleCount; paramsCB.SetData(parameters); device.ComputeShaderConstants[0] = paramsCB; device.SetCSRWBuffer(0, rwVertexBuffer, (int)parameters.MaxParticles); device.ComputeShaderResources[2] = LinksIndexBuffer; device.ComputeShaderResources[3] = LinksBuffer; device.ComputeShaderResources[4] = SelectBuffer; device.PipelineState = factory[(int)( ComputeFlags.COMPUTE | ComputeFlags.SIMULATION | ComputeFlags.EULER | ComputeFlags.LINKS)]; // device.PipelineState = factory[(int)( // ComputeFlags.COMPUTE | ComputeFlags.SIMULATION | // ComputeFlags.EULER)]; device.Dispatch(MathUtil.IntDivUp((int)parameters.MaxParticles, BlockSize)); // device.ResetStates(); // add localization forces: device.PipelineState = factory[(int)(ComputeFlags.COMPUTE | ComputeFlags.LOCAL)]; if (categories.Count > 0) { foreach (var cat in categories) { parameters.LocalCenter = new Vector4(cat.Center, 0); parameters.LocalRadius = cat.Radius; parameters.StartIndex = cat.startIndex; parameters.EndIndex = cat.endIndex; paramsCB.SetData(parameters); // device.ComputeShaderConstants[0] = paramsCB; device.Dispatch(MathUtil.IntDivUp((int)(cat.endIndex - cat.startIndex), BlockSize)); } } device.ResetStates(); }
public void SetData(List<Particle3d> ParticleList, List<Link> linkList, List<List<int>> linkIndexLists) { numParticles = ParticleList.Count; numLinks = linkList.Count; Particle3d[] particleBufferCPU = ParticleList.ToArray(); Link[] linksBufferCPU = linkList.ToArray(); LinkId[] linksPtrBufferCPU = new LinkId[linkList.Count * 2]; int iter = 0; int lpIter = 0; foreach (var ptrList in linkIndexLists) { int blockSize = 0; particleBufferCPU[iter].linksPtr = lpIter; if (ptrList != null) { foreach (var linkPtr in ptrList) { linksPtrBufferCPU[lpIter] = new LinkId { id = linkPtr }; ++lpIter; ++blockSize; } } particleBufferCPU[iter].linksCount = blockSize; ++iter; } disposeOfBuffers(); if (particleBufferCPU.Length != 0) { CurrentStateBuffer = new StructuredBuffer(env.GraphicsDevice, typeof(Particle3d), particleBufferCPU.Length, StructuredBufferFlags.Counter); NextStateBuffer = new StructuredBuffer(env.GraphicsDevice, typeof(Particle3d), particleBufferCPU.Length, StructuredBufferFlags.Counter); CurrentStateBuffer.SetData(particleBufferCPU); EnergyBuffer = new StructuredBuffer( env.GraphicsDevice, typeof(Vector4), MathUtil.IntDivUp(particleBufferCPU.Length, BlockSize), StructuredBufferFlags.Counter); if (linksBufferCPU.Length != 0) { LinksBuffer = new StructuredBuffer( env.GraphicsDevice, typeof(Link), linksBufferCPU.Length, StructuredBufferFlags.Counter); LinksBuffer.SetData(linksBufferCPU); } if (linksPtrBufferCPU.Length != 0) { LinksIndexBuffer = new StructuredBuffer( env.GraphicsDevice, typeof(LinkId), linksPtrBufferCPU.Length, StructuredBufferFlags.Counter); LinksIndexBuffer.SetData(linksPtrBufferCPU); } if (categoryIndices.Count > 0) { SelectBuffer = new StructuredBuffer( env.GraphicsDevice, typeof(int), categoryIndices.Count, StructuredBufferFlags.Counter); SelectBuffer.SetData(categoryIndices.ToArray()); } // Test stuff: //////////////////////////////////// // List<int> indices = new List<int>(); // for (int i = 0; i < particleBufferCPU.Length; ++i) // { // indices.Add(i); // } //////////////////////////////////////////////////// initializeCalc(); } }
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 ) ); }
/// <summary> /// /// </summary> public override void Initialize() { paramsCB = new ConstantBuffer( Game.GraphicsDevice, typeof(Params) ); injectionBuffer = new StructuredBuffer( Game.GraphicsDevice, typeof(Particle), MaxInjectingParticles, StructuredBufferFlags.None ); simulationBufferSrc = new StructuredBuffer( Game.GraphicsDevice, typeof(Particle), MaxSimulatedParticles, StructuredBufferFlags.Append ); simulationBufferDst = new StructuredBuffer( Game.GraphicsDevice, typeof(Particle), MaxSimulatedParticles, StructuredBufferFlags.Append ); base.Initialize(); Game.Reloading += Game_Reloading; Game_Reloading(this, EventArgs.Empty); }
public override void Initialize() { base.Initialize(); plStruct = new PointLightStruct[maxLights]; pLightBuffer = new StructuredBuffer<PointLightStruct>(maxLights, false, true); string path = @"R:\Users\Rox Cox\Documents\Visual Studio 2013\Projects\LightingEngine_v2\LightingEngine_v2\LightingD3D11\HLSL\"; ShaderFlags flags = ShaderFlags.Debug | ShaderFlags.EnableStrictness | ShaderFlags.PackMatrixRowMajor; using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(path + "forward.hlsl", "ForwardPS", "ps_5_0", flags, EffectFlags.None, null, new IncludeFX(path))) { PS_PointLights = new PixelShader(Renderer.Device, bytecode); } DepthStencilStateDescription dssdesc = States.DepthDefault(); dssdesc.DepthComparison = Comparison.GreaterEqual; dss = DepthStencilState.FromDescription(Renderer.Device, dssdesc); }
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; }