コード例 #1
0
        private unsafe void FlushVertexArray(VertexPosition3ColorTexture *vertexArray, int vertexIndex, Texture2D texture, View view, Sampler sampler, IntRect?scissorRect)
        {
            if (texture == null)
            {
                return;
            }

            var vrsd            = new ResourceSetDescription(viewResourceLayout, worldMatrixBuffer);
            var viewResourceSet = factory.CreateResourceSet(vrsd);

            var grsd = new ResourceSetDescription(graphicsResourceLayout, texture.TextureView, sampler ?? device.PointSampler);
            var graphicsResourceSet = factory.CreateResourceSet(grsd);

            //TODO: Depth buffer
            commandList.Begin();
            commandList.UpdateBuffer(vertexBuffer, 0, (IntPtr)vertexArray, (uint)vertexIndex * VERTEX_SIZE);
            commandList.SetFramebuffer(framebuffer);
            commandList.SetViewport(0, view.ScreenView);
            if (scissorRect.HasValue)
            {
                var sr = scissorRect.Value;
                commandList.SetScissorRect(0, (uint)sr.X, (uint)sr.Y, (uint)sr.Width, (uint)sr.Height);
            }
            commandList.SetPipeline(pipeline);
            commandList.SetGraphicsResourceSet(0, viewResourceSet);
            commandList.SetGraphicsResourceSet(1, graphicsResourceSet);
            commandList.SetIndexBuffer(indexBuffer, IndexFormat.UInt16);
            commandList.SetVertexBuffer(0, vertexBuffer);
            commandList.DrawIndexed((uint)(vertexIndex * 1.5));
            commandList.End();
            device.SubmitCommands(commandList);

            viewResourceSet.Dispose();
            graphicsResourceSet.Dispose();
        }
コード例 #2
0
ファイル: BufferTests.cs プロジェクト: uzbekdev1/veldrid
        public unsafe void CopyBuffer_ZeroSize(BufferUsage usage)
        {
            DeviceBuffer src = CreateBuffer(1024, usage);
            DeviceBuffer dst = CreateBuffer(1024, usage);

            byte[] initialDataSrc = Enumerable.Range(0, 1024).Select(i => (byte)i).ToArray();
            byte[] initialDataDst = Enumerable.Range(0, 1024).Select(i => (byte)(i * 2)).ToArray();
            GD.UpdateBuffer(src, 0, initialDataSrc);
            GD.UpdateBuffer(dst, 0, initialDataDst);

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.CopyBuffer(src, 0, dst, 0, 0);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            DeviceBuffer readback = GetReadback(dst);

            MappedResourceView <byte> readMap = GD.Map <byte>(readback, MapMode.Read);

            for (int i = 0; i < 1024; i++)
            {
                Assert.Equal((byte)(i * 2), readMap[i]);
            }
            GD.Unmap(readback);
        }
コード例 #3
0
        protected override void Draw(float deltaSeconds)
        {
            _ticks += deltaSeconds * 1000f;
            _cl.Begin();

            _cl.UpdateBuffer(_projectionBuffer, 0, Matrix4x4.CreatePerspectiveFieldOfView(
                                 1.0f,
                                 (float)Window.Width / Window.Height,
                                 0.5f,
                                 100f));

            _cl.UpdateBuffer(_viewBuffer, 0, Matrix4x4.CreateLookAt(Vector3.UnitZ * 2.5f, Vector3.Zero, Vector3.UnitY));

            Matrix4x4 rotation =
                Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, (_ticks / 1000f))
                * Matrix4x4.CreateFromAxisAngle(Vector3.UnitX, (_ticks / 3000f));

            _cl.UpdateBuffer(_worldBuffer, 0, ref rotation);

            _cl.SetFramebuffer(MainSwapchain.Framebuffer);
            _cl.ClearColorTarget(0, RgbaFloat.Black);
            _cl.ClearDepthStencil(1f);
            _cl.SetPipeline(_pipeline);
            _cl.SetVertexBuffer(0, _vertexBuffer);
            _cl.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);
            _cl.SetGraphicsResourceSet(0, _projViewSet);
            _cl.SetGraphicsResourceSet(1, _worldTextureSet);
            _cl.DrawIndexed(36, 1, 0, 0, 0);

            _cl.End();
            GraphicsDevice.SubmitCommands(_cl);
            GraphicsDevice.SwapBuffers(MainSwapchain);
            GraphicsDevice.WaitForIdle();
        }
コード例 #4
0
        public void Execute(RenderContext context)
        {
            RenderedObjectsOpaque      = 0;
            RenderedObjectsTransparent = 0;

            EnsureIntermediateFramebuffer(context.GraphicsDevice, context.RenderTarget);

            _renderList.Clear();

            context.Scene3D?.BuildRenderList(
                _renderList,
                context.Scene3D.Camera,
                context.GameTime);

            BuildingRenderList?.Invoke(this, new BuildingRenderListEventArgs(
                                           _renderList,
                                           context.Scene3D?.Camera,
                                           context.GameTime));

            _commandList.Begin();

            if (context.Scene3D != null)
            {
                _commandList.PushDebugGroup("3D Scene");
                Render3DScene(_commandList, context.Scene3D, context);
                _commandList.PopDebugGroup();
            }
            else
            {
                _commandList.SetFramebuffer(_intermediateFramebuffer);
                _commandList.ClearColorTarget(0, ClearColor);
            }

            // GUI and camera-dependent 2D elements
            {
                _commandList.PushDebugGroup("2D Scene");

                _drawingContext.Begin(
                    _commandList,
                    context.ContentManager.LinearClampSampler,
                    new SizeF(context.RenderTarget.Width, context.RenderTarget.Height));

                context.Scene3D?.Render(_drawingContext);
                context.Scene2D?.Render(_drawingContext);

                Rendering2D?.Invoke(this, new Rendering2DEventArgs(_drawingContext));

                _drawingContext.End();

                _commandList.PopDebugGroup();
            }

            _commandList.End();

            context.GraphicsDevice.SubmitCommands(_commandList);

            _textureCopier.Execute(
                _intermediateTexture,
                context.RenderTarget);
        }
コード例 #5
0
ファイル: BufferTests.cs プロジェクト: uzbekdev1/veldrid
        public void CopyBuffer_Chain_Succeeds()
        {
            DeviceBuffer src = CreateBuffer(1024, BufferUsage.Staging);

            int[] data = Enumerable.Range(0, 256).Select(i => 2 * i).ToArray();
            GD.UpdateBuffer(src, 0, data);

            DeviceBuffer finalDst = CreateBuffer(1024, BufferUsage.Staging);

            for (int chainLength = 2; chainLength <= 10; chainLength += 4)
            {
                DeviceBuffer[] dsts = Enumerable.Range(0, chainLength)
                                      .Select(i => RF.CreateBuffer(new BufferDescription(1024, BufferUsage.UniformBuffer)))
                                      .ToArray();

                CommandList copyCL = RF.CreateCommandList();
                copyCL.Begin();
                copyCL.CopyBuffer(src, 0, dsts[0], 0, src.SizeInBytes);
                for (int i = 0; i < chainLength - 1; i++)
                {
                    copyCL.CopyBuffer(dsts[i], 0, dsts[i + 1], 0, src.SizeInBytes);
                }
                copyCL.CopyBuffer(dsts[dsts.Length - 1], 0, finalDst, 0, src.SizeInBytes);
                copyCL.End();
                GD.SubmitCommands(copyCL);
                GD.WaitForIdle();

                MappedResourceView <int> view = GD.Map <int>(finalDst, MapMode.Read);
                for (int i = 0; i < view.Count; i++)
                {
                    Assert.Equal(i * 2, view[i]);
                }
                GD.Unmap(finalDst);
            }
        }
コード例 #6
0
        /// <summary>
        /// Infinitely calls the Render task until the overlay closes.
        /// </summary>
        private async Task RunInfiniteLoop(CancellationToken cancellationToken)
        {
            var stopwatch = Stopwatch.StartNew();

            while (window.Exists && !cancellationToken.IsCancellationRequested)
            {
                InputSnapshot snapshot = window.PumpEvents();
                if (!window.Exists)
                {
                    break;
                }

                var deltaSeconds = (float)stopwatch.ElapsedTicks / Stopwatch.Frequency;
                stopwatch.Restart();
                imController.Update(deltaSeconds, snapshot, window.Handle);

                await Render();

                commandList.Begin();
                commandList.SetFramebuffer(graphicsDevice.MainSwapchain.Framebuffer);
                commandList.ClearColorTarget(0, new RgbaFloat(0.00f, 0.00f, 0.00f, 0.00f));
                imController.Render(graphicsDevice, commandList);
                commandList.End();
                graphicsDevice.SubmitCommands(commandList);
                graphicsDevice.SwapBuffers(graphicsDevice.MainSwapchain);
            }

            if (window.Exists)
            {
                window.Close();
            }
        }
コード例 #7
0
        private static void Draw()
        {
            // Begin() must be called before commands can be issued.
            _commandList.Begin();

            // We want to render directly to the output window.
            _commandList.SetFramebuffer(_graphicsDevice.SwapchainFramebuffer);
            _commandList.ClearColorTarget(0, RgbaFloat.Black);

            // Set all relevant state to draw our quad.
            _commandList.SetVertexBuffer(0, _vertexBuffer);
            _commandList.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);
            _commandList.SetPipeline(_pipeline);
            // Issue a Draw command for a single instance with 4 indices.
            _commandList.DrawIndexed(
                indexCount: 4,
                instanceCount: 1,
                indexStart: 0,
                vertexOffset: 0,
                instanceStart: 0);

            // End() must be called before commands can be submitted for execution.
            _commandList.End();
            _graphicsDevice.SubmitCommands(_commandList);

            // Once commands have been submitted, the rendered image can be presented to the application window.
            _graphicsDevice.SwapBuffers();
        }
コード例 #8
0
        /// <summary>
        /// Infinite While Loop to render the ImGui.
        /// </summary>
        private void WhileLoop()
        {
            while (window.Exists)
            {
                if (requireResize)
                {
                    Sdl2Native.SDL_SetWindowPosition(window.SdlWindowHandle, (int)futurePos.X, (int)futurePos.Y);
                    Sdl2Native.SDL_SetWindowSize(window.SdlWindowHandle, (int)futureSize.X, (int)futureSize.Y);
                    window.PumpEvents();
                    continue;
                }

                if (!window.Visible)
                {
                    window.PumpEvents();
                    Thread.Sleep(10);
                    continue;
                }

                if (!window.Exists)
                {
                    break;
                }

                imController.InitlizeFrame(1f / myFps);
                this.SubmitUI?.Invoke(this, new EventArgs());
                commandList.Begin();
                commandList.SetFramebuffer(graphicsDevice.MainSwapchain.Framebuffer);
                commandList.ClearColorTarget(0, new RgbaFloat(clearColor.X, clearColor.Y, clearColor.Z, clearColor.W));
                imController.Render(graphicsDevice, commandList);
                commandList.End();
                graphicsDevice.SubmitCommands(commandList);
                graphicsDevice.SwapBuffers(graphicsDevice.MainSwapchain);
            }
        }
コード例 #9
0
ファイル: TextureLoader.cs プロジェクト: yvanoff/nitrosharp
        public Texture LoadTexture(Stream stream, bool staging)
        {
            using (stream)
            {
                Texture stagingTex = LoadStaging(stream);
                if (staging)
                {
                    return(stagingTex);
                }

                Texture sampledTex = _rf.CreateTexture(TextureDescription.Texture2D(
                                                           stagingTex.Width, stagingTex.Height, mipLevels: 1, arrayLayers: 1,
                                                           PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled
                                                           ));

                using CommandList cl = _gd.ResourceFactory.CreateCommandList();
                cl.Begin();
                cl.CopyTexture(source: stagingTex, destination: sampledTex);
                cl.End();
                _gd.SubmitCommands(cl);
                // TODO: report the GL backend's quirk upstream
                if (_gd.BackendType == GraphicsBackend.OpenGL)
                {
                    _gd.DisposeWhenIdle(stagingTex);
                }
                else
                {
                    stagingTex.Dispose();
                }
                return(sampledTex);
            }
        }
コード例 #10
0
        internal void SetRenderTarget(RenderTarget renderTarget)
        {
            if (renderTarget != null)
            {
                _commandList.Begin();

                _commandList.SetFramebuffer(renderTarget.Framebuffer);
                _commandList.ClearColorTarget(0, new RgbaFloat(0, 0, 0, 0));

                _clipMaskDrawingContext.Begin(
                    _commandList,
                    _graphicsLoadContext.StandardGraphicsResources.LinearClampSampler,
                    new SizeF(renderTarget.ColorTarget.Width, renderTarget.ColorTarget.Height));

                _activeDrawingContext = _clipMaskDrawingContext;
            }
            else
            {
                _clipMaskDrawingContext.End();

                _commandList.End();

                _contentManager.GraphicsDevice.SubmitCommands(_commandList);

                _activeDrawingContext = _drawingContext;
            }
        }
コード例 #11
0
        private RgbaByte RenderQuad(Veldrid.Shader[] shaders)
        {
            using (var pipeline = ResourceFactory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                             BlendStateDescription.SingleOverrideBlend,
                                                                             DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                             RasterizerStateDescription.CullNone,
                                                                             PrimitiveTopology.TriangleStrip,
                                                                             new ShaderSetDescription(new VertexLayoutDescription[0], shaders),
                                                                             new ResourceLayout[0],
                                                                             Framebuffer.OutputDescription
                                                                             )))
            {
                CommandList.Begin();
                CommandList.SetFramebuffer(Framebuffer);
                CommandList.SetFullViewports();
                CommandList.ClearColorTarget(0, RgbaFloat.Black);
                CommandList.ClearDepthStencil(1);
                CommandList.SetPipeline(pipeline);
                CommandList.Draw(4);
                CommandList.End();

                GraphicsDevice.SubmitCommands(CommandList);
                GraphicsDevice.WaitForIdle();

                var readRenderTargetPixel = ReadRenderTargetPixel();
                return(readRenderTargetPixel);
            }
        }
コード例 #12
0
        /// <summary>
        /// Used the velocity buffer to move the nodes in the positions buffer
        /// </summary>
        /// <param name="RSetDesc">Position shader resource set</param>
        /// <param name="cl">Commandlist to run the commands on</param>
        /// <param name="plot">PlottedGraph to compute</param>
        /// <param name="delta">A float representing how much time has passed since the last frame. Higher values => bigger movements</param>
        private unsafe void RenderPosition(ResourceSetDescription RSetDesc, CommandList cl, PlottedGraph plot, float delta)
        {
            _timer.Restart();
            cl.Begin();

            ResourceSet resourceSet = _gd.ResourceFactory.CreateResourceSet(RSetDesc);
            //Debug.Assert(!VeldridGraphBuffers.DetectNaN(_gd, positions));
            //Debug.Assert(!VeldridGraphBuffers.DetectNaN(_gd, velocities));

            //if (GlobalConfig.Settings.Logs.BulkLogging) Logging.RecordLogEvent($"RenderPosition  {this.EngineID}", Logging.LogFilterType.BulkDebugLogFile);

            PositionShaderParams parameters = new PositionShaderParams
            {
                delta     = delta,
                nodeCount = (uint)plot.RenderedNodeCount()
            };

            //Logging.WriteConsole($"RenderPosition Parambuffer Size is {(uint)Unsafe.SizeOf<PositionShaderParams>()}");

            cl.UpdateBuffer(_positionParamsBuffer, 0, parameters);
            cl.SetPipeline(_positionComputePipeline);
            cl.SetComputeResourceSet(0, resourceSet);
            cl.Dispatch((uint)Math.Ceiling(plot.LayoutState.PositionsVRAM1 !.SizeInBytes / (256.0 * sizeof(Vector4))), 1, 1);
            cl.End();
            _timer.Stop();
            PositionSetupTime = _timer.Elapsed.TotalMilliseconds;

            _timer.Restart();
            _gd !.SubmitCommands(cl);
            _gd !.WaitForIdle();
            _gd.DisposeWhenIdle(resourceSet);
            _timer.Stop();
            PositionTime = _timer.Elapsed.TotalMilliseconds;
        }
コード例 #13
0
        protected override void Draw(float deltaSeconds)
        {
            UpdateAnimation(deltaSeconds);
            UpdateUniforms();
            _cl.Begin();
            _cl.SetFramebuffer(GraphicsDevice.SwapchainFramebuffer);
            _cl.ClearColorTarget(0, RgbaFloat.Black);
            _cl.ClearDepthStencil(1f);

            Matrix4x4 worldMatrix =
                Matrix4x4.CreateTranslation(0, 15000, -5000)
                * Matrix4x4.CreateRotationX(3 * (float)Math.PI / 2)
                * Matrix4x4.CreateScale(0.05f);

            _cl.UpdateBuffer(_worldBuffer, 0, ref worldMatrix);

            DrawMesh();

            worldMatrix =
                Matrix4x4.CreateTranslation(0, 15000, -5000)
                * Matrix4x4.CreateRotationX(3 * (float)Math.PI / 2)
                * Matrix4x4.CreateScale(0.07f);

            _cl.UpdateBuffer(_worldBuffer, 0, ref worldMatrix);
            DrawMesh();

            _cl.End();

            GraphicsDevice.SubmitCommands(_cl);
            GraphicsDevice.SwapBuffers();
        }
コード例 #14
0
        private void _Submit()
        {
            this.CopyTo(_IndexedVertexBuffer);



            _CommandList.Begin();

            _CommandList.SetFramebuffer(_FrameBuffer);

            if (_FillColor.HasValue)
            {
                var color = _FillColor.Value;
                var c     = new RgbaFloat(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f);
                _CommandList.ClearColorTarget(0, c);
            }

            var wvp = Matrix4x4.CreateOrthographicOffCenter(0, _FrameBuffer.Width, _FrameBuffer.Height, 0, 0, 1);

            var effect = _Factory.SpriteEffect;

            effect.Bind(_CommandList, _FrameBuffer.OutputDescription);
            effect.SetWorldMatrix(wvp);

            _IndexedVertexBuffer.Bind(_CommandList);
            foreach (var batch in this.Batches)
            {
                _Factory._SetTexture(_CommandList, batch.TextureId);

                batch.DrawTo(_CommandList, _IndexedVertexBuffer);
            }

            _CommandList.End();
            _Factory.GraphicsDevice.SubmitCommands(_CommandList);
        }
コード例 #15
0
        private static void Draw()
        {
            _commandList.Begin();

            _commandList.SetFramebuffer(_graphicsDevice.SwapchainFramebuffer);

            _commandList.ClearColorTarget(0, RgbaFloat.CornflowerBlue);

            _commandList.SetVertexBuffer(0, _vertexBuffer);
            _commandList.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);

            _commandList.SetPipeline(_pipeline);

            var redValue = Math.Sin((double)_stopWatch.ElapsedMilliseconds / 1000) / 2.0f + 0.5f;

            _shaderResourceManager.UpdateShaderResourceBuffer(_commandList, "MyColorBlock", new MyColorBlock {
                Color = new RgbaFloat((float)redValue, 0f, 0f, 1.0f)
            });

            _commandList.DrawIndexed(indexCount: 4, instanceCount: 1, indexStart: 0, vertexOffset: 0, instanceStart: 0);

            _commandList.End();

            _graphicsDevice.SubmitCommands(_commandList);
            _graphicsDevice.SwapBuffers();
        }
コード例 #16
0
        private void Record(GraphicsDevice device, ResourceFactory factory)
        {
            if (!_initialized)
            {
                Initialize(device, factory);
            }

            // Begin() must be called before commands can be issued.
            _commandList.Begin();

            // We want to render directly to the output window.
            _commandList.SetFramebuffer(Framebuffer);

            // TODO Set from Camera color ?
            _commandList.ClearColorTarget(0, RgbaFloat.Grey);
            _commandList.ClearDepthStencil(1f);

            //
            // Draw Opaque Geometry
            //
            DrawOpaqueRenderGroups(device, factory);

            //
            // Draw Transparent Geometry
            //
            if (_cullVisitor.TransparentRenderGroup.HasDrawableElements())
            {
                DrawTransparentRenderGroups(device, factory);
            }

            _commandList.End();
        }
コード例 #17
0
        public unsafe Texture CreateDeviceTexture(GraphicsDevice gd, ResourceFactory rf, TextureUsage usage)
        {
            using (Texture staging = rf.CreateTexture(new TextureDescription(Width, Height, Depth, MipLevels,
                                                                             ArrayLayers, Format, TextureUsage.Staging, Type)))
            {
                staging.Name = Name + "_Staging";

                fixed(uint *texDataPtr = &TextureData[0])
                {
                    uint subresourceSize = Width * Height * 4;

                    gd.UpdateTexture(
                        staging, (IntPtr)texDataPtr, subresourceSize,
                        0, 0, 0, Width, Height, 1, 0, 0);
                }

                Texture texture = rf.CreateTexture(new TextureDescription(Width, Height, Depth, MipLevels, ArrayLayers, Format, usage, Type));
                texture.Name = Name;
                using (CommandList cl = rf.CreateCommandList())
                {
                    cl.Begin();
                    cl.CopyTexture(staging, texture);
                    cl.End();
                    gd.SubmitCommands(cl);
                }

                IsDirty = false;
                return(texture);
            }
        }
コード例 #18
0
        public void Render(float timeSinceLastDraw)
        {
            ProcessRenderStageUpdates(timeSinceLastDraw);

            _cl.Begin();

            if (_renderCommandQueue.CommandQueueSize == 0)
            {
                ClearWindowWhenNoRenderCommandsQueued(_startUpPropertiesCache.Internal.DefaultWindowClearColourOnNoRenderCommandsQueued);
            }
            else
            {
                ProcessRenderCommandQueue();
            }

            if (_debugOverlay.Visible)
            {
                _debugOverlay.Render(_cl, _systemComponents);
            }

            _cl.End();

            _systemComponents.Device.SubmitCommands(_cl);

            _renderStageVisitor.ClearCachedDrawingModels();

            Task.Run(() =>
            {
                _systemComponents.Device.WaitForIdle();
                _systemComponents.Device.SwapBuffers();
                ExecutePostRenderFunctions();
                RenderingComplete = true;
            });
        }
コード例 #19
0
        private void Update(float deltaSeconds)
        {
            if (!_window.Exists)
            {
                return;
            }

            if (_resized)
            {
                _resized = false;

                WindowOnResized();
            }

            var input = _window.PumpEvents();

            ImGuiRenderer.Update(deltaSeconds, input);

            _commandList.Begin();
            _commandList.SetFramebuffer(_framebuffer);
            _commandList.ClearColorTarget(0, RgbaFloat.Black);

            Draw?.Invoke();

            ImGuiRenderer.Render(_graphicsDevice, _commandList);

            _commandList.End();

            _graphicsDevice.SubmitCommands(_commandList);
            _graphicsDevice.SwapBuffers();
        }
コード例 #20
0
        private void Draw()
        {
            int ticks = Environment.TickCount;

            _cl.Begin();

            _cl.UpdateBuffer(_projectionBuffer, 0, Matrix4x4.CreatePerspectiveFieldOfView(
                                 1.0f,
                                 (float)_window.Width / _window.Height,
                                 0.5f,
                                 100f));

            _cl.UpdateBuffer(_viewBuffer, 0, Matrix4x4.CreateLookAt(Vector3.UnitZ * 2.5f, Vector3.Zero, Vector3.UnitY));

            Matrix4x4 rotation =
                Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, (ticks / 1000f))
                * Matrix4x4.CreateFromAxisAngle(Vector3.UnitX, (ticks / 3000f));

            _cl.UpdateBuffer(_worldBuffer, 0, ref rotation);

            _cl.SetFramebuffer(_gd.SwapchainFramebuffer);
            _cl.SetFullViewports();
            _cl.ClearColorTarget(0, RgbaFloat.Black);
            _cl.ClearDepthTarget(1f);
            _cl.SetPipeline(_pipeline);
            _cl.SetVertexBuffer(0, _vertexBuffer);
            _cl.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);
            _cl.SetGraphicsResourceSet(0, _projViewSet);
            _cl.SetGraphicsResourceSet(1, _worldTextureSet);
            _cl.DrawIndexed(36, 1, 0, 0, 0);

            _cl.End();
            _gd.ExecuteCommands(_cl);
            _gd.SwapBuffers();
        }
コード例 #21
0
ファイル: TestUtils.cs プロジェクト: yvanoff/veldrid
 protected Texture GetReadback(Texture texture)
 {
     if ((texture.Usage & TextureUsage.Staging) != 0)
     {
         return(texture);
     }
     else
     {
         uint layers = texture.ArrayLayers;
         if ((texture.Usage & TextureUsage.Cubemap) != 0)
         {
             layers *= 6;
         }
         TextureDescription desc = new TextureDescription(
             texture.Width, texture.Height, texture.Depth,
             texture.MipLevels, layers,
             texture.Format,
             TextureUsage.Staging, texture.Type);
         Texture     readback = RF.CreateTexture(ref desc);
         CommandList cl       = RF.CreateCommandList();
         cl.Begin();
         cl.CopyTexture(texture, readback);
         cl.End();
         GD.SubmitCommands(cl);
         GD.WaitForIdle();
         return(readback);
     }
 }
コード例 #22
0
        void CreateAllObjects()
        {
            using (PerfTracker.InfrequentEvent("Create objects"))
            {
                _frameCommands      = GraphicsDevice.ResourceFactory.CreateCommandList();
                _frameCommands.Name = "Frame Commands List";

                CommandList initCL = GraphicsDevice.ResourceFactory.CreateCommandList();
                initCL.Name = "Recreation Initialization Command List";
                initCL.Begin();
                _sceneContext.CreateDeviceObjects(GraphicsDevice, initCL);

                foreach (var r in _renderers.Values)
                {
                    r.CreateDeviceObjects(GraphicsDevice, initCL, _sceneContext);
                }

                initCL.End();
                GraphicsDevice.SubmitCommands(initCL);
                GraphicsDevice.WaitForIdle();
                initCL.Dispose();
                GraphicsDevice.WaitForIdle();
                Resolve <IShaderCache>().CleanupOldFiles();
            }
        }
コード例 #23
0
ファイル: BufferTests.cs プロジェクト: uzbekdev1/veldrid
        public void CopyBuffer_Succeeds()
        {
            DeviceBuffer src = CreateBuffer(1024, BufferUsage.Staging);

            int[] data = Enumerable.Range(0, 256).Select(i => 2 * i).ToArray();
            GD.UpdateBuffer(src, 0, data);

            DeviceBuffer dst = CreateBuffer(1024, BufferUsage.Staging);

            CommandList copyCL = RF.CreateCommandList();

            copyCL.Begin();
            copyCL.CopyBuffer(src, 0, dst, 0, src.SizeInBytes);
            copyCL.End();
            GD.SubmitCommands(copyCL);
            GD.WaitForIdle();
            src.Dispose();

            MappedResourceView <int> view = GD.Map <int>(dst, MapMode.Read);

            for (int i = 0; i < view.Count; i++)
            {
                Assert.Equal(i * 2, view[i]);
            }
        }
コード例 #24
0
        private void MainLoop(CancellationToken cancellationToken)
        {
            while (_window.Exists && !cancellationToken.IsCancellationRequested)
            {
                var snapshot = _window.PumpEvents();
                if (!_window.Exists)
                {
                    break;
                }

                _controller.Update(1f / 60f, snapshot); // Feed the input events to our ImGui controller, which passes them through to ImGui.

                Render();

                _cl.Begin();
                _cl.SetFramebuffer(_gd.MainSwapchain.Framebuffer);
                _cl.ClearColorTarget(0, new RgbaFloat(_clearColor.X, _clearColor.Y, _clearColor.Z, 0.0f));
                _controller.Render(_gd, _cl);
                _cl.End();
                _gd.SubmitCommands(_cl);
                _gd.SwapBuffers(_gd.MainSwapchain);
            }

            if (_window.Exists)
            {
                _window.Close();
            }
        }
コード例 #25
0
ファイル: BufferTests.cs プロジェクト: uzbekdev1/veldrid
        public void Copy_UnalignedRegion(
            uint srcBufferSize, BufferUsage srcUsage, uint srcCopyOffset,
            uint dstBufferSize, BufferUsage dstUsage, uint dstCopyOffset,
            uint copySize)
        {
            DeviceBuffer src = CreateBuffer(srcBufferSize, srcUsage);
            DeviceBuffer dst = CreateBuffer(dstBufferSize, dstUsage);

            byte[] data = Enumerable.Range(0, (int)srcBufferSize).Select(i => (byte)i).ToArray();
            GD.UpdateBuffer(src, 0, data);

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.CopyBuffer(src, srcCopyOffset, dst, dstCopyOffset, copySize);
            cl.End();

            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            DeviceBuffer readback = GetReadback(dst);

            MappedResourceView <byte> readView = GD.Map <byte>(readback, MapMode.Read);

            for (uint i = 0; i < copySize; i++)
            {
                byte expected = data[i + srcCopyOffset];
                byte actual   = readView[i + dstCopyOffset];
                Assert.Equal(expected, actual);
            }
            GD.Unmap(readback);
        }
コード例 #26
0
        /// <summary>
        /// Create a node attributes buffer with standard values
        /// </summary>
        /// <param name="bd">BufferDescription</param>
        /// <param name="gd">GraphicsDevice</param>
        /// <param name="name">Buuffer name</param>
        /// <returns>Created attributes buffer</returns>
        public unsafe static DeviceBuffer CreateDefaultAttributesBuffer(BufferDescription bd, GraphicsDevice gd, string name = "")
        {
            DeviceBuffer    buf = TrackedVRAMAlloc(gd, bd.SizeInBytes, bd.Usage, bd.StructureByteStride, name);
            ResourceFactory rf  = gd.ResourceFactory;

            int floatCount = (int)(buf.SizeInBytes / 4);

            float[] output = new float[floatCount];
            float[] item   = new float[4] {
                CONSTANTS.Anim_Constants.DEFAULT_NODE_DIAMETER, 1, 0, 0
            };
            int itemSize = item.Length * sizeof(float);

            for (var i = 0; i < floatCount; i += 4)
            {
                Array.Copy(item, 0, output, i, item.Length);
            }
            CommandList cl = rf.CreateCommandList();

            cl.Begin();
            fixed(float *dataPtr = output)
            {
                cl.UpdateBuffer(buf, 0, (IntPtr)dataPtr, buf.SizeInBytes);
            }

            cl.End();
            gd.SubmitCommands(cl);
            gd.WaitForIdle();
            cl.Dispose();

            return(buf);
        }
コード例 #27
0
 protected override void Render()
 {
     commandList.Begin();
     commandList.SetFramebuffer(GraphicsDevice.MainSwapchain.Framebuffer);
     imGuiRenderer.Render(GraphicsDevice, commandList);
     commandList.End();
 }
コード例 #28
0
        /// <summary>
        /// Get a CPU readable mapping of VRAM
        /// </summary>
        /// <param name="gd">A veldrid graphics device</param>
        /// <param name="buffer">The buffer to read</param>
        /// <returns></returns>
        public static DeviceBuffer GetReadback(GraphicsDevice gd, DeviceBuffer?buffer)
        {
            System.Diagnostics.Debug.Assert(buffer is not null);

            DeviceBuffer readback;

            if ((buffer.Usage & BufferUsage.Staging) != 0)
            {
                readback = buffer;
            }
            else
            {
                ResourceFactory factory = gd.ResourceFactory;
                readback = TrackedVRAMAlloc(gd, buffer.SizeInBytes, BufferUsage.Staging, name: "ReadBack");
                CommandList cl = factory.CreateCommandList();
                cl.Begin();
                cl.CopyBuffer(buffer, 0, readback, 0, buffer.SizeInBytes);
                cl.End();
                gd.SubmitCommands(cl);
                gd.WaitForIdle();
                cl.Dispose();
            }

            return(readback);
        }
コード例 #29
0
        public unsafe void Update_ThenCopySingleMip_Succeeds_R16UNorm()
        {
            TextureDescription desc = TextureDescription.Texture2D(
                1024, 1024, 3, 1, PixelFormat.R16_UNorm, TextureUsage.Staging);
            Texture src = RF.CreateTexture(desc);
            Texture dst = RF.CreateTexture(desc);

            ushort[] data = Enumerable.Range(0, 256 * 256).Select(i => (ushort)i).ToArray();

            fixed(ushort *dataPtr = data)
            {
                GD.UpdateTexture(src, (IntPtr)dataPtr, 256 * 256 * sizeof(ushort), 0, 0, 0, 256, 256, 1, 2, 0);
            }

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.CopyTexture(src, dst, 2, 0);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            MappedResource map            = GD.Map(dst, MapMode.Read, 2);
            ushort *       mappedFloatPtr = (ushort *)map.Data;

            for (int y = 0; y < 256; y++)
            {
                for (int x = 0; x < 256; x++)
                {
                    uint   mapIndex = (uint)(y * (map.RowPitch / sizeof(ushort)) + x);
                    ushort value    = (ushort)(y * 256 + x);
                    Assert.Equal(value, mappedFloatPtr[mapIndex]);
                }
            }
        }
コード例 #30
0
        public void Run()
        {
            Stopwatch s = new Stopwatch();

            s.Start();
            double secs = 0;

            while (Window.Exists)
            {
                InputSnapshot inputSnapshot = Window.PumpEvents();

                if (!Window.Exists)
                {
                    break;
                }

                // ToDo: GameTimer implementieren
                double news = s.Elapsed.TotalSeconds;
                ImGuiRenderer.Update((float)(news - secs), inputSnapshot);
                secs = news;
                UpdateAndDrawGui();

                Cl.Begin();
                Cl.SetFramebuffer(Gd.SwapchainFramebuffer);
                Cl.ClearColorTarget(0, new RgbaFloat(0.45f, 0.55f, 0.6f, 1.0f));

                ImGuiRenderer.Render(Gd, Cl);

                Cl.End();
                Gd.SubmitCommands(Cl);
                Gd.SwapBuffers();
            }
        }