private void DrawTextureSampling() { // Clears the screen GraphicsContext.CommandList.Clear(GraphicsDevice.Presenter.BackBuffer, Color.LightBlue); GraphicsContext.CommandList.Clear(GraphicsDevice.Presenter.DepthStencilBuffer, DepthStencilClearOptions.DepthBuffer | DepthStencilClearOptions.Stencil); GraphicsContext.CommandList.SetRenderTargetAndViewport(GraphicsDevice.Presenter.DepthStencilBuffer, GraphicsDevice.Presenter.BackBuffer); // Update effect simpleEffect.UpdateEffect(GraphicsDevice); // Create pipeline state pipelineState.State.SetDefaults(); pipelineState.State.RootSignature = simpleEffect.RootSignature; pipelineState.State.EffectBytecode = simpleEffect.Effect.Bytecode; pipelineState.State.InputElements = mesh.Draw.VertexBuffers.CreateInputElements(); pipelineState.State.PrimitiveType = PrimitiveType.TriangleList; pipelineState.State.RasterizerState = RasterizerStates.CullNone; pipelineState.State.Output.CaptureState(GraphicsContext.CommandList); pipelineState.Update(); // Set pipeline state GraphicsContext.CommandList.SetPipelineState(pipelineState.CurrentState); // Set vertex/index buffers GraphicsContext.CommandList.SetVertexBuffer(0, mesh.Draw.VertexBuffers[0].Buffer, mesh.Draw.VertexBuffers[0].Offset, mesh.Draw.VertexBuffers[0].Stride); GraphicsContext.CommandList.SetIndexBuffer(mesh.Draw.IndexBuffer.Buffer, mesh.Draw.IndexBuffer.Offset, mesh.Draw.IndexBuffer.Is32Bit); for (var i = 0; i < myDraws.Length; ++i) { simpleEffect.Parameters.Set(TexturingKeys.Sampler, myDraws[i].Sampler); simpleEffect.Parameters.Set(SpriteBaseKeys.MatrixTransform, myDraws[i].Transform); simpleEffect.Apply(GraphicsContext); GraphicsContext.CommandList.DrawIndexed(6); } }
protected override void Draw(GameTime gameTime) { base.Draw(gameTime); var cl = GraphicsContext.CommandList; cl.ResetTargets(); var gp = GraphicsDevice.Presenter; cl.Clear(gp.BackBuffer, Color.Blue); cl.Clear(gp.DepthStencilBuffer, DepthStencilClearOptions.DepthBuffer | DepthStencilClearOptions.Stencil); // Render to the backbuffer cl.SetRenderTargetAndViewport(gp.DepthStencilBuffer, gp.BackBuffer); if (_tribuf == null) { Init(); } simpleEffect.UpdateEffect(GraphicsDevice); pipelineState.State.RootSignature = simpleEffect.RootSignature; pipelineState.State.EffectBytecode = simpleEffect.Effect.Bytecode; pipelineState.State.BlendState = BlendStates.Default; pipelineState.State.Output.CaptureState(cl); pipelineState.Update(); cl.SetPipelineState(pipelineState.CurrentState); // Apply the effect simpleEffect.Apply(GraphicsContext); cl.SetVertexBuffer(0, _tribuf, 0, 16); cl.Draw(3, 0); }
protected override void DrawCore(RenderDrawContext context) { if (string.IsNullOrEmpty(ShaderSourceName)) { return; } Parameters.Set(ComputeEffectShaderKeys.ThreadNumbers, ThreadNumbers); Parameters.Set(ComputeEffectShaderKeys.ComputeShaderName, ShaderSourceName); Parameters.Set(ComputeShaderBaseKeys.ThreadGroupCountGlobal, ThreadGroupCounts); if (pipelineStateDirty) { EffectInstance.UpdateEffect(GraphicsDevice); pipelineState.State.SetDefaults(); pipelineState.State.RootSignature = EffectInstance.RootSignature; pipelineState.State.EffectBytecode = EffectInstance.Effect.Bytecode; pipelineState.Update(); pipelineStateDirty = false; } // Apply pipeline state context.CommandList.SetPipelineState(pipelineState.CurrentState); // Apply the effect EffectInstance.Apply(context.GraphicsContext); // Draw a full screen quad context.CommandList.Dispatch(ThreadGroupCounts.X, ThreadGroupCounts.Y, ThreadGroupCounts.Z); // Un-apply //throw new InvalidOperationException(); //EffectInstance.Effect.UnbindResources(GraphicsDevice); }
/// <summary> /// Begins text rendering (swaps and maps the vertex buffer to write to). /// </summary> /// <param name="graphicsContext">The current GraphicsContext.</param> public void End([NotNull] GraphicsContext graphicsContext) { if (graphicsContext == null) { throw new ArgumentNullException(nameof(graphicsContext)); } // Unmap the vertex buffer graphicsContext.CommandList.UnmapSubresource(mappedVertexBuffer); mappedVertexBufferPointer = IntPtr.Zero; // Update pipeline state pipelineState.State.SetDefaults(); pipelineState.State.RootSignature = simpleEffect.RootSignature; pipelineState.State.EffectBytecode = simpleEffect.Effect.Bytecode; pipelineState.State.DepthStencilState = DepthStencilStates.None; pipelineState.State.BlendState = BlendStates.AlphaBlend; pipelineState.State.Output.CaptureState(graphicsContext.CommandList); pipelineState.State.InputElements = inputElementDescriptions[activeVertexBufferIndex]; pipelineState.Update(); graphicsContext.CommandList.SetPipelineState(pipelineState.CurrentState); // Update effect simpleEffect.UpdateEffect(graphicsContext.CommandList.GraphicsDevice); simpleEffect.Apply(graphicsContext); // Bind and draw graphicsContext.CommandList.SetVertexBuffer(0, vertexBuffersBinding[activeVertexBufferIndex].Buffer, vertexBuffersBinding[activeVertexBufferIndex].Offset, vertexBuffersBinding[activeVertexBufferIndex].Stride); graphicsContext.CommandList.SetIndexBuffer(indexBufferBinding.Buffer, 0, indexBufferBinding.Is32Bit); graphicsContext.CommandList.DrawIndexed(charsToRenderCount * 6); }
protected override async Task LoadContent() { await base.LoadContent(); var view = Matrix.LookAtRH(new Vector3(2, 2, 2), new Vector3(0, 0, 0), Vector3.UnitY); var projection = Matrix.PerspectiveFovRH((float)Math.PI / 4.0f, (float)GraphicsDevice.Presenter.BackBuffer.ViewWidth / GraphicsDevice.Presenter.BackBuffer.ViewHeight, 0.1f, 100.0f); worldViewProjection = Matrix.Multiply(view, projection); geometry = GeometricPrimitive.Cube.New(GraphicsDevice); simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(TexturingKeys.Texture0, UVTexture); simpleEffect.UpdateEffect(GraphicsDevice); // TODO DisposeBy is not working with device reset offlineTarget0 = Texture.New2D(GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget).DisposeBy(this); offlineTarget1 = Texture.New2D(GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget).DisposeBy(this); offlineTarget2 = Texture.New2D(GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget).DisposeBy(this); depthBuffer = Texture.New2D(GraphicsDevice, 512, 512, PixelFormat.D16_UNorm, TextureFlags.DepthStencil).DisposeBy(this); width = GraphicsDevice.Presenter.BackBuffer.ViewWidth; height = GraphicsDevice.Presenter.BackBuffer.ViewHeight; }
protected override void Draw(GameTime gameTime) { base.Draw(gameTime); // Clear screen GraphicsContext.CommandList.Clear(GraphicsDevice.Presenter.BackBuffer, Color.CornflowerBlue); GraphicsContext.CommandList.Clear(GraphicsDevice.Presenter.DepthStencilBuffer, DepthStencilClearOptions.DepthBuffer | DepthStencilClearOptions.Stencil); // Set render target GraphicsContext.CommandList.SetRenderTargetAndViewport(GraphicsDevice.Presenter.DepthStencilBuffer, GraphicsDevice.Presenter.BackBuffer); var time = (float)gameTime.Total.TotalSeconds; // Compute matrices var world = Matrix.Scaling((float)Math.Sin(time * 1.5f) * 0.2f + 1.0f) * Matrix.RotationX(time) * Matrix.RotationY(time * 2.0f) * Matrix.RotationZ(time * .7f) * Matrix.Translation(0, 0, 0); var projection = Matrix.PerspectiveFovRH((float)Math.PI / 4.0f, (float)GraphicsDevice.Presenter.BackBuffer.ViewWidth / GraphicsDevice.Presenter.BackBuffer.ViewHeight, 0.1f, 100.0f); // Setup effect/shader simpleEffect.Parameters.Set(SpriteBaseKeys.MatrixTransform, Matrix.Multiply(world, Matrix.Multiply(view, projection))); simpleEffect.UpdateEffect(GraphicsDevice); // Draw teapot.Draw(GraphicsContext, simpleEffect); }
/// <summary> /// Initializes a FastTextRendering instance (create and build required ressources, ...). /// </summary> /// <param name="graphicsContext">The current GraphicsContext.</param> private unsafe void Initialize(GraphicsContext graphicsContext, int maxCharacters) { maxCharacterCount = maxCharacters; var indexBufferSize = maxCharacters * 6 * sizeof(int); var indexBufferLength = indexBufferSize / IndexStride; // Map and build the indice buffer indexBuffer = graphicsContext.Allocator.GetTemporaryBuffer(new BufferDescription(indexBufferSize, BufferFlags.IndexBuffer, GraphicsResourceUsage.Dynamic)); var mappedIndices = graphicsContext.CommandList.MapSubresource(indexBuffer, 0, MapMode.WriteNoOverwrite, false, 0, indexBufferSize); var indexPointer = mappedIndices.DataBox.DataPointer; var i = 0; for (var c = 0; c < maxCharacters; c++) { *(int *)(indexPointer + IndexStride * i++) = c * 4 + 0; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 1; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 2; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 1; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 3; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 2; } graphicsContext.CommandList.UnmapSubresource(mappedIndices); indexBufferBinding = new IndexBufferBinding(Buffer.Index.New(graphicsContext.CommandList.GraphicsDevice, new DataPointer(indexPointer, indexBufferSize)), true, indexBufferLength); // Create vertex buffers vertexBuffers = new Buffer[VertexBufferCount]; for (int j = 0; j < VertexBufferCount; j++) { vertexBuffers[j] = Buffer.Vertex.New(graphicsContext.CommandList.GraphicsDevice, new VertexPositionNormalTexture[VertexBufferLength], GraphicsResourceUsage.Dynamic); } vertexBuffersBinding = new VertexBufferBinding[VertexBufferCount]; for (int j = 0; j < VertexBufferCount; j++) { vertexBuffersBinding[j] = new VertexBufferBinding(vertexBuffers[j], VertexPositionNormalTexture.Layout, 0); } inputElementDescriptions = new InputElementDescription[VertexBufferCount][]; for (int j = 0; j < VertexBufferCount; j++) { inputElementDescriptions[j] = vertexBuffersBinding[j].Declaration.CreateInputElements(); } // Create the pipeline state object pipelineState = new MutablePipelineState(graphicsContext.CommandList.GraphicsDevice); pipelineState.State.SetDefaults(); pipelineState.State.InputElements = inputElementDescriptions[0]; pipelineState.State.PrimitiveType = PrimitiveType.TriangleList; // Create the effect simpleEffect = new EffectInstance(new Effect(graphicsContext.CommandList.GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(TexturingKeys.Sampler, graphicsContext.CommandList.GraphicsDevice.SamplerStates.LinearClamp); simpleEffect.UpdateEffect(graphicsContext.CommandList.GraphicsDevice); }
protected override void DrawCore(RenderDrawContext context) { if (EffectInstance.UpdateEffect(GraphicsDevice) || pipelineStateDirty || previousBytecode != EffectInstance.Effect.Bytecode) { // The EffectInstance might have been updated from outside previousBytecode = EffectInstance.Effect.Bytecode; pipelineState.State.SetDefaults(); pipelineState.State.RootSignature = EffectInstance.RootSignature; pipelineState.State.EffectBytecode = EffectInstance.Effect.Bytecode; pipelineState.State.InputElements = PrimitiveQuad.VertexDeclaration.CreateInputElements(); pipelineState.State.PrimitiveType = PrimitiveQuad.PrimitiveType; pipelineState.State.BlendState = blendState; pipelineState.State.Output.CaptureState(context.CommandList); pipelineState.Update(); pipelineStateDirty = false; } context.CommandList.SetPipelineState(pipelineState.CurrentState); EffectInstance.Apply(context.GraphicsContext); // Draw a full screen quad context.GraphicsDevice.PrimitiveQuad.Draw(context.CommandList); }
protected override unsafe void DrawCore(RenderDrawContext context) { // Clear render targets if there is a dependency conflict (D3D11 warning) if (delaySetRenderTargets) { context.CommandList.ResetTargets(); } if (EffectInstance.UpdateEffect(GraphicsDevice) || pipelineStateDirty || previousBytecode != EffectInstance.Effect.Bytecode) { // The EffectInstance might have been updated from outside previousBytecode = EffectInstance.Effect.Bytecode; pipelineState.State.RootSignature = EffectInstance.RootSignature; pipelineState.State.EffectBytecode = EffectInstance.Effect.Bytecode; pipelineState.State.BlendState = blendState; pipelineState.State.DepthStencilState = depthStencilState; var renderTargetCount = OutputCount; if (renderTargetCount > 0) { // Special case: texture cube var isTextureCube = GetOutput(0).ViewDimension == TextureDimension.TextureCube; if (isTextureCube) { renderTargetCount = 6; } // Capture output state manually (since render targets might not be bound if delaySetRenderTargets is set to true) pipelineState.State.Output.RenderTargetCount = renderTargetCount; fixed(PixelFormat *pixelFormatStart = &pipelineState.State.Output.RenderTargetFormat0) for (int i = 0; i < renderTargetCount; ++i) { pixelFormatStart[i] = GetOutput(isTextureCube ? 0 : i).ViewFormat; } } if (HasDepthStencilOutput) { pipelineState.State.Output.DepthStencilFormat = DepthStencil.Format; } pipelineState.Update(); pipelineStateDirty = false; } context.CommandList.SetPipelineState(pipelineState.CurrentState); EffectInstance.Apply(context.GraphicsContext); // Now that resources are bound, set render targets if (delaySetRenderTargets) { SetRenderTargets(context); } // Draw a full screen quad context.GraphicsDevice.PrimitiveQuad.Draw(context.CommandList); }
void CreateDeviceObjects() { // set up a commandlist commandList = context.CommandList; // compile de shader imShader = new EffectInstance(effectSystem.LoadEffect("ImGuiShader").WaitForResult()); imShader.UpdateEffect(device); var layout = new VertexDeclaration( VertexElement.Position <Vector2>(), VertexElement.TextureCoordinate <Vector2>(), VertexElement.Color(PixelFormat.R8G8B8A8_UNorm) ); imVertLayout = layout; // de pipeline desc var pipeline = new PipelineStateDescription() { BlendState = BlendStates.NonPremultiplied, RasterizerState = new RasterizerStateDescription() { CullMode = CullMode.None, DepthBias = 0, FillMode = FillMode.Solid, MultisampleAntiAliasLine = false, ScissorTestEnable = true, SlopeScaleDepthBias = 0, }, PrimitiveType = PrimitiveType.TriangleList, InputElements = imVertLayout.CreateInputElements(), DepthStencilState = DepthStencilStates.Default, EffectBytecode = imShader.Effect.Bytecode, RootSignature = imShader.RootSignature, Output = new RenderOutputDescription(PixelFormat.R8G8B8A8_UNorm) }; // finally set up the pipeline var pipelineState = PipelineState.New(device, ref pipeline); imPipeline = pipelineState; var is32Bits = false; var indexBuffer = Xenko.Graphics.Buffer.Index.New(device, INITIAL_INDEX_BUFFER_SIZE * sizeof(ushort), GraphicsResourceUsage.Dynamic); var indexBufferBinding = new IndexBufferBinding(indexBuffer, is32Bits, 0); indexBinding = indexBufferBinding; var vertexBuffer = Xenko.Graphics.Buffer.Vertex.New(device, INITIAL_VERTEX_BUFFER_SIZE * imVertLayout.CalculateSize(), GraphicsResourceUsage.Dynamic); var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, layout, 0); vertexBinding = vertexBufferBinding; }
protected override Task <bool> Initialize(EditorServiceGame editorGame) { game = (EntityHierarchyEditorGame)editorGame; // create the default font var fontItem = OfflineRasterizedSpriteFontFactory.Create(); fontItem.FontType.Size = 8; defaultFont = OfflineRasterizedFontCompiler.Compile(game.Services.GetService <IFontFactory>(), fontItem, game.GraphicsDevice.ColorSpace == ColorSpace.Linear); incrustBatch = new SpriteBatch(game.GraphicsDevice); // SpriteEffect will be used to draw camera incrust border spriteEffect = new EffectInstance(new Graphics.Effect(game.GraphicsDevice, SpriteEffect.Bytecode)); spriteEffect.Parameters.Set(TexturingKeys.Texture0, game.GraphicsDevice.GetSharedWhiteTexture()); spriteEffect.UpdateEffect(game.GraphicsDevice); borderPipelineState = new MutablePipelineState(game.GraphicsDevice); borderPipelineState.State.RootSignature = spriteEffect.RootSignature; borderPipelineState.State.EffectBytecode = spriteEffect.Effect.Bytecode; borderPipelineState.State.InputElements = VertexPositionTexture.Layout.CreateInputElements(); borderPipelineState.State.PrimitiveType = PrimitiveType.LineStrip; borderPipelineState.State.RasterizerState = RasterizerStates.CullNone; unsafe { var borderVertices = new[] { new VertexPositionTexture(new Vector3(0.0f, 0.0f, 0.0f), Vector2.Zero), new VertexPositionTexture(new Vector3(0.0f, 1.0f, 0.0f), Vector2.Zero), new VertexPositionTexture(new Vector3(1.0f, 1.0f, 0.0f), Vector2.Zero), new VertexPositionTexture(new Vector3(1.0f, 0.0f, 0.0f), Vector2.Zero), new VertexPositionTexture(new Vector3(0.0f, 0.0f, 0.0f), Vector2.Zero), new VertexPositionTexture(new Vector3(0.0f, 1.0f, 0.0f), Vector2.Zero), // extra vertex so that left-top corner is not missing (likely due to rasterization rule) }; fixed(VertexPositionTexture *borderVerticesPtr = borderVertices) borderVertexBuffer = Graphics.Buffer.Vertex.New(game.GraphicsDevice, new DataPointer(borderVerticesPtr, VertexPositionTexture.Size * borderVertices.Length)); } var editorTopLevel = game.EditorSceneSystem.GraphicsCompositor.Game as EditorTopLevelCompositor; if (editorTopLevel != null) { // Display it as incrust editorTopLevel.PostGizmoCompositors.Add(renderIncrustRenderer = new RenderIncrustRenderer(this)); } Services.Get <IEditorGameEntitySelectionService>().SelectionUpdated += UpdateModifiedEntitiesList; return(Task.FromResult(true)); }
private void CreateDeviceObjects() { var commandList = Game.GraphicsContext.CommandList; var shader = new EffectInstance(EffectSystem.LoadEffect("MultiMeshShader").WaitForResult()); shader.UpdateEffect(GraphicsDevice); streamShader = shader; var outputDesc = new RenderOutputDescription(GraphicsDevice.Presenter.BackBuffer.Format); outputDesc.CaptureState(commandList); var pipeline = new PipelineStateDescription() { /* TODO: do we need all these? */ BlendState = BlendStates.Default, RasterizerState = RasterizerStateDescription.Default, DepthStencilState = DepthStencilStates.None, Output = outputDesc, PrimitiveType = PrimitiveType.TriangleList, InputElements = VertexType.Layout.CreateInputElements(), EffectBytecode = shader.Effect.Bytecode, RootSignature = shader.RootSignature, }; var newPipelineState = PipelineState.New(GraphicsDevice, ref pipeline); pipelineState = newPipelineState; var streamBuffer = Xenko.Graphics.Buffer.New <VertexType>( GraphicsDevice, INITIAL_INSTANCE_COUNT, BufferFlags.VertexBuffer | BufferFlags.StreamOutput ); streamOutBufferBinding = new VertexBufferBinding(streamBuffer, VertexType.Layout, streamBuffer.ElementCount); transformBuffer = Xenko.Graphics.Buffer.Structured.New <Matrix>( GraphicsDevice, INITIAL_INSTANCE_COUNT, isUnorderedAccess: true ); colorBuffer = Xenko.Graphics.Buffer.Structured.New <Color4>( GraphicsDevice, INITIAL_INSTANCE_COUNT, isUnorderedAccess: true ); }
/// <summary> /// Initializes a new instance of the <see cref="PrimitiveQuad" /> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> /// <param name="effect">The effect.</param> public PrimitiveQuad(GraphicsDevice graphicsDevice) { GraphicsDevice = graphicsDevice; sharedData = GraphicsDevice.GetOrCreateSharedData(GraphicsDeviceSharedDataType.PerDevice, "PrimitiveQuad::VertexBuffer", d => new SharedData(GraphicsDevice)); simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(SpriteBaseKeys.MatrixTransform, Matrix.Identity); simpleEffect.UpdateEffect(graphicsDevice); pipelineState = new MutablePipelineState(GraphicsDevice); pipelineState.State.SetDefaults(); pipelineState.State.InputElements = VertexDeclaration.CreateInputElements(); pipelineState.State.PrimitiveType = PrimitiveType; }
/// <summary> /// Draws a quad. The effect must have been applied before calling this method with pixel shader having the signature float2:TEXCOORD. /// </summary> /// <param name="texture"></param> public void Draw(GraphicsContext graphicsContext, EffectInstance effectInstance) { effectInstance.UpdateEffect(GraphicsDevice); pipelineState.State.RootSignature = effectInstance.RootSignature; pipelineState.State.EffectBytecode = effectInstance.Effect.Bytecode; pipelineState.State.BlendState = BlendStates.Default; pipelineState.State.Output.CaptureState(graphicsContext.CommandList); pipelineState.Update(); graphicsContext.CommandList.SetPipelineState(pipelineState.CurrentState); // Apply the effect effectInstance.Apply(graphicsContext); Draw(graphicsContext.CommandList); }
private void Init() { _tribuf = Buffer.New(GraphicsDevice, new[] { new Vector4(-0.5f, 0.5f, 0, 1), new Vector4(0.5f, 0.5f, 0, 1), new Vector4(0, -0.5f, 0, 1) }, BufferFlags.VertexBuffer, GraphicsResourceUsage.Immutable); simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(SpriteBaseKeys.MatrixTransform, Matrix.Identity); simpleEffect.UpdateEffect(GraphicsDevice); pipelineState = new MutablePipelineState(GraphicsDevice); pipelineState.State.SetDefaults(); pipelineState.State.InputElements = VertexDeclaration.CreateInputElements(); pipelineState.State.PrimitiveType = PrimitiveType; }
public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage) { float blendValue = (selectionService?.DisplaySelectionMask ?? false) ? 1.0f : MathUtil.Clamp((1.0f - (float)clockSelection.Elapsed.TotalSeconds), 0.0f, 1.0f); shader.UpdateEffect(context.GraphicsDevice); foreach (var renderNode in renderViewStage.SortedRenderNodes) { var renderMesh = renderNode.RenderObject as RenderMesh; if (renderMesh == null) { continue; } MeshDraw drawData = renderMesh.ActiveMeshDraw; // bind VB for (int slot = 0; slot < drawData.VertexBuffers.Length; slot++) { var vertexBuffer = drawData.VertexBuffers[slot]; context.CommandList.SetVertexBuffer(slot, vertexBuffer.Buffer, vertexBuffer.Offset, vertexBuffer.Stride); } // set shader parameters shader.Parameters.Set(SelectionWireframeShaderKeys.WorldViewProjection, renderMesh.World * renderView.ViewProjection); // matrix shader.Parameters.Set(SelectionWireframeShaderKeys.WorldScale, new Vector3(1.0001f)); // increase scale to avoid z-fight shader.Parameters.Set(SelectionWireframeShaderKeys.Viewport, new Vector4(context.RenderContext.RenderView.ViewSize, 0, 0)); shader.Parameters.Set(SelectionWireframeShaderKeys.LineWidth, LineWidth); // prepare pipeline state pipelineState.State.RootSignature = shader.RootSignature; pipelineState.State.EffectBytecode = shader.Effect.Bytecode; pipelineState.State.PrimitiveType = drawData.PrimitiveType; Draw(context, drawData, GetColor(ColorOccludedLines, blendValue), DepthStencilStates.None); // occluded Draw(context, drawData, GetColor(ColorNonOccludedLines, blendValue), DepthStencilStates.DepthRead); // non-occluded } }
public VideoTexture(GraphicsDevice graphicsDevice, IServiceRegistry serviceRegistry, int width, int height, int maxMipMapCount) { if (width <= 0 || height <= 0) { throw new InvalidOperationException("Invalid video resolution."); } if (maxMipMapCount < 0) { throw new InvalidOperationException("A negative number of mip maps is not allowed."); } var effectSystem = serviceRegistry.GetSafeServiceAs <EffectSystem>(); // We want to sample mip maps using point filtering (to make sure nothing bleeds between mip maps). minMagLinearMipPointSampler = SamplerState.New(graphicsDevice, new SamplerStateDescription(TextureFilter.MinMagLinearMipPoint, TextureAddressMode.Clamp)); // Allocate the effect for copying decoder output texture to our normal render texture effectDecoderTextureCopy = new EffectInstance(effectSystem.LoadEffect("SpriteEffectExtTexture").WaitForResult()); effectDecoderTextureCopy.Parameters.Set(SpriteEffectExtTextureKeys.Gamma, 2.2f); effectDecoderTextureCopy.Parameters.Set(SpriteEffectExtTextureKeys.MipLevel, 0.0f); effectDecoderTextureCopy.Parameters.Set(SpriteEffectExtTextureKeys.Sampler, minMagLinearMipPointSampler); effectDecoderTextureCopy.UpdateEffect(graphicsDevice); // Allocate the effect for copying regular 2d textures: effectTexture2DCopy = new EffectInstance(effectSystem.LoadEffect("SpriteEffectExtTextureRegular").WaitForResult()); effectTexture2DCopy.Parameters.Set(SpriteEffectExtTextureKeys.MipLevel, 0.0f); effectTexture2DCopy.Parameters.Set(SpriteEffectExtTextureRegularKeys.Sampler, minMagLinearMipPointSampler); effectTexture2DCopy.UpdateEffect(graphicsDevice); // Create a mip mapped texture with the same size as our video // Only generate up to "MaxMipMapCount" number of mip maps var mipMapCount = Math.Min(Texture.CountMips(Math.Max(width, height)), maxMipMapCount + 1); var textureDescription = TextureDescription.New2D(width, height, mipMapCount, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.ShaderResource | TextureFlags.RenderTarget, 1, GraphicsResourceUsage.Dynamic); renderTargetTexture = Texture.New(graphicsDevice, textureDescription, null); // Supply no data. Create an empty texture. }
protected override async Task LoadContent() { await base.LoadContent(); wireframeState = new RasterizerStateDescription(CullMode.Back) { FillMode = FillMode.Wireframe }; simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); // TODO GRAPHICS REFACTOR simpleEffect.Parameters.Set(TexturingKeys.Texture0, UVTexture); simpleEffect.UpdateEffect(GraphicsDevice); primitives = new List <GeometricPrimitive>(); // Creates all primitives primitives = new List <GeometricPrimitive> { GeometricPrimitive.Plane.New(GraphicsDevice), GeometricPrimitive.Cube.New(GraphicsDevice), GeometricPrimitive.Sphere.New(GraphicsDevice), GeometricPrimitive.GeoSphere.New(GraphicsDevice), GeometricPrimitive.Cylinder.New(GraphicsDevice), GeometricPrimitive.Torus.New(GraphicsDevice), GeometricPrimitive.Teapot.New(GraphicsDevice), GeometricPrimitive.Capsule.New(GraphicsDevice, 0.5f, 0.3f), GeometricPrimitive.Cone.New(GraphicsDevice) }; view = Matrix.LookAtRH(new Vector3(0, 0, 5), new Vector3(0, 0, 0), Vector3.UnitY); Window.AllowUserResizing = true; }
/// <summary> /// Initializes a new instance of the <see cref="XenkoGeometryBuffer"/> class. /// </summary> public XenkoGeometryBuffer() : base() { effect = new EffectInstance(new Effect(XenkoRenderer.GraphicsDevice, SpriteEffect.Bytecode)); effect.UpdateEffect(XenkoRenderer.GraphicsDevice); }
/// <summary> /// Begins text rendering (swaps and maps the vertex buffer to write to). /// </summary> /// <param name="graphicsContext">The current GraphicsContext.</param> public void End([NotNull] GraphicsContext graphicsContext) { if (graphicsContext == null) { throw new ArgumentNullException(nameof(graphicsContext)); } // Reallocate buffers if max number of characters is exceeded if (charsToRenderCount > maxCharacterCount) { maxCharacterCount = (int)(1.5f * charsToRenderCount); Initialize(graphicsContext, maxCharacterCount); } // Set the rendering parameters simpleEffect.Parameters.Set(TexturingKeys.Texture0, DebugSpriteFont); simpleEffect.Parameters.Set(SpriteEffectKeys.Color, TextColor); // Swap vertex buffer activeVertexBufferIndex = ++activeVertexBufferIndex >= VertexBufferCount ? 0 : activeVertexBufferIndex; // Map the vertex buffer to write to mappedVertexBuffer = graphicsContext.CommandList.MapSubresource(vertexBuffers[activeVertexBufferIndex], 0, MapMode.WriteDiscard); mappedVertexBufferPointer = mappedVertexBuffer.DataBox.DataPointer; unsafe { // Clear buffer first (because of the buffer mapping mode used) Utilities.ClearMemory(mappedVertexBufferPointer, 0x0, VertexBufferLength * sizeof(VertexPositionNormalTexture)); charsToRenderCount = 0; //Draw the strings var constantInfos = new RectangleF(GlyphWidth, GlyphHeight, DebugSpriteWidth, DebugSpriteHeight); foreach (var textInfo in stringsToDraw) { var textLength = textInfo.Text.Length; var textLengthPointer = new IntPtr(&textLength); Native.NativeInvoke.xnGraphicsFastTextRendererGenerateVertices(constantInfos, textInfo.RenderingInfo, textInfo.Text, out textLengthPointer, out mappedVertexBufferPointer); charsToRenderCount += *(int *)textLengthPointer.ToPointer(); } } // Unmap the vertex buffer graphicsContext.CommandList.UnmapSubresource(mappedVertexBuffer); mappedVertexBufferPointer = IntPtr.Zero; // Update pipeline state pipelineState.State.SetDefaults(); pipelineState.State.RootSignature = simpleEffect.RootSignature; pipelineState.State.EffectBytecode = simpleEffect.Effect.Bytecode; pipelineState.State.DepthStencilState = DepthStencilStates.None; pipelineState.State.BlendState = BlendStates.AlphaBlend; pipelineState.State.Output.CaptureState(graphicsContext.CommandList); pipelineState.State.InputElements = inputElementDescriptions[activeVertexBufferIndex]; pipelineState.Update(); graphicsContext.CommandList.SetPipelineState(pipelineState.CurrentState); // Update effect simpleEffect.UpdateEffect(graphicsContext.CommandList.GraphicsDevice); simpleEffect.Apply(graphicsContext); // Bind and draw graphicsContext.CommandList.SetVertexBuffer(0, vertexBuffersBinding[activeVertexBufferIndex].Buffer, vertexBuffersBinding[activeVertexBufferIndex].Offset, vertexBuffersBinding[activeVertexBufferIndex].Stride); graphicsContext.CommandList.SetIndexBuffer(indexBufferBinding.Buffer, 0, indexBufferBinding.Is32Bit); graphicsContext.CommandList.DrawIndexed(charsToRenderCount * 6); }
protected override void DrawCore(RenderDrawContext context) { if (string.IsNullOrEmpty(ShaderSourceName) || FRefreshTime > context.RenderContext.Time.Total) { return; } Parameters.Set(ComputeEffectShaderKeys.ThreadNumbers, ThreadNumbers); Parameters.Set(ComputeEffectShaderKeys.ComputeShaderName, ShaderSourceName); Parameters.Set(ComputeShaderBaseKeys.ThreadGroupCountGlobal, ThreadGroupCounts); var effectUpdated = false; try { effectUpdated = EffectInstance.UpdateEffect(GraphicsDevice); FCompiled = true; LastError = string.Empty; } catch (Exception e) { LastError = e.InnermostException().Message; FCompiled = false; FRefreshTime = context.RenderContext.Time.Total + TimeSpan.FromSeconds(3); } if (!FCompiled) { return; } try { if (effectUpdated || pipelineStateDirty || previousBytecode != EffectInstance.Effect.Bytecode) { // The EffectInstance might have been updated from outside previousBytecode = EffectInstance.Effect.Bytecode; pipelineState.State.SetDefaults(); pipelineState.State.RootSignature = EffectInstance.RootSignature; pipelineState.State.EffectBytecode = EffectInstance.Effect.Bytecode; pipelineState.Update(); pipelineStateDirty = false; } } catch (Exception e) { LastError = e.InnermostException().Message; FCompiled = false; FRefreshTime = context.RenderContext.Time.Total + TimeSpan.FromSeconds(3); return; } // Apply pipeline state var commandList = context.CommandList; commandList.SetPipelineState(pipelineState.CurrentState); drawRenderDrawContext = context; drawCommandList = commandList; // Un-apply //throw new InvalidOperationException(); //EffectInstance.Effect.UnbindResources(GraphicsDevice); }
protected override async Task LoadContent() { await base.LoadContent(); pipelineState = new MutablePipelineState(GraphicsDevice); var vertices = new Vertex[4]; vertices[0] = new Vertex { Position = new Vector3(-1, -1, 0.5f), TexCoords = new Vector2(0, 0) }; vertices[1] = new Vertex { Position = new Vector3(-1, 1, 0.5f), TexCoords = new Vector2(3, 0) }; vertices[2] = new Vertex { Position = new Vector3(1, 1, 0.5f), TexCoords = new Vector2(3, 3) }; vertices[3] = new Vertex { Position = new Vector3(1, -1, 0.5f), TexCoords = new Vector2(0, 3) }; var indices = new short[] { 0, 1, 2, 0, 2, 3 }; var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices, GraphicsResourceUsage.Default); var indexBuffer = Buffer.Index.New(GraphicsDevice, indices, GraphicsResourceUsage.Default); var meshDraw = new MeshDraw { DrawCount = 4, PrimitiveType = PrimitiveType.TriangleList, VertexBuffers = new[] { new VertexBufferBinding(vertexBuffer, new VertexDeclaration(VertexElement.Position <Vector3>(), VertexElement.TextureCoordinate <Vector2>()), 4) }, IndexBuffer = new IndexBufferBinding(indexBuffer, false, indices.Length), }; mesh = new Mesh { Draw = meshDraw, }; simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(TexturingKeys.Texture0, UVTexture); simpleEffect.UpdateEffect(GraphicsDevice); // TODO GRAPHICS REFACTOR //vao = VertexArrayObject.New(GraphicsDevice, mesh.Draw.IndexBuffer, mesh.Draw.VertexBuffers); myDraws = new DrawOptions[3]; myDraws[0] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearClamp, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(-0.5f, 0.5f, 0f)) }; myDraws[1] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearWrap, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, 0.5f, 0f)) }; myDraws[2] = new DrawOptions { Sampler = SamplerState.New(GraphicsDevice, new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Mirror)), Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, -0.5f, 0f)) }; //var borderDescription = new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Border) { BorderColor = Color.Purple }; //var border = SamplerState.New(GraphicsDevice, borderDescription); //myDraws[3] = new DrawOptions { Sampler = border, Transform = Matrix.Multiply(Matrix.Scale(0.3f), Matrix.Translation(-0.5f, -0.5f, 0f)) }; }
/// <summary> /// Initializes a FastTextRendering instance (create and build required ressources, ...). /// </summary> /// <param name="graphicsContext">The current GraphicsContext.</param> public unsafe FastTextRenderer Initialize([NotNull] GraphicsContext graphicsContext) { var indexBufferSize = MaxCharactersPerLine * MaxCharactersLines * 6 * sizeof(int); var indexBufferLength = indexBufferSize / IndexStride; // Map and build the indice buffer indexBuffer = graphicsContext.Allocator.GetTemporaryBuffer(new BufferDescription(indexBufferSize, BufferFlags.IndexBuffer, GraphicsResourceUsage.Dynamic)); var mappedIndices = graphicsContext.CommandList.MapSubresource(indexBuffer, 0, MapMode.WriteNoOverwrite, false, 0, indexBufferSize); var indexPointer = mappedIndices.DataBox.DataPointer; var i = 0; for (var c = 0; c < MaxCharactersPerLine * MaxCharactersLines; c++) { *(int *)(indexPointer + IndexStride * i++) = c * 4 + 0; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 1; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 2; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 1; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 3; *(int *)(indexPointer + IndexStride * i++) = c * 4 + 2; } graphicsContext.CommandList.UnmapSubresource(mappedIndices); indexBufferBinding = new IndexBufferBinding(Buffer.Index.New(graphicsContext.CommandList.GraphicsDevice, new DataPointer(indexPointer, indexBufferSize)), true, indexBufferLength); // Create vertex buffers var vertexBufferLength = MaxCharactersPerLine * MaxCharactersLines * 4; vertexBuffers = new Buffer[] { Buffer.Vertex.New(graphicsContext.CommandList.GraphicsDevice, new VertexPositionNormalTexture[vertexBufferLength], GraphicsResourceUsage.Dynamic), Buffer.Vertex.New(graphicsContext.CommandList.GraphicsDevice, new VertexPositionNormalTexture[vertexBufferLength], GraphicsResourceUsage.Dynamic) }; vertexBuffersBinding = new[] { new VertexBufferBinding(vertexBuffers[0], VertexPositionNormalTexture.Layout, 0), new VertexBufferBinding(vertexBuffers[1], VertexPositionNormalTexture.Layout, 0) }; inputElementDescriptions = new[] { vertexBuffersBinding[0].Declaration.CreateInputElements(), vertexBuffersBinding[1].Declaration.CreateInputElements() }; // Create the pipeline state object pipelineState = new MutablePipelineState(graphicsContext.CommandList.GraphicsDevice); pipelineState.State.SetDefaults(); pipelineState.State.InputElements = inputElementDescriptions[0]; pipelineState.State.PrimitiveType = PrimitiveType.TriangleList; // Create the effect simpleEffect = new EffectInstance(new Effect(graphicsContext.CommandList.GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(SpriteBaseKeys.MatrixTransform, Matrix.Identity); simpleEffect.Parameters.Set(TexturingKeys.Texture0, DebugSpriteFont); simpleEffect.Parameters.Set(TexturingKeys.Sampler, graphicsContext.CommandList.GraphicsDevice.SamplerStates.LinearClamp); simpleEffect.Parameters.Set(SpriteEffectKeys.Color, TextColor); simpleEffect.UpdateEffect(graphicsContext.CommandList.GraphicsDevice); return(this); }