public void Add(GPUBuffer buffer, params string[] aliases) { foreach (var name in aliases) { buffers[name] = buffer; } }
public static void Init( ) { VERTEX_BUFFER = new GPUBuffer(2, 4, BufferPrimitiveType.Quad, new float[] { -1f, 1f, -1f, -1f, 1f, -1f, 1f, 1f }, BufferUsage.StaticDraw); TEXTURE_BUFFER = new GPUBuffer(2, 4, BufferPrimitiveType.Quad, new float[] { 0, 1, 0, 0, 1, 0, 1, 1 }, BufferUsage.StaticDraw); INDEX_BUFFER = new IndexBuffer(1); Program = new GaussianBlurProgram( ); }
public void InitBuffers() { BufferStreamer.QueueTask((a) => { if (vArray == null) { vArray = new VertexArray(); } if (vBuf != null) { vBuf.Dispose(); } vBuf = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer, Side * Side * Side * 16, false); //vBuf = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); //vBuf.BufferData(0, vertex.ToArray(), OpenTK.Graphics.OpenGL4.BufferUsageHint.StaticDraw); vArray.SetBufferObject(0, vBuf, 4, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Int2101010Rev); if (vMat != null) { vMat.Dispose(); } vMat = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer, Side * Side * Side * 8, false); //vMat = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); //vMat.BufferData(0, mat.ToArray(), OpenTK.Graphics.OpenGL4.BufferUsageHint.StaticDraw); vArray.SetBufferObject(1, vMat, 1, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Short); }, null); }
private void TestWriting() { GPUBuffer testBuffer = null; try { float[] data = new float[1024]; testBuffer = Gpu.CreateBuffer(data.Length, sizeof(float), true); // initialize the buffer to 0's this.Gpu.Write(testBuffer, data); float[] op = new float[2]; for (int i = 0; i < data.Length; i += 2) { op[0] = i; op[1] = i * 2; this.Gpu.Write(testBuffer, op, 0, i, op.Length); } // read the results back in this.Gpu.Read(testBuffer, data); this.Gpu.Wait(); } finally { if (testBuffer != null) { Gpu.ReleaseBuffer(testBuffer); testBuffer = null; } } }
public EnvironmentCube(string cubemapPath, PipelineLayout plLayout, Queue staggingQ, RenderPass renderPass, PipelineCache cache = null) : base(renderPass, cache, "EnvCube pipeline") { using (GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, renderPass.Samples, false)) { cfg.RenderPass = renderPass; cfg.Layout = plLayout; cfg.AddVertexBinding(0, 3 * sizeof(float)); cfg.AddVertexAttributes(0, VkFormat.R32g32b32Sfloat); cfg.AddShaders( new ShaderInfo(Dev, VkShaderStageFlags.Vertex, "#EnvironmentPipeline.skybox.vert.spv"), new ShaderInfo(Dev, VkShaderStageFlags.Fragment, STR_FRAG_PATH) ); cfg.multisampleState.rasterizationSamples = Samples; layout = cfg.Layout; init(cfg); } using (CommandPool cmdPool = new CommandPool(staggingQ.Dev, staggingQ.index)) { vboSkybox = new GPUBuffer <float> (staggingQ, cmdPool, VkBufferUsageFlags.VertexBuffer, box_vertices); cubemap = KTX.KTX.Load(staggingQ, cmdPool, cubemapPath, VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, true); cubemap.CreateView(VkImageViewType.Cube, VkImageAspectFlags.Color); cubemap.CreateSampler(VkSamplerAddressMode.ClampToEdge); cubemap.SetName("skybox Texture"); cubemap.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; generateBRDFLUT(staggingQ, cmdPool); generateCubemaps(staggingQ, cmdPool); } }
internal void ApplyPass(ComputeShader adder, GPUBuffer constant, int index) { if (PassLength > 0) { adder.NumberOfXThreads = this.BufferSize / 512; Gpu.ExecuteComputeShader(adder); } }
public ComputeBuffer Add(ComputeBuffer buffer, params string[] aliases) { foreach (var name in aliases) { buffers[name] = new GPUBuffer(buffer); } return(buffer); }
public static void DynamicBuffer(GPUBuffer dynamicBuffer, int width, GraphicsContext graphicsContext) { if (width != dynamicBuffer.size) { dynamicBuffer.size = width; graphicsContext.UpdateDynamicBuffer(dynamicBuffer); } }
public EngineObject() { mesh = new VertexArray(); verts = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); indices = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ElementArrayBuffer); uvs = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); norms = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); textures = new List<Texture>(); }
public EngineObject() { mesh = new VertexArray(); verts = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); indices = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ElementArrayBuffer); uvs = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); norms = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); textures = new List <Texture>(); }
/// <summary> /// Frees the underlying CPU and GPU memory handles. /// </summary> protected override void DisposeAcceleratorObject(bool disposing) { if (!disposing) { return; } CPUBuffer.Dispose(); GPUBuffer.Dispose(); }
public void SetBufferObject(int index, GPUBuffer buffer, int elementCount, VertexAttribPointerType type) { GPUStateMachine.BindVertexArray(id); GL.EnableVertexAttribArray(index); GPUStateMachine.BindBuffer(buffer.target, buffer.id); GL.VertexAttribPointer(index, elementCount, type, false, 0, 0); GPUStateMachine.UnbindBuffer(buffer.target); GPUStateMachine.UnbindVertexArray(); }
private void CreateBuffers() { var squareSize = length * length; flowsBuffer = gpu.CreateBuffer(squareSize, 4, true); attractionStarBuffer = gpu.CreateBuffer(length, 4, true); balancedBuffer = gpu.CreateBuffer(2, 4, true); productionBuffer = gpu.CreateBuffer(length, 4, false); attractionBuffer = gpu.CreateBuffer(length, 4, false); frictionBuffer = gpu.CreateBuffer(squareSize, 4, false); parameters = gpu.CreateConstantBuffer(16); }
public EngineObject(EngineObject src, bool lockChanges) { mesh = src.mesh; verts = src.verts; indices = src.indices; uvs = src.uvs; norms = src.norms; IndexCount = src.IndexCount; textures = new List<Texture>(); lock_changes = lockChanges; }
public EngineObject(EngineObject src, bool lockChanges) { mesh = src.mesh; verts = src.verts; indices = src.indices; uvs = src.uvs; norms = src.norms; IndexCount = src.IndexCount; textures = new List <Texture>(); lock_changes = lockChanges; }
public GPUSimulation(FiniteDeformationMesh mesh) { this.mesh = mesh; buffers = new BuffersHelper(); nodes = new GPUBuffer <Node>(mesh.nodes); buffers.Add(nodes, "nodes"); buffers.Add(new GPUBuffer <Edge>(mesh.edges), "edges"); buffers.Add(new GPUBuffer <Constraint>(mesh.totalconstraints), "constraints"); deformationshader = new ShaderWrapper("DeformationModel"); deformationshader.Shader.SetInt("numnodes", mesh.nodes.Length); deformationshader.Shader.SetInt("numedges", mesh.edges.Length); buffers.SetBuffers(deformationshader.Shader, 0, 1, 2, 3); }
private int Balance(GPU gpu, ComputeShader gravityModelShader, GPUBuffer balancedBuffer, GPUBuffer parameters, float[] balanced, int iterations, int[] step1, int[] step2) { do { 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); return(iterations); }
public void UpdateBuffers() { if (mappingData == null | ColorData == null) { mappingData = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.TextureBuffer); ColorData = new BufferTexture(); } Vector4[] cols = new Vector4[Voxels.Count]; for (int i = 0; i < cols.Length; i++) { cols[i] = Voxels[i].Color; } mappingData.BufferData(0, cols, OpenTK.Graphics.OpenGL4.BufferUsageHint.StaticDraw); ColorData.SetStorage(mappingData, OpenTK.Graphics.OpenGL4.SizedInternalFormat.Rgba32f); }
protected override void initVulkan() { base.initVulkan(); cmds = cmdPool.AllocateCommandBuffer(swapChain.ImageCount); loadTexture(imgPathes[currentImgIndex]); vbo = new GPUBuffer <float> (presentQueue, cmdPool, VkBufferUsageFlags.VertexBuffer, vertices); ibo = new GPUBuffer <ushort> (presentQueue, cmdPool, VkBufferUsageFlags.IndexBuffer, indices); descriptorPool = new DescriptorPool(dev, 1, new VkDescriptorPoolSize(VkDescriptorType.UniformBuffer), new VkDescriptorPoolSize(VkDescriptorType.CombinedImageSampler) ); dsLayout = new DescriptorSetLayout(dev, 0, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Vertex, VkDescriptorType.UniformBuffer), new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler)); using (GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount4)) { cfg.Layout = new PipelineLayout(dev, dsLayout); cfg.RenderPass = new RenderPass(dev, swapChain.ColorFormat, dev.GetSuitableDepthFormat(), cfg.Samples); cfg.AddVertexBinding(0, 5 * sizeof(float)); cfg.AddVertexAttributes(0, VkFormat.R32g32b32Sfloat, VkFormat.R32g32Sfloat); cfg.AddShader(dev, VkShaderStageFlags.Vertex, "#shaders.main.vert.spv"); cfg.AddShader(dev, VkShaderStageFlags.Fragment, "#shaders.main.frag.spv"); pipeline = new GraphicPipeline(cfg); } uboMats = new HostBuffer(dev, VkBufferUsageFlags.UniformBuffer, matrices); uboMats.Map(); //permanent map descriptorSet = descriptorPool.Allocate(dsLayout); updateTextureSet(); DescriptorSetWrites uboUpdate = new DescriptorSetWrites(descriptorSet, dsLayout.Bindings[0]); uboUpdate.Write(dev, uboMats.Descriptor); }
public void InitBuffers() { BufferStreamer.QueueTask((a) => { if (vArray == null) vArray = new VertexArray(); if (vBuf != null) vBuf.Dispose(); vBuf = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer, Side * Side * Side * 16, false); //vBuf = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); //vBuf.BufferData(0, vertex.ToArray(), OpenTK.Graphics.OpenGL4.BufferUsageHint.StaticDraw); vArray.SetBufferObject(0, vBuf, 4, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Int2101010Rev); if (vMat != null) vMat.Dispose(); vMat = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer, Side * Side * Side * 8, false); //vMat = new GPUBuffer(OpenTK.Graphics.OpenGL4.BufferTarget.ArrayBuffer); //vMat.BufferData(0, mat.ToArray(), OpenTK.Graphics.OpenGL4.BufferUsageHint.StaticDraw); vArray.SetBufferObject(1, vMat, 1, OpenTK.Graphics.OpenGL4.VertexAttribPointerType.Short); }, null); }
protected void loadSolids <VX> (glTFLoader ctx) { ulong vertexCount, indexCount; ctx.GetVertexCount(out vertexCount, out indexCount, out IndexBufferType); ulong vertSize = vertexCount * (ulong)Marshal.SizeOf <VX> (); ulong idxSize = indexCount * (IndexBufferType == VkIndexType.Uint16 ? 2ul : 4ul); ulong size = vertSize + idxSize; vbo = new GPUBuffer(dev, VkBufferUsageFlags.VertexBuffer | VkBufferUsageFlags.TransferDst, vertSize); ibo = new GPUBuffer(dev, VkBufferUsageFlags.IndexBuffer | VkBufferUsageFlags.TransferDst, idxSize); vbo.SetName("vbo gltf"); ibo.SetName("ibo gltf"); Meshes = new List <Mesh> (ctx.LoadMeshes <VX> (IndexBufferType, vbo, 0, ibo, 0)); Scenes = new List <Scene> (ctx.LoadScenes(out defaultSceneIndex)); }
void InitComputeShaders() { m_particleWarpCount = Mathf.CeilToInt((float)m_particleCount / WARP_SIZE); m_cellWarpCount = Mathf.CeilToInt((float)m_cellCount / WARP_SIZE); m_particleBuffer = new GPUBuffer <Particle>(m_particleCount); m_sumBuffer = new GPUBuffer <Vector3>(m_particleCount); for (int i = 0; i < m_particleCount; i++) { m_particleBuffer.CPUData[i].position = Random.insideUnitSphere; m_particleBuffer.CPUData[i].velocity = Random.insideUnitSphere; } m_particleBuffer.Upload(); m_offsetBuffer = new GPUBuffer <int>(m_cellCount); m_sortedIndexBuffer = new GPUBuffer <int>(m_particleCount); foreach (var kernelName in m_kernelNames) { m_kernels[kernelName] = m_computeShader.FindKernel(kernelName); } m_computeShader.SetBuffer(m_kernels["Integrate"], "_particleBuffer", m_particleBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["Integrate"], "_sortedIndexBuffer", m_sortedIndexBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["Integrate"], "_cellOffsetBuffer", m_offsetBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["ResetIndices"], "_sortedIndexBuffer", m_sortedIndexBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["ZeroOutOffsets"], "_cellOffsetBuffer", m_offsetBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["SortBuffer"], "_particleBuffer", m_particleBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["SortBuffer"], "_sortedIndexBuffer", m_sortedIndexBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["CalculateOffsets"], "_particleBuffer", m_particleBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["CalculateOffsets"], "_sortedIndexBuffer", m_sortedIndexBuffer.Buffer); m_computeShader.SetBuffer(m_kernels["CalculateOffsets"], "_cellOffsetBuffer", m_offsetBuffer.Buffer); m_material.SetBuffer("particleBuffer", m_particleBuffer.Buffer); }
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; }
private void CreateBuffers() { var squareSize = length * length; flowsBuffer = gpu.CreateBuffer( squareSize, 4, true ); attractionStarBuffer = gpu.CreateBuffer( length, 4, true ); balancedBuffer = gpu.CreateBuffer( 2, 4, true ); productionBuffer = gpu.CreateBuffer( length, 4, false ); attractionBuffer = gpu.CreateBuffer( length, 4, false ); frictionBuffer = gpu.CreateBuffer( squareSize, 4, false ); parameters = gpu.CreateConstantBuffer( 16 ); }
public void SetStorage(GPUBuffer storage, SizedInternalFormat internalFormat) { GPUStateMachine.BindTexture(0, TextureTarget.TextureBuffer, id); GL.TexBuffer(TextureBufferTarget.TextureBuffer, internalFormat, storage.id); GPUStateMachine.UnbindTexture(0, TextureTarget.TextureBuffer); }
public Program() : base() { #if DEBUG dbgReport = new DebugReport(instance, VkDebugReportFlagsEXT.ErrorEXT | VkDebugReportFlagsEXT.DebugEXT | VkDebugReportFlagsEXT.WarningEXT | VkDebugReportFlagsEXT.PerformanceWarningEXT ); #endif imgResult = new Image(dev, VkFormat.R32g32b32a32Sfloat, VkImageUsageFlags.TransferDst | VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, IMG_DIM, IMG_DIM); imgResult.CreateView(); imgResult.CreateSampler(VkFilter.Nearest, VkFilter.Nearest, VkSamplerMipmapMode.Nearest, VkSamplerAddressMode.ClampToBorder); imgResult.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; staggingVBO = new HostBuffer <Vector2> (dev, VkBufferUsageFlags.TransferSrc, MAX_VERTICES); staggingVBO.Map(); vbo = new GPUBuffer <Vector2> (dev, VkBufferUsageFlags.VertexBuffer | VkBufferUsageFlags.StorageBuffer | VkBufferUsageFlags.TransferDst, MAX_VERTICES); ibo = new GPUBuffer <uint> (dev, VkBufferUsageFlags.IndexBuffer | VkBufferUsageFlags.StorageBuffer, MAX_VERTICES * 3); inBuff = new GPUBuffer <float> (dev, VkBufferUsageFlags.StorageBuffer | VkBufferUsageFlags.TransferSrc | VkBufferUsageFlags.TransferDst, (int)data_size); outBuff = new GPUBuffer <float> (dev, VkBufferUsageFlags.StorageBuffer | VkBufferUsageFlags.TransferSrc | VkBufferUsageFlags.TransferDst, (int)data_size); dsPool = new DescriptorPool(dev, 4, new VkDescriptorPoolSize(VkDescriptorType.CombinedImageSampler), new VkDescriptorPoolSize(VkDescriptorType.StorageBuffer, 6)); dslImage = new DescriptorSetLayout(dev, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler) ); dslCompute = new DescriptorSetLayout(dev, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Compute, VkDescriptorType.StorageBuffer), new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Compute, VkDescriptorType.StorageBuffer) ); dslVAO = new DescriptorSetLayout(dev, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Compute, VkDescriptorType.StorageBuffer), new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Compute, VkDescriptorType.StorageBuffer) ); plInit = new ComputePipeline( new PipelineLayout(dev, new VkPushConstantRange(VkShaderStageFlags.Compute, 3 * sizeof(int)), dslCompute, dslVAO), "shaders/init.comp.spv"); plCompute = new ComputePipeline(plInit.Layout, "shaders/computeTest.comp.spv"); plNormalize = new ComputePipeline(plInit.Layout, "shaders/normalize.comp.spv"); GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount1); cfg.Layout = new PipelineLayout(dev, dslImage); cfg.RenderPass = new RenderPass(dev, swapChain.ColorFormat, dev.GetSuitableDepthFormat(), VkSampleCountFlags.SampleCount1); cfg.RenderPass.ClearValues[0] = new VkClearValue { color = new VkClearColorValue(0.1f, 0.1f, 0.1f) }; cfg.AddShader(VkShaderStageFlags.Vertex, "shaders/FullScreenQuad.vert.spv"); cfg.AddShader(VkShaderStageFlags.Fragment, "shaders/simpletexture.frag.spv"); cfg.blendAttachments[0] = new VkPipelineColorBlendAttachmentState(true); grPipeline = new GraphicPipeline(cfg); cfg.ResetShadersAndVerticesInfos(); cfg.Layout = new PipelineLayout(dev, new VkPushConstantRange(VkShaderStageFlags.Vertex, 4 * sizeof(int))); cfg.inputAssemblyState.topology = VkPrimitiveTopology.LineStrip; cfg.AddVertexBinding <Vector2> (0); cfg.SetVertexAttributes(0, VkFormat.R32g32Sfloat); cfg.AddShader(VkShaderStageFlags.Vertex, "shaders/triangle.vert.spv"); cfg.AddShader(VkShaderStageFlags.Fragment, "shaders/triangle.frag.spv"); trianglesPipeline = new GraphicPipeline(cfg); dsImage = dsPool.Allocate(dslImage); dsPing = dsPool.Allocate(dslCompute); dsPong = dsPool.Allocate(dslCompute); dsVAO = dsPool.Allocate(dslCompute); DescriptorSetWrites dsUpdate = new DescriptorSetWrites(dsPing, dslCompute); dsUpdate.Write(dev, inBuff.Descriptor, outBuff.Descriptor); dsUpdate.Write(dev, dsPong, outBuff.Descriptor, inBuff.Descriptor); dsUpdate = new DescriptorSetWrites(dsImage, dslImage); dsUpdate.Write(dev, imgResult.Descriptor); dsUpdate = new DescriptorSetWrites(dsVAO, dslVAO); dsUpdate.Write(dev, vbo.Descriptor, ibo.Descriptor); UpdateFrequency = 5; addPoint(IMG_DIM / 2 - 1, IMG_DIM / 2 - 1); }
public Program() : base() { if (Instance.DEBUG_UTILS) { dbgReport = new DebugReport(instance, VkDebugReportFlagsEXT.ErrorEXT | VkDebugReportFlagsEXT.DebugEXT | VkDebugReportFlagsEXT.WarningEXT | VkDebugReportFlagsEXT.PerformanceWarningEXT ); } imgResult = new Image(dev, VkFormat.R32g32b32a32Sfloat, VkImageUsageFlags.TransferDst | VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, imgDim, imgDim); imgResult.CreateView(); imgResult.CreateSampler(VkFilter.Nearest, VkFilter.Nearest, VkSamplerMipmapMode.Nearest, VkSamplerAddressMode.ClampToBorder); imgResult.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; datas = new float[data_size]; addSeed(imgDim / 2 - 1, imgDim / 2 - 1); stagingDataBuff = new HostBuffer <float> (dev, VkBufferUsageFlags.TransferSrc, datas); stagingDataBuff.Map(); inBuff = new GPUBuffer <float> (dev, VkBufferUsageFlags.StorageBuffer | VkBufferUsageFlags.TransferSrc | VkBufferUsageFlags.TransferDst, (int)data_size); outBuff = new GPUBuffer <float> (dev, VkBufferUsageFlags.StorageBuffer | VkBufferUsageFlags.TransferSrc, (int)data_size); dsPool = new DescriptorPool(dev, 3, new VkDescriptorPoolSize(VkDescriptorType.CombinedImageSampler), new VkDescriptorPoolSize(VkDescriptorType.StorageBuffer, 4)); dslImage = new DescriptorSetLayout(dev, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler) ); dslCompute = new DescriptorSetLayout(dev, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Compute, VkDescriptorType.StorageBuffer), new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Compute, VkDescriptorType.StorageBuffer) ); GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount1); cfg.Layout = new PipelineLayout(dev, dslImage); cfg.RenderPass = new RenderPass(dev, swapChain.ColorFormat, dev.GetSuitableDepthFormat(), VkSampleCountFlags.SampleCount1); cfg.RenderPass.ClearValues[0] = new VkClearValue { color = new VkClearColorValue(0.0f, 0.1f, 0.0f) }; cfg.ResetShadersAndVerticesInfos(); cfg.AddShader(VkShaderStageFlags.Vertex, "shaders/FullScreenQuad.vert.spv"); cfg.AddShader(VkShaderStageFlags.Fragment, "shaders/simpletexture.frag.spv"); cfg.blendAttachments[0] = new VkPipelineColorBlendAttachmentState(true); grPipeline = new GraphicPipeline(cfg); plCompute = new ComputePipeline( new PipelineLayout(dev, new VkPushConstantRange(VkShaderStageFlags.Compute, 2 * sizeof(int)), dslCompute), "shaders/computeTest.comp.spv"); plNormalize = new ComputePipeline( plCompute.Layout, "shaders/normalize.comp.spv"); dsImage = dsPool.Allocate(dslImage); dsetPing = dsPool.Allocate(dslCompute); dsetPong = dsPool.Allocate(dslCompute); DescriptorSetWrites dsUpdate = new DescriptorSetWrites(dsetPing, dslCompute); dsUpdate.Write(dev, inBuff.Descriptor, outBuff.Descriptor); dsUpdate.Write(dev, dsetPong, outBuff.Descriptor, inBuff.Descriptor); dsUpdate = new DescriptorSetWrites(dsImage, dslImage); dsUpdate.Write(dev, imgResult.Descriptor); UpdateFrequency = 5; }
void Init() { if (_screenTex != null) { _screenTex?.Release(); } _screenTex = null; if (_screenTexSwap != null) { _screenTexSwap?.Release(); } _screenTexSwap = null; if (_lumaTex != null) { _lumaTex?.Release(); } _lumaTex = null; if (_postTex != null) { _postTex?.Release(); } _postTex = null; m_particleBuffer?.Dispose(); m_particleBuffer = new GPUBuffer <Agent>(m_particleCount); for (int i = 0; i < m_particleCount; i++) { m_particleBuffer.CPUData[i].posX = Random.value; m_particleBuffer.CPUData[i].posY = Random.value; m_particleBuffer.CPUData[i].direction = Random.value * Mathf.PI * 2; m_particleBuffer.CPUData[i].age = Random.value * _maxLifetime; m_particleBuffer.CPUData[i].random = Random.value * 2 - 1; } m_particleBuffer.Upload(); // textures m_fieldA = new RenderTexture(_resultTexture.width, _resultTexture.height, 0, RenderTextureFormat.ARGBFloat); m_fieldA.filterMode = FilterMode.Bilinear; m_fieldA.wrapMode = TextureWrapMode.Repeat; m_fieldA.enableRandomWrite = true; m_fieldA.Create(); m_fieldB = new RenderTexture(_resultTexture.width, _resultTexture.height, 0, RenderTextureFormat.ARGBFloat); m_fieldB.filterMode = FilterMode.Bilinear; m_fieldB.wrapMode = TextureWrapMode.Repeat; m_fieldB.enableRandomWrite = true; m_fieldB.Create(); m_material.mainTexture = _screenTex; foreach (var k in m_fieldKernelNames) { m_kernels[k] = m_fieldShader.FindKernel(k); } m_gradientTexture = new Texture2D(128, 1); m_gradientTexture.wrapMode = TextureWrapMode.Clamp; m_lumaGradientTexture = new Texture2D(128, 1); m_lumaGradientTexture.wrapMode = TextureWrapMode.Clamp; UpdateGradientTextures(); }
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 ); }
public SparseTwinIndex <float> ProcessFlow(SparseArray <float> O, SparseArray <float> D) { float[] o = O.GetFlatData(); float[] d = D.GetFlatData(); var oLength = o.Length; var dLength = d.Length; var squareSize = oLength * dLength; float[] flows = new float[squareSize]; float[] residules = new float[dLength]; GPU gpu = new GPU(); string programPath; var codeBase = Assembly.GetEntryAssembly().CodeBase; try { programPath = Path.GetFullPath(codeBase); } catch { programPath = codeBase.Replace("file:///", String.Empty); } // Since the modules are always located in the ~/Modules subdirectory for XTMF, // we can just go in there to find the script ComputeShader gravityModelShader = null; Task compile = new Task(delegate() { gravityModelShader = gpu.CompileComputeShader(Path.Combine(Path.GetDirectoryName(programPath), "Modules", "GravityModel.hlsl"), "CSMain"); gravityModelShader.NumberOfXThreads = oLength; gravityModelShader.NumberOfYThreads = 1; gravityModelShader.ThreadGroupSizeX = 64; gravityModelShader.ThreadGroupSizeY = 1; }); compile.Start(); GPUBuffer flowsBuffer = gpu.CreateBuffer(squareSize, 4, true); GPUBuffer attractionStarBuffer = gpu.CreateBuffer(oLength, 4, true); GPUBuffer balancedBuffer = gpu.CreateBuffer(2, 4, true); GPUBuffer productionBuffer = gpu.CreateBuffer(dLength, 4, false); GPUBuffer attractionBuffer = gpu.CreateBuffer(oLength, 4, false); GPUBuffer frictionBuffer = gpu.CreateBuffer(squareSize, 4, false); GPUBuffer parameters = gpu.CreateConstantBuffer(16); float[] balanced = new float[] { 0, this.Epsilon }; int iterations = 0; var step1 = new int[] { oLength, 0, this.MaxIterations }; var step2 = new int[] { oLength, 1, this.MaxIterations }; compile.Wait(); Stopwatch watch = new Stopwatch(); watch.Start(); FillAndLoadBuffers(o, d, Friction, gpu, gravityModelShader, flowsBuffer, attractionStarBuffer, balancedBuffer, productionBuffer, attractionBuffer, frictionBuffer, parameters, balanced); if (gravityModelShader == null) { throw new XTMF.XTMFRuntimeException("Unable to compile the GravityModel GPU Kernel!"); } iterations = Balance(gpu, gravityModelShader, balancedBuffer, parameters, balanced, iterations, step1, step2); gpu.Read(flowsBuffer, flows); gravityModelShader.RemoveAllBuffers(); watch.Stop(); using (StreamWriter writer = new StreamWriter("GPUPerf.txt", true)) { writer.Write("Iteraions:"); writer.WriteLine(iterations); writer.Write("Time(ms):"); writer.WriteLine(watch.ElapsedMilliseconds); } gravityModelShader.Dispose(); gpu.Release(); return(BuildDistribution(O, D, oLength, flows)); }
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); }
Vector4 outlineColor = new Vector4(1.0f, 0.0f, 0.0f, 0.6f); //alpha => 0:disabled 1:enabled protected override void initVulkan() { base.initVulkan(); cmds = cmdPool.AllocateCommandBuffer(swapChain.ImageCount); font = new BMFont(vke.samples.Utils.GetDataFile("font.fnt")); vbo = new GPUBuffer <float> (dev, VkBufferUsageFlags.VertexBuffer | VkBufferUsageFlags.TransferDst, 1024); ibo = new GPUBuffer <ushort> (dev, VkBufferUsageFlags.IndexBuffer | VkBufferUsageFlags.TransferDst, 2048); descriptorPool = new DescriptorPool(dev, 1, new VkDescriptorPoolSize(VkDescriptorType.UniformBuffer), new VkDescriptorPoolSize(VkDescriptorType.CombinedImageSampler) ); dsLayout = new DescriptorSetLayout(dev, 0, new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Vertex, VkDescriptorType.UniformBuffer), new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Fragment, VkDescriptorType.CombinedImageSampler)); using (GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList, VkSampleCountFlags.SampleCount4, false)) { cfg.Layout = new PipelineLayout(dev, dsLayout); cfg.Layout.AddPushConstants(new VkPushConstantRange(VkShaderStageFlags.Fragment, (uint)Marshal.SizeOf <Vector4> () * 2)); cfg.RenderPass = new RenderPass(dev, swapChain.ColorFormat, cfg.Samples); cfg.blendAttachments[0] = new VkPipelineColorBlendAttachmentState( true, VkBlendFactor.One, VkBlendFactor.OneMinusSrcAlpha, VkBlendOp.Add, VkBlendFactor.One, VkBlendFactor.Zero); cfg.AddVertexBinding(0, 5 * sizeof(float)); cfg.AddVertexAttributes(0, VkFormat.R32g32b32Sfloat, VkFormat.R32g32Sfloat); cfg.AddShader(dev, VkShaderStageFlags.Vertex, "#shaders.main.vert.spv"); cfg.AddShader(dev, VkShaderStageFlags.Fragment, "#shaders.main.frag.spv"); pipeline = new GraphicPipeline(cfg); } uboMats = new HostBuffer(dev, VkBufferUsageFlags.UniformBuffer, matrices); uboMats.Map(); //permanent map descriptorSet = descriptorPool.Allocate(dsLayout); fontTexture = font.GetPageTexture(0, presentQueue, cmdPool); fontTexture.CreateView(); fontTexture.CreateSampler(); fontTexture.Descriptor.imageLayout = VkImageLayout.ShaderReadOnlyOptimal; DescriptorSetWrites dsUpdate = new DescriptorSetWrites(descriptorSet, dsLayout); dsUpdate.Write(dev, uboMats.Descriptor, fontTexture.Descriptor); generateText("Vulkan", out HostBuffer <Vertex> staggingVbo, out HostBuffer <ushort> staggingIbo); PrimaryCommandBuffer cmd = cmdPool.AllocateAndStart(VkCommandBufferUsageFlags.OneTimeSubmit); staggingVbo.CopyTo(cmd, vbo); staggingIbo.CopyTo(cmd, ibo); presentQueue.EndSubmitAndWait(cmd); staggingVbo.Dispose(); staggingIbo.Dispose(); UpdateFrequency = 10; }
unsafe public static void DrawRanges <I, T>(GPUBuffer <I> ib, GPUBuffer <T> vb, NativeSlice <DrawBufferRange> ranges) where T : struct where I : struct { Debug.Assert(ib.ElementStride == 2); DrawRanges(ib.BufferPointer, vb.BufferPointer, vb.ElementStride, new IntPtr(ranges.GetUnsafePtr()), ranges.Length); }