private void GlControl_OnContextCreated(object sender, GlControlEventArgs e) { var control = (GlControl)sender; Gl.MatrixMode(MatrixMode.Modelview); Gl.LoadIdentity(); Gl.ClearColor(_bgColorVec.X, _bgColorVec.Y, _bgColorVec.Z, _bgColorVec.W); Shader = new ShaderHelper(); AdjustOrtho(new Size(control.Height, control.Width)); }
private void UpdateShadowParams() { Shader.SetGlobalFloat(ShaderHelper.PropertyToID(ShaderHelper.ShadowBias), _shadowBias); Shader.SetGlobalFloat(ShaderHelper.PropertyToID(ShaderHelper.ShadowNormalBias), _shadowNormalBias); Shader.SetGlobalFloat(ShaderHelper.PropertyToID(ShaderHelper.ShadowIntensity), _shadowStrength); Shader.SetGlobalTexture(ShaderHelper.PropertyToID(ShaderHelper.ShadowMap), _shadowMap); Shader.SetGlobalFloat(ShaderHelper.PropertyToID(ShaderHelper.ShadowMapWidthScale), 1f / GetShadowMapWidth()); Shader.SetGlobalFloat(ShaderHelper.PropertyToID(ShaderHelper.ShadowMapHeightScale), 1f / GetShadowMapHeight()); }
/// <summary> /// Throws the Render event. /// </summary> /// <param name="e">The event data.</param> public override void OnRender(RenderEventArgs e) { base.OnRender(e); // if (_vertexBuffer != null) if ((_vertexBuffer != null) && (_sculptor.VertexPositionTextureNormals != null)) { // For texture rendering e.GraphicsDevice.SamplerStates[0] = _samplerState; e.GraphicsDevice.SetVertexBuffer(null); // to prevent InvalidOperationException during _vertexBuffer.SetData() _vertexBuffer.SetData(0, _sculptor.VertexPositionTextureNormals, 0, _sculptor.VertexPositionTextureNormals.Length, 0); // e.GraphicsDevice.SetVertexBuffer(_vertexBuffer); // Vertex pipeline e.GraphicsDevice.SetVertexBuffer(_vertexBuffer); ShaderHelper.SetVertexShader(e.GraphicsDevice, _scene._vertexShader); ShaderHelper.SetVertexShaderConstantMatrix(e.GraphicsDevice, ref e.ViewProjection); ShaderHelper.SetVertexShaderConstantMatrix(e.GraphicsDevice, ref _matrix); // Pixel pipeline ShaderHelper.SetPixelShader(e.GraphicsDevice, _scene._pixelShader); Vector4 lookDirection = new Vector4(_scene.Camera.LookTarget, 0.0f); ShaderHelper.SetPixelShaderConstantFloat4(e.GraphicsDevice, ref lookDirection); ShaderHelper.SetPixelShaderConstantFloat4(e.GraphicsDevice, ref _scene._ambientLightVector); ShaderHelper.SetPixelShaderConstantFloat4(e.GraphicsDevice, ref _scene._directionalLightVector1); ShaderHelper.SetPixelShaderConstantFloat4(e.GraphicsDevice, ref _scene._directionalLightVector2); ShaderHelper.SetPixelShaderConstantFloat4(e.GraphicsDevice, ref _scene._directionalLightVector3); ShaderHelper.SetPixelShaderConstantFloat4(e.GraphicsDevice, ref _scene._directionalLightVector4); ShaderHelper.SetPixelShaderConstantMaterial(e.GraphicsDevice, ref _material); if (_texture != null) { e.GraphicsDevice.Textures[0] = _texture; } if (_sculptor.Triangles.Count > 0) // to prevent ArgumentOutOfRangeException on GraphicsDevice.DrawPrimitives() { e.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, _sculptor.Triangles.Count); if (_backTexture != null) { e.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; e.GraphicsDevice.Textures[0] = _backTexture; ShaderHelper.SetPixelShaderConstantMaterial(e.GraphicsDevice, ref _backMaterial); e.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, _sculptor.Triangles.Count); e.GraphicsDevice.RasterizerState = Helper3D.DefaultRasterizerState; } } } }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { ResourceFactory factory = gd.ResourceFactory; _vb = factory.CreateBuffer(new BufferDescription(s_vertices.SizeInBytes(), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, s_vertices); _ib = factory.CreateBuffer(new BufferDescription(s_indices.SizeInBytes(), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_indices); ImageSharpCubemapTexture imageSharpCubemapTexture = new ImageSharpCubemapTexture(_right, _left, _top, _bottom, _back, _front, false); Texture textureCube = imageSharpCubemapTexture.CreateDeviceTexture(gd, factory); TextureView textureView = factory.CreateTextureView(new TextureViewDescription(textureCube)); VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3)) }; (Shader vs, Shader fs) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "Skybox"); _layout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("CubeTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("CubeSampler", ResourceKind.Sampler, ShaderStages.Fragment))); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( BlendStateDescription.SingleAlphaBlend, gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, true, true), PrimitiveTopology.TriangleList, new ShaderSetDescription(vertexLayouts, new[] { vs, fs }, ShaderHelper.GetSpecializations(gd)), new ResourceLayout[] { _layout }, sc.MainSceneFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); pd.Outputs = sc.ReflectionFramebuffer.OutputDescription; _reflectionPipeline = factory.CreateGraphicsPipeline(ref pd); _resourceSet = factory.CreateResourceSet(new ResourceSetDescription( _layout, sc.ProjectionMatrixBuffer, sc.ViewMatrixBuffer, textureView, gd.PointSampler)); _disposeCollector.Add(_vb, _ib, textureCube, textureView, _layout, _pipeline, _reflectionPipeline, _resourceSet, vs, fs); }
/// <summary> /// Loads both vertex and fragment shaders from a single custom file /// </summary> /// <param name="path">The path to the file in which the shaders are.</param> /// <returns>An array containing both the vertex and the fragment shader</returns> public static Shader[] LoadShaders(string path) { #if DEBUG using Profiler fullProfiler = new Profiler(typeof(AssetManager)); #endif (string vs, string fs) = ShaderHelper.LoadShaders(path); Shader[] shaders = new Shader[2]; shaders[0] = gd.ResourceFactory.CreateShader(new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vs), "main")); shaders[0].Name = ExtractNameFromPath(path) + "-Vertex"; shaders[1] = gd.ResourceFactory.CreateShader(new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fs), "main")); shaders[1].Name = ExtractNameFromPath(path) + "-Fragment"; ResourceCache.AddShaders(shaders); return(shaders); }
public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); var shaderCache = Resolve <IShaderCache>(); _shaders = shaderCache.GetShaderPair(gd.ResourceFactory, VertexShaderName, FragmentShaderName, shaderCache.GetGlsl(VertexShaderName), shaderCache.GetGlsl(FragmentShaderName)); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend, BlendAttachmentDescription.OverrideBlend), gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, _shaders, ShaderHelper.GetSpecializations(gd)), new[] { resourceLayout }, sc.DuplicatorFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _pipeline.Name = "P_ScreenDuplicator"; float[] verts = Util.GetFullScreenQuadVerts(gd); _vb = factory.CreateBuffer(new BufferDescription(verts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, verts); _ib = factory.CreateBuffer( new BufferDescription((uint)QuadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, QuadIndices); }
void OnPostLoadProcess(Object o) { var ui = Instantiate(o) as GameObject; ui.SetActive(true); ui.name = o.name; ShaderHelper.SetupShader(ui); AttachToCanvas(ui); _uis.Add(ui.name, ui); RaiseEvent(ui); }
public void PrepareData(ComputeBuffer <Vector3f> elements) { int numAll = elements.Count; SortDataPrepearerShader.SetBuffer(KERNEL_ID_CONVERT, "Input", elements); if (Prepeared == null) { Prepeared = new ComputeBuffer <Particle>(numAll); } SortDataPrepearerShader.SetBuffer(KERNEL_ID_CONVERT, "Output", Prepeared); SortDataPrepearerShader.Dispatch(KERNEL_ID_CONVERT, ShaderHelper.GetNumberOfDispatchGroups(numAll, (int)BLOCK_SIZE), 1, 1); }
public static void RenderMesh2(Model m, Vector3 position, string effectName, string technique, Matrix mWorld, int stride) { if (m == null || m.MeshObj == null) { return; } Shader e = WorldData.GetObject(effectName) as Shader; Matrix world = Matrix.Identity + Matrix.Translation(position); if (mWorld != null) { world = mWorld; } ShaderHelper.UpdateCommonEffectVars(e, world); EffectTechnique t = e.EffectObj.GetTechniqueByName(technique); D3D10.Buffer indexBuffer = m.MeshObj.GetDeviceIndexBuffer(); D3D10.Buffer vertextBuffer = m.MeshObj.GetDeviceVertexBuffer(0); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); Game.Device.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0); Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertextBuffer, stride, 0)); for (int p = 0; p < t.Description.PassCount; p++) { EffectPass pass = t.GetPassByIndex(p); InputLayout l = ShaderHelper.ConstructInputLayout(m.Mesh3d.inputElements, pass.Description.Signature); Game.Device.InputAssembler.SetInputLayout(l); for (int subset = 0; subset < m.Mesh3d.NumAttributes; subset++) { EffectResourceVariable diffTex = e.GetVar(ShaderHelper.DiffTex).AsResource(); if (diffTex != null) { diffTex.SetResource(m.Mesh3d.textureViews[subset]); } pass.Apply(); MeshAttributeRange r = m.Mesh3d.attrTable[subset]; // * 2 cause adj data is twice as much data //Game.Device.DrawIndexed((r.FaceCount * 3) * 2, (r.FaceStart * 3) * 2, 0); Game.Device.DrawIndexed((r.FaceCount * 3), (r.FaceStart * 3), 0); } } indexBuffer.Dispose(); vertextBuffer.Dispose(); }
protected override void DoInitialize() { // Now create a simple program to visualize the result basicShaderProgram = new ShaderProgram(); basicShaderProgram.Create(basicVertexShader, basicFragmentShader, null); base_model_matrix_pos = GL.GetUniformLocation(basicShaderProgram.ShaderProgramObject, "model_matrix"); base_projection_matrix_pos = GL.GetUniformLocation(basicShaderProgram.ShaderProgramObject, "projection_matrix"); fur_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(fur_prog, ShaderType.VertexShader, furVertexShader); ShaderHelper.vglAttachShaderSource(fur_prog, ShaderType.GeometryShader, furGeometryShader); ShaderHelper.vglAttachShaderSource(fur_prog, ShaderType.FragmentShader, furFragmentShader); GL.LinkProgram(fur_prog); GL.UseProgram(fur_prog); fur_model_matrix_pos = GL.GetUniformLocation(fur_prog, "model_matrix"); fur_projection_matrix_pos = GL.GetUniformLocation(fur_prog, "projection_matrix"); GL.GenTextures(1, fur_texture); UnmanagedArray <byte> tex = new UnmanagedArray <byte>(1024 * 1024 * 4); Random random = new Random(); for (int n = 0; n < 256; n++) { for (int m = 0; m < 1270; m++) { int x = random.Next() & 0x3FF; int y = random.Next() & 0x3FF; tex[(y * 1024 + x) * 4 + 0] = (byte)((random.Next() & 0x3F) + 0xC0); tex[(y * 1024 + x) * 4 + 1] = (byte)((random.Next() & 0x3F) + 0xC0); tex[(y * 1024 + x) * 4 + 2] = (byte)((random.Next() & 0x3F) + 0xC0); tex[(y * 1024 + x) * 4 + 3] = (byte)(n); //tex[(y * 1024 + x) * 4 + 0] = (byte)(random.Next()); //tex[(y * 1024 + x) * 4 + 1] = (byte)(random.Next()); //tex[(y * 1024 + x) * 4 + 2] = (byte)(random.Next()); //tex[(y * 1024 + x) * 4 + 3] = (byte)(random.Next()); } } GL.BindTexture(GL.GL_TEXTURE_2D, fur_texture[0]); GL.TexImage2D(TexImage2DTargets.Texture2D, 0, TexImage2DFormats.RGBA, 1024, 1024, 0, TexImage2DFormats.RGBA, TexImage2DTypes.UnsignedByte, tex.Header); GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR); GL.TexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, (int)GL.GL_LINEAR); tex.Dispose(); vboObject.LoadFromVBM(@"media\ninja.vbm", 0, 1, 2); base.BeforeRendering += LightingExample_BeforeRendering; base.AfterRendering += LightingExample_AfterRendering; }
private static void DrawClouds(bool renderReflection) { if (skyBoxCloudsMesh == null || skyBoxCloudsMesh.MeshObj == null) { return; } Shader scatterEffect = WorldData.GetObject("scatter.fx") as Shader; EffectTechnique tech = scatterEffect.EffectObj.GetTechniqueByName("RenderClouds"); if (renderReflection) { tech = scatterEffect.EffectObj.GetTechniqueByName("RenderCloudsReflection"); } D3D10.Buffer iBuffer = skyBoxCloudsMesh.MeshObj.GetDeviceIndexBuffer(); D3D10.Buffer vBuffer = skyBoxCloudsMesh.MeshObj.GetDeviceVertexBuffer(0); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); Game.Device.InputAssembler.SetIndexBuffer(iBuffer, Format.R16_UInt, 0); Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vBuffer, 56, 0)); EffectPass p1 = tech.GetPassByIndex(0); InputLayout layout = ShaderHelper.ConstructInputLayout(MeshInputElements10.NormalMesh, p1.Description.Signature); Game.Device.InputAssembler.SetInputLayout(layout); Matrix mWorld = Matrix.Translation(Camera.Position); if (renderReflection) { mWorld = Matrix.Scaling(1, -1, 1) * Matrix.Translation(Camera.Position); } scatterEffect.GetVar("WorldViewProj").AsMatrix().SetMatrix(mWorld * Camera.ViewMatrix * Camera.ProjectionMatrix); if (settings != null && settings.SkySettings != null) { scatterEffect.GetVar("cloud1Tile").AsScalar().Set(settings.SkySettings.CloudTile.X); scatterEffect.GetVar("cloud2Tile").AsScalar().Set(settings.SkySettings.CloudTile.Y); scatterEffect.GetVar("cloudCover").AsScalar().Set(settings.SkySettings.CloudCover); } scatterEffect.GetVar("scroll").AsVector().Set(t); scatterEffect.GetVar("clouds1Tex").AsResource().SetResource(skyClouds1); scatterEffect.GetVar("clouds2Tex").AsResource().SetResource(skyClouds2); scatterEffect.GetVar("SunColor").AsVector().Set(SunColor); p1.Apply(); Game.Device.DrawIndexed((skyBoxCloudsMesh.Mesh3d.attrTable[0].FaceCount * 3), 0, 0); iBuffer.Dispose(); vBuffer.Dispose(); }
void UpdateOcclusion() { if (gm == null) { return; } if (occlusionQueryActive) { // If the previous query has not yet completed, wait until it does. if (!occQuery.IsDataAvailable) { return; } UInt64 pixelCount = occQuery.GetData().Read <UInt64>(); occlusionAlpha = Math.Min(pixelCount / 25000.0f, 1); } occQuery.Begin(); Matrix m = Matrix.Scaling(3000, 3000, 3000) * Matrix.Translation(-SkyDome.LightDirection * 25000); Shader e = WorldData.GetObject("scatter.fx") as Shader; EffectTechnique t = e.EffectObj.GetTechniqueByName("RenderOccluder"); D3D10.Buffer indexBuffer = gm.MeshObj.GetDeviceIndexBuffer(); D3D10.Buffer vertextBuffer = gm.MeshObj.GetDeviceVertexBuffer(0); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); Game.Device.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0); Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertextBuffer, 16, 0)); EffectPass pass = t.GetPassByIndex(0); InputLayout l = ShaderHelper.ConstructInputLayout(gm.Mesh3d.inputElements, pass.Description.Signature); Game.Device.InputAssembler.SetInputLayout(l); Matrix proj = Matrix.PerspectiveFovLH(Camera.Fovx, Camera.AspectRatio, 1.0f, 1000000.0f); e.GetVar("WorldViewProjection").AsMatrix().SetMatrix(m * Camera.ViewMatrix * proj); pass.Apply(); Game.Device.DrawIndexed((gm.Mesh3d.attrTable[0].FaceCount * 3), (gm.Mesh3d.attrTable[0].FaceStart * 3), 0); indexBuffer.Dispose(); vertextBuffer.Dispose(); occQuery.End(); occlusionQueryActive = true; }
protected override void DoInitialize() { base_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(base_prog, ShaderType.VertexShader, quad_shader_vs); ShaderHelper.vglAttachShaderSource(base_prog, ShaderType.FragmentShader, quad_shader_fs); GL.GenBuffers(1, quad_vbo); GL.BindBuffer(BufferTarget.ArrayBuffer, quad_vbo[0]); var quad_data = new UnmanagedArray <vec2>(8); quad_data[0] = new vec2(1.0f, -1.0f); quad_data[1] = new vec2(-1.0f, -1.0f); quad_data[2] = new vec2(-1.0f, 1.0f); quad_data[3] = new vec2(1.0f, 1.0f); quad_data[4] = new vec2(0.0f, 0.0f); quad_data[5] = new vec2(1.0f, 0.0f); quad_data[6] = new vec2(1.0f, 1.0f); quad_data[7] = new vec2(0.0f, 1.0f); GL.BufferData(BufferTarget.ArrayBuffer, quad_data, BufferUsage.StaticDraw); GL.GenVertexArrays(1, vao); GL.BindVertexArray(vao[0]); GL.VertexAttribPointer(0, 2, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.VertexAttribPointer(1, 2, GL.GL_FLOAT, false, 0, new IntPtr(8 * sizeof(float))); GL.EnableVertexAttribArray(0); GL.EnableVertexAttribArray(1); GL.LinkProgram(base_prog); StringBuilder buf = new StringBuilder(1024); GL.GetProgramInfoLog(base_prog, 1024, IntPtr.Zero, buf); vglImageData image = new vglImageData(); tex = vgl.vglLoadTexture(@"media\test.dds", 0, ref image); GL.TexParameteri(image.target, GL.GL_TEXTURE_MIN_FILTER, (int)GL.GL_LINEAR_MIPMAP_LINEAR); vgl.vglUnloadImage(ref image); }
public static void DrawInstancedSpheres(GraphicsDeviceManager gdm, List <Matrix> instances) { Model sphere = WorldData.GetObject("sphereInstanced.mesh") as Model; D3D10.Buffer indexBuffer = sphere.MeshObj.GetDeviceIndexBuffer(); D3D10.Buffer vertextBuffer = sphere.MeshObj.GetDeviceVertexBuffer(0); Shader e = WorldData.GetObject("Instanced.fx") as Shader; EffectTechnique t = e.EffectObj.GetTechniqueByName("RenderInstanced"); InputLayout l = ShaderHelper.ConstructInputLayout(MeshInputElements10.PositionOnlyInstanced, t.GetPassByIndex(0).Description.Signature); BufferDescription bd = new BufferDescription(); bd.SizeInBytes = System.Runtime.InteropServices.Marshal.SizeOf(instances[0]) * instances.Count; bd.Usage = ResourceUsage.Dynamic; bd.CpuAccessFlags = CpuAccessFlags.Write; bd.BindFlags = BindFlags.VertexBuffer; D3D10.Buffer instanceData = new D3D10.Buffer(gdm.Direct3D10.Device, bd); DataStream ds = instanceData.Map(MapMode.WriteDiscard, SlimDX.Direct3D10.MapFlags.None); ds.Position = 0; ds.WriteRange(instances.ToArray()); instanceData.Unmap(); Game.Device.InputAssembler.SetInputLayout(l); Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertextBuffer, 16, 0), new VertexBufferBinding(instanceData, System.Runtime.InteropServices.Marshal.SizeOf(instances[0]), 0)); Game.Device.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); e.GetVar("WorldViewProj").AsMatrix().SetMatrix(Camera.ViewMatrix * Camera.ProjectionMatrix); t.GetPassByIndex(0).Apply(); Game.Device.DrawIndexedInstanced((sphere.Mesh3d.attrTable[0].FaceCount * 3), instances.Count, 0, 0, 0); //Game.Device.DrawIndexed((sphere.attrTable[0].FaceCount * 3) * 2, 0, 0); indexBuffer.Dispose(); vertextBuffer.Dispose(); sphere.Dispose(); }
Pipeline BuildPipeline(GraphicsDevice gd, SceneContext sc) { var shaderCache = Resolve <IShaderCache>(); var shaderName = "InfoOverlay"; var vertexShaderName = shaderName + "SV.vert"; var fragmentShaderName = shaderName + "SF.frag"; var vertexShaderContent = shaderCache.GetGlsl(vertexShaderName); var fragmentShaderContent = shaderCache.GetGlsl(fragmentShaderName); var shaders = shaderCache.GetShaderPair( gd.ResourceFactory, vertexShaderName, fragmentShaderName, vertexShaderContent, fragmentShaderContent); _shaders.AddRange(shaders); var depthStencilMode = gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyLessEqual : DepthStencilStateDescription.DepthOnlyGreaterEqual; var rasterizerMode = new RasterizerStateDescription( FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, true, // depth test true); // scissor test var pipelineDescription = new GraphicsPipelineDescription( BlendStateDescription.SingleAlphaBlend, depthStencilMode, rasterizerMode, PrimitiveTopology.TriangleList, new ShaderSetDescription(new[] { VertexLayout }, shaders, ShaderHelper.GetSpecializations(gd)), new[] { _perSpriteResourceLayout, sc.CommonResourceLayout }, gd.SwapchainFramebuffer.OutputDescription); var pipeline = gd.ResourceFactory.CreateGraphicsPipeline(ref pipelineDescription); pipeline.Name = "P_InfoOverlay"; return(pipeline); }
internal override void ConstrainPositions(double di) { FluidBody3d fluid = Body as FluidBody3d; fluid.NeighboursSearcher.NeighbourhoodSearch(fluid.GPUPredicted, Boundary.GPUPositions); CurrentShader.SetInt("FluidNumParticles", fluid.NumParticles); //pre step(Calcuclate Density, Calculate Lambda Coeffs) CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "NeighboursMap", fluid.NeighboursSearcher.NeighboursMap); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "NumNeighbours", fluid.NeighboursSearcher.NumNeighbours); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "FluidPositions", fluid.GPUPositions); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "FluidPredicted", fluid.GPUPredicted); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "FluidDensities", fluid.GPUDensities); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "FluidLambda", fluid.GPULambda); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "BoundaryPositions", Boundary.GPUPositions); CurrentShader.SetBuffer(KERNEL_ID_PRESTEP, "BoundaryPsi", Boundary.GPUPsi); //constraint CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "NeighboursMap", fluid.NeighboursSearcher.NeighboursMap); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "NumNeighbours", fluid.NeighboursSearcher.NumNeighbours); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "FluidPositions", fluid.GPUPositions); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "FluidPredicted", fluid.GPUPredicted); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "FluidDensities", fluid.GPUDensities); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "FluidLambda", fluid.GPULambda); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "BoundaryPositions", Boundary.GPUPositions); CurrentShader.SetBuffer(KERNEL_DENSITYCONSTRAINT, "BoundaryPsi", Boundary.GPUPsi); int iter = 0; while (iter < Iterations) { //pre step(Calcuclate Density, Calculate Lambda Coeffs) CurrentShader.Dispatch(KERNEL_ID_PRESTEP, ShaderHelper.GetNumberOfDispatchGroups(fluid.NumParticles, BLOCK_SIZE), 1, 1); //constraint CurrentShader.Dispatch(KERNEL_DENSITYCONSTRAINT, ShaderHelper.GetNumberOfDispatchGroups(fluid.NumParticles, BLOCK_SIZE), 1, 1); iter++; } }
public void PrepareData(ComputeBuffer <Vector3f> matterParticles, ComputeBuffer <Vector3f> boundaryParticles) { int numAll = matterParticles.Count + boundaryParticles.Count; int numMatterParticles = matterParticles.Count; SortDataPrepearerShader.SetInt("NumMatterParticles", numMatterParticles); SortDataPrepearerShader.SetBuffer(KERNEL_ID_CONVERT, "InputMatterParticles", matterParticles); SortDataPrepearerShader.SetBuffer(KERNEL_ID_CONVERT, "InputBoundaryParticles", boundaryParticles); if (Prepeared == null) { Prepeared = new ComputeBuffer <Particle>(numAll); } SortDataPrepearerShader.SetBuffer(KERNEL_ID_CONVERT, "Output", Prepeared); SortDataPrepearerShader.Dispatch(KERNEL_ID_CONVERT, ShaderHelper.GetNumberOfDispatchGroups(numAll, (int)BLOCK_SIZE), 1, 1); }
ShaderInfo GenerateShader() { shaderInfo = new ShaderInfo(); shaderInfo.ShaderProgramID = GL.CreateProgram(); ShaderHelper.LoadShader("Shaders/vertex.glsl", ShaderType.VertexShader, shaderInfo.ShaderProgramID, out shaderInfo.VertexShaderID); ShaderHelper.LoadShader("Shaders/fragment.glsl", ShaderType.FragmentShader, shaderInfo.ShaderProgramID, out shaderInfo.FragmentShaderID); GL.LinkProgram(shaderInfo.ShaderProgramID); Console.WriteLine(GL.GetProgramInfoLog(shaderInfo.ShaderProgramID)); shaderInfo.Attribute_vertexPosition = GL.GetAttribLocation(shaderInfo.ShaderProgramID, "vPosition"); shaderInfo.Attribute_vertexColor = GL.GetAttribLocation(shaderInfo.ShaderProgramID, "vColor"); shaderInfo.Attribute_vertexNormal = GL.GetAttribLocation(shaderInfo.ShaderProgramID, "vNormal"); shaderInfo.Uniform_modelview = GL.GetUniformLocation(shaderInfo.ShaderProgramID, "modelview"); return(shaderInfo); }
public unsafe override void CreateDeviceObjects(RenderContext rc) { ResourceFactory factory = rc.ResourceFactory; _vb = factory.CreateVertexBuffer(s_vertices.Length * VertexPosition.SizeInBytes, false); _vb.SetVertexData(s_vertices, new VertexDescriptor(VertexPosition.SizeInBytes, 1, IntPtr.Zero)); _ib = factory.CreateIndexBuffer(s_indices.Length * sizeof(int), false); _ib.SetIndices(s_indices); SkyboxSetInfo.CreateAll( factory, ShaderHelper.LoadBytecode(factory, "Skybox", ShaderStages.Vertex), ShaderHelper.LoadBytecode(factory, "Skybox", ShaderStages.Fragment), out _shaderSet, out _resourceSlots); _viewMatrixBuffer = factory.CreateConstantBuffer(ShaderConstantType.Matrix4x4); fixed(Rgba32 *frontPin = &_front.ISImage.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * backPin = &_back.ISImage.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * leftPin = &_left.ISImage.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * rightPin = &_right.ISImage.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * topPin = &_top.ISImage.DangerousGetPinnableReferenceToPixelBuffer()) fixed(Rgba32 * bottomPin = &_bottom.ISImage.DangerousGetPinnableReferenceToPixelBuffer()) { _cubemapTexture = factory.CreateCubemapTexture( (IntPtr)frontPin, (IntPtr)backPin, (IntPtr)leftPin, (IntPtr)rightPin, (IntPtr)topPin, (IntPtr)bottomPin, _front.Width, _front.Height, _front.PixelSizeInBytes, _front.Format); _cubemapBinding = factory.CreateShaderTextureBinding(_cubemapTexture); } _rasterizerState = factory.CreateRasterizerState(FaceCullingMode.None, TriangleFillMode.Solid, false, false); }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend, BlendAttachmentDescription.OverrideBlend), DepthStencilStateDescription.DepthOnlyLessEqual, RasterizerStateDescription.Default, PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { ShaderHelper.LoadShader(gd, factory, "ScreenDuplicator", ShaderStages.Vertex, "VS"), ShaderHelper.LoadShader(gd, factory, "ScreenDuplicator", ShaderStages.Fragment, "FS"), }), new ResourceLayout[] { resourceLayout }, sc.DuplicatorFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _vb = factory.CreateBuffer(new BufferDescription((uint)s_quadVerts.Length * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, s_quadVerts); _ib = factory.CreateBuffer( new BufferDescription((uint)s_quadIndices.Length * sizeof(ushort), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
private static GraphicsPipelineStateDescription BuildGraphicsPipelineStateDescription(RootSignature rootSignature, int msaaCount, int msaaQuality, Format depthStencilFormat) { var inputLayout = BuildInputLayout(); return(new GraphicsPipelineStateDescription { InputLayout = inputLayout, RootSignature = rootSignature, VertexShader = ShaderHelper.CompileShader("Shaders\\Color.hlsl", "VS", "vs_5_0"), PixelShader = ShaderHelper.CompileShader("Shaders\\Color.hlsl", "PS", "ps_5_0"), RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, SampleDescription = new SampleDescription(msaaCount, msaaQuality), DepthStencilFormat = depthStencilFormat }); }
public static void RenderVertices(VertexBufferBinding vbb, int numVertices, Matrix world, InputElement[] inputElements, string effectName, string technique) { Shader e = WorldData.GetObject(effectName) as Shader; ShaderHelper.UpdateCommonEffectVars(e, world); EffectTechnique t = e.EffectObj.GetTechniqueByName(technique); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.LineList); Game.Device.InputAssembler.SetVertexBuffers(0, vbb); for (int p = 0; p < t.Description.PassCount; p++) { EffectPass pass = t.GetPassByIndex(p); InputLayout l = ShaderHelper.ConstructInputLayout(inputElements, pass.Description.Signature); Game.Device.InputAssembler.SetInputLayout(l); pass.Apply(); Game.Device.Draw(numVertices, 0); } }
public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory); _disposeCollector = factory.DisposeCollector; ResourceLayout resourceLayout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("SourceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("SourceSampler", ResourceKind.Sampler, ShaderStages.Fragment))); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( new BlendStateDescription( RgbaFloat.Black, BlendAttachmentDescription.OverrideBlend), DepthStencilStateDescription.Disabled, new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, false), PrimitiveTopology.TriangleList, new ShaderSetDescription( new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2), new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, new[] { ShaderHelper.LoadShader(gd, factory, "FullScreenQuad", ShaderStages.Vertex, "VS"), ShaderHelper.LoadShader(gd, factory, "FullScreenQuad", ShaderStages.Fragment, "FS"), }), new ResourceLayout[] { resourceLayout }, gd.SwapchainFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _vb = factory.CreateBuffer(new BufferDescription(s_quadVerts.SizeInBytes() * sizeof(float), BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, s_quadVerts); _ib = factory.CreateBuffer( new BufferDescription(s_quadIndices.SizeInBytes(), BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, s_quadIndices); }
Pipeline BuildPipeline(GraphicsDevice gd, SceneContext sc) { var shaderCache = Resolve <IShaderCache>(); var vertexShaderName = "SkyBoxSV.vert"; var fragmentShaderName = "SkyBoxSF.frag"; var vertexShaderContent = shaderCache.GetGlsl(vertexShaderName); var fragmentShaderContent = shaderCache.GetGlsl(fragmentShaderName); var shaders = shaderCache.GetShaderPair( gd.ResourceFactory, vertexShaderName, fragmentShaderName, vertexShaderContent, fragmentShaderContent); _shaders.AddRange(shaders); var shaderSet = new ShaderSetDescription(new[] { VertexLayout }, shaders); var depthStencilMode = DepthStencilStateDescription.Disabled; var rasterizerMode = new RasterizerStateDescription( FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, false, // depth test true); // scissor test var pipelineDescription = new GraphicsPipelineDescription( BlendStateDescription.SingleDisabled, depthStencilMode, rasterizerMode, PrimitiveTopology.TriangleList, new ShaderSetDescription(new[] { VertexLayout }, shaderSet.Shaders, ShaderHelper.GetSpecializations(gd)), new[] { _resourceLayout, sc.CommonResourceLayout }, sc.MainSceneFramebuffer.OutputDescription); var pipeline = gd.ResourceFactory.CreateGraphicsPipeline(ref pipelineDescription); pipeline.Name = "P_Skybox"; return(pipeline); }
/// <summary> /// Allocates and initializes OpenGL resources needed by the plane renderer. Must be /// called on the OpenGL thread, typically in /// {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}. /// @param context Needed to access shader source and texture PNG. /// @param gridDistanceTextureName Name of the PNG file containing the grid texture. /// </summary> public void CreateOnGlThread(Context context, String gridDistanceTextureName) { int vertexShader = ShaderHelper.Load(TAG, context, GLES20.GlVertexShader, Resource.Raw.plane_vertex); int passthroughShader = ShaderHelper.Load(TAG, context, GLES20.GlFragmentShader, Resource.Raw.plane_fragment); mPlaneProgram = GLES20.GlCreateProgram(); GLES20.GlAttachShader(mPlaneProgram, vertexShader); GLES20.GlAttachShader(mPlaneProgram, passthroughShader); GLES20.GlLinkProgram(mPlaneProgram); GLES20.GlUseProgram(mPlaneProgram); // Read the texture. var textureBitmap = Android.Graphics.BitmapFactory.DecodeStream( context.Assets.Open(gridDistanceTextureName)); GLES20.GlActiveTexture(GLES20.GlTexture0); GLES20.GlGenTextures(mTextures.Length, mTextures, 0); GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]); GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear); GLES20.GlTexParameteri(GLES20.GlTexture2d, GLES20.GlTextureMagFilter, GLES20.GlLinear); GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0); GLES20.GlGenerateMipmap(GLES20.GlTexture2d); GLES20.GlBindTexture(GLES20.GlTexture2d, 0); mPlaneXZPositionAlphaAttribute = GLES20.GlGetAttribLocation(mPlaneProgram, "a_XZPositionAlpha"); mPlaneModelUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_Model"); mPlaneModelViewProjectionUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_ModelViewProjection"); mTextureUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_Texture"); mLineColorUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_lineColor"); mDotColorUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_dotColor"); mGridControlUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_gridControl"); mPlaneUvMatrixUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix"); }
static void UpdateMieRayleighTextures(RenderTargetView rtv, DepthStencilView dsv) { // Save the Old viewport and set new one Viewport[] oldViews = Game.Device.Rasterizer.GetViewports(); Game.Device.Rasterizer.SetViewports(vp); Game.Device.OutputMerger.SetTargets(new RenderTargetView[] { rayleighRT.rtv, mieRT.rtv }); Game.Device.ClearRenderTargetView(rayleighRT.rtv, Color.CornflowerBlue); Game.Device.ClearRenderTargetView(mieRT.rtv, Color.CornflowerBlue); Shader scatterEffect = WorldData.GetObject("scatter.fx") as Shader; if (scatterEffect == null) { return; } EffectTechnique tech = scatterEffect.EffectObj.GetTechniqueByName("Update"); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleStrip); InputLayout l = ShaderHelper.ConstructInputLayout(MeshInputElements10.PosTex4, tech.GetPassByIndex(0).Description.Signature); Game.Device.InputAssembler.SetInputLayout(l); Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(QuadRenderComponent.quadVerts, 24, 0)); if (settings != null && settings.SkySettings != null) { scatterEffect.GetVar("NumSamples").AsScalar().Set(settings.SkySettings.NumSamples); } scatterEffect.GetVar("InvWavelength").AsVector().Set(InvWaveLengths); scatterEffect.GetVar("WavelengthMie").AsVector().Set(WaveLengthsMie); scatterEffect.GetVar("v3SunDir").AsVector().Set(-LightDirection); tech.GetPassByIndex(0).Apply(); Game.Device.Draw(4, 0); Game.Device.OutputMerger.SetTargets(dsv, rtv); Game.Device.Rasterizer.SetViewports(oldViews); }
public static void DrawLightVolume(Model gm, Matrix mWorld, Vector4 GridColor) { if (gm == null || gm.Mesh3d == null) { return; } Shader effect = WorldData.GetObject("SimpleTexturedQuad.fx") as Shader; EffectTechnique tech = effect.EffectObj.GetTechniqueByName("RenderLightVolume"); EffectPass pass = tech.GetPassByIndex(0); InputLayout layout = ShaderHelper.ConstructInputLayout(gm.Mesh3d.inputElements, pass.Description.Signature); SlimDX.Direct3D10.Buffer indexBuffer = gm.MeshObj.GetDeviceIndexBuffer(); SlimDX.Direct3D10.Buffer vertexBuffer = gm.MeshObj.GetDeviceVertexBuffer(0); Game.Device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); Game.Device.InputAssembler.SetIndexBuffer(indexBuffer, Format.R16_UInt, 0); Game.Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, MeshInputElements10.GetStride(gm.Mesh3d.inputElements), 0)); Game.Device.InputAssembler.SetInputLayout(layout); effect.GetVar("color").AsVector().Set(GridColor); effect.GetVar("WorldViewProj").AsMatrix().SetMatrix(mWorld * Camera.ViewMatrix * Camera.ProjectionMatrix); pass.Apply(); Game.Device.DrawIndexed((gm.Mesh3d.attrTable[0].FaceCount * 3), 0, 0); }
public unsafe override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc) { ResourceFactory factory = gd.ResourceFactory; _vb = factory.CreateBuffer(new BufferDescription(VertexPosition.SizeInBytes * 4, BufferUsage.VertexBuffer)); cl.UpdateBuffer(_vb, 0, new VertexPosition[] { new VertexPosition(new Vector3(-1000, 0, -1000)), new VertexPosition(new Vector3(+1000, 0, -1000)), new VertexPosition(new Vector3(+1000, 0, +1000)), new VertexPosition(new Vector3(-1000, 0, +1000)), }); _ib = factory.CreateBuffer(new BufferDescription(6 * 2, BufferUsage.IndexBuffer)); cl.UpdateBuffer(_ib, 0, new ushort[] { 0, 1, 2, 0, 2, 3 }); const int gridSize = 64; RgbaByte borderColor = new RgbaByte(255, 255, 255, 150); RgbaByte[] pixels = CreateGridTexturePixels(gridSize, 1, borderColor, new RgbaByte()); Texture gridTexture = factory.CreateTexture(new TextureDescription(gridSize, gridSize, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled)); fixed(RgbaByte *pixelsPtr = pixels) { gd.UpdateTexture(gridTexture, (IntPtr)pixelsPtr, pixels.SizeInBytes(), 0, 0, 0, gridSize, gridSize, 1, 0, 0); } TextureView textureView = factory.CreateTextureView(new TextureViewDescription(gridTexture)); VertexLayoutDescription[] vertexLayouts = new VertexLayoutDescription[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3)) }; Shader gridVS = ShaderHelper.LoadShader(gd, factory, "Grid", ShaderStages.Vertex, "VS"); Shader gridFS = ShaderHelper.LoadShader(gd, factory, "Grid", ShaderStages.Fragment, "FS"); ResourceLayout layout = factory.CreateResourceLayout(new ResourceLayoutDescription( new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("GridTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("GridSampler", ResourceKind.Sampler, ShaderStages.Fragment))); GraphicsPipelineDescription pd = new GraphicsPipelineDescription( BlendStateDescription.SingleAlphaBlend, DepthStencilStateDescription.DepthOnlyLessEqual, new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, true, true), PrimitiveTopology.TriangleList, new ShaderSetDescription(vertexLayouts, new[] { gridVS, gridFS }), new ResourceLayout[] { layout }, sc.MainSceneFramebuffer.OutputDescription); _pipeline = factory.CreateGraphicsPipeline(ref pd); _resourceSet = factory.CreateResourceSet(new ResourceSetDescription( layout, sc.ProjectionMatrixBuffer, sc.ViewMatrixBuffer, textureView, gd.PointSampler)); _disposeCollector.Add(_vb, _ib, gridTexture, textureView, gridVS, gridFS, layout, _pipeline, _resourceSet); }
private void Initialize() { // Setup full render pipeline resources, basic one-time initialization (Shader vs, Shader fs) = ShaderHelper.LoadSPIRV(_device, _resources, "roundedquad"); }
} // end sub #endregion protected override void DoInitialize() { render_prog = GL.CreateProgram(); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.VertexShader, render_vs); ShaderHelper.vglAttachShaderSource(render_prog, ShaderType.FragmentShader, render_fs); GL.LinkProgram(render_prog); GL.UseProgram(render_prog); view_matrix_loc = GL.GetUniformLocation(render_prog, "view_matrix"); projection_matrix_loc = GL.GetUniformLocation(render_prog, "projection_matrix"); vboObject.LoadFromVBM(@"media\armadillo_low.vbm", 0, 1, 2); // Bind its vertex array object so that we can append the instanced attributes vboObject.BindVertexArray(); // Get the locations of the vertex attributes in 'prog', which is the // (linked) program object that we're going to be rendering with. Note // that this isn't really necessary because we specified locations for // all the attributes in our vertex shader. This code could be made // more concise by assuming the vertex attributes are where we asked // the compiler to put them. int position_loc = GL.GetAttribLocation(render_prog, "position"); int normal_loc = GL.GetAttribLocation(render_prog, "normal"); int color_loc = GL.GetAttribLocation(render_prog, "color"); int matrix_loc = GL.GetAttribLocation(render_prog, "model_matrix"); // Generate the colors of the objects var colors = new UnmanagedArray <vec4>(INSTANCE_COUNT); for (int n = 0; n < INSTANCE_COUNT; n++) { float a = (float)(n) / 4.0f; float b = (float)(n) / 5.0f; float c = (float)(n) / 6.0f; colors[n] = new vec4( (float)(0.5f + 0.25f * (Math.Sin(a + 1.0f) + 1.0f)), (float)(0.5f + 0.25f * (Math.Sin(b + 2.0f) + 1.0f)), (float)(0.5f + 0.25f * (Math.Sin(c + 3.0f) + 1.0f)), (float)(1.0f) ); } GL.GenBuffers(1, color_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, colors, BufferUsage.DynamicDraw); colors.Dispose(); // Now we set up the color array. We want each instance of our geometry // to assume a different color, so we'll just pack colors into a buffer // object and make an instanced vertex attribute out of it. GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer[0]); GL.VertexAttribPointer((uint)color_loc, 4, GL.GL_FLOAT, false, 0, IntPtr.Zero); GL.EnableVertexAttribArray((uint)color_loc); // This is the important bit... set the divisor for the color array to // 1 to get OpenGL to give us a new value of 'color' per-instance // rather than per-vertex. GL.VertexAttribDivisor((uint)color_loc, 1); // Likewise, we can do the same with the model matrix. Note that a // matrix input to the vertex shader consumes N consecutive input // locations, where N is the number of columns in the matrix. So... // we have four vertex attributes to set up. UnmanagedArray <mat4> tmp = new UnmanagedArray <mat4>(INSTANCE_COUNT); GL.GenBuffers(1, model_matrix_buffer); GL.BindBuffer(BufferTarget.ArrayBuffer, model_matrix_buffer[0]); GL.BufferData(BufferTarget.ArrayBuffer, tmp, BufferUsage.DynamicDraw); tmp.Dispose(); // Loop over each column of the matrix... for (int i = 0; i < 4; i++) { // Set up the vertex attribute GL.VertexAttribPointer((uint)(matrix_loc + i), // Location 4, GL.GL_FLOAT, false, // vec4 Marshal.SizeOf(typeof(mat4)), // Stride new IntPtr(Marshal.SizeOf(typeof(vec4)) * i)); // Start offset // Enable it GL.EnableVertexAttribArray((uint)(matrix_loc + i)); // Make it instanced GL.VertexAttribDivisor((uint)(matrix_loc + i), 1); } // Done (unbind the object's VAO) GL.BindVertexArray(0); }
/// <summary> /// /// </summary> /// <param name="mat"></param> /// <param name="terrain"></param> /// <param name="tt"></param> protected void AddTechnique( Material mat, Terrain terrain, TechniqueType tt ) { string ttStr = string.Empty; switch ( tt ) { case TechniqueType.HighLod: ttStr += "hl"; break; case TechniqueType.LowLod: ttStr += "ll"; break; case TechniqueType.RenderCompositeMap: ttStr += "rc"; break; } LogManager.Instance.Write( "AddTechique:" + ttStr, null ); Technique tech = mat.CreateTechnique(); //only supporting one pass Pass pass = tech.CreatePass(); GpuProgramManager gmgr = GpuProgramManager.Instance; HighLevelGpuProgramManager hmgr = HighLevelGpuProgramManager.Instance; if ( this.mShaderGen == null ) { bool check2x = this.mLayerNormalMappingEnabled || this.mLayerParallaxMappingEnabled; /* if (hmgr.IsLanguageSupported("cg") && (check2x && (gmgr.IsSyntaxSupported("fp40") || gmgr.IsSyntaxSupported("ps_2_x"))) || (gmgr.IsSyntaxSupported("ps_2_0"))) mShaderGen = new ShaderHelperCG(); else*/ if ( hmgr.IsLanguageSupported( "hlsl" ) ) { this.mShaderGen = new ShaderHelperHLSL(); } else if ( hmgr.IsLanguageSupported( "glsl" ) ) { this.mShaderGen = new ShaderHelperGLSL(); } else { //TODO } } HighLevelGpuProgram vprog = this.mShaderGen.GenerateVertexProgram( this, terrain, tt ); HighLevelGpuProgram fprog = this.mShaderGen.GenerateFragmentProgram( this, terrain, tt ); pass.SetVertexProgram( vprog.Name ); pass.SetFragmentProgram( fprog.Name ); if ( tt == TechniqueType.HighLod || tt == TechniqueType.RenderCompositeMap ) { //global normal map TextureUnitState tu = pass.CreateTextureUnitState(); tu.SetTextureName( terrain.TerrainNormalMap.Name ); tu.SetTextureAddressingMode( TextureAddressing.Clamp ); //global color map if ( terrain.IsGlobalColorMapEnabled && IsGlobalColorMapEnabled ) { tu = pass.CreateTextureUnitState( terrain.GlobalColorMap.Name ); tu.SetTextureAddressingMode( TextureAddressing.Clamp ); } //light map if ( IsLightMapEnabled ) { tu = pass.CreateTextureUnitState( terrain.LightMap.Name ); tu.SetTextureAddressingMode( TextureAddressing.Clamp ); } //blend maps uint maxLayers = GetMaxLayers( terrain ); uint numBlendTextures = Utility.Min( terrain.GetBlendTextureCount( (byte)maxLayers ), terrain.GetBlendTextureCount() ); uint numLayers = Utility.Min( maxLayers, (uint)terrain.LayerCount ); for ( uint i = 0; i < numBlendTextures; ++i ) { tu = pass.CreateTextureUnitState( terrain.GetBlendTextureName( (byte)i ) ); tu.SetTextureAddressingMode( TextureAddressing.Clamp ); } //layer textures for ( uint i = 0; i < numLayers; ++i ) { //diffuse / specular string name = terrain.GetLayerTextureName( (byte)i, 0 ); tu = pass.CreateTextureUnitState( terrain.GetLayerTextureName( (byte)i, 0 ) ); //normal / height tu = pass.CreateTextureUnitState( terrain.GetLayerTextureName( (byte)i, 1 ) ); } } //end if else if ( this.mCompositeMapEnabled ) { // LOW_LOD textures // composite map TextureUnitState tu = pass.CreateTextureUnitState(); tu.SetTextureName( terrain.CompositeMap.Name ); tu.SetTextureAddressingMode( TextureAddressing.Clamp ); // That's it! } }