Пример #1
0
		public EncodedRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle, int encoding)
		{
			this.rfb = rfb;
			this.framebuffer = framebuffer;
			this.rectangle = rectangle;

			//Select appropriate reader
			BinaryReader reader = (encoding == RfbProtocol.ZRLE_ENCODING) ? rfb.ZrleReader : rfb.Reader;

			// Create the appropriate PixelReader depending on screen size and encoding
			switch (framebuffer.BitsPerPixel)
			{
				case 32:
					if (encoding == RfbProtocol.ZRLE_ENCODING)
					{
						preader = new CPixelReader(reader, framebuffer);
					}
					else
					{
						preader = new PixelReader32(reader, framebuffer);
					}
					break;
				case 16:
					preader = new PixelReader16(reader, framebuffer);
					break;
				case 8:
					preader = new PixelReader8(reader, framebuffer, rfb);
					break;
				default:
					throw new ArgumentOutOfRangeException("BitsPerPixel", framebuffer.BitsPerPixel, "Valid VNC Pixel Widths are 8, 16 or 32 bits.");
			}
		}
Пример #2
0
 public RenderManager(Renderer renderer, Camera cam, Action userRender)
 {
     RenderManager.renderer = renderer;
     this.userRender = userRender;
     postProcessor = new PostProcessor(this, cam);
     depthFbo = new Framebuffer(cam.Width, cam.Height);
 }
Пример #3
0
        /** Initialises the renderer, creating the internal buffers with the given dimensions. */
        public FramebufferManager(int width, int height, int lowResWidth, int lowResHeight)
        {
            HighLevelRenderer.shaderDrawSprite = Video.loadShader("drawSprite");
            HighLevelRenderer.shaderIndexedBitmapSprite = Video.loadShader("indexedBitmapSprite");

            highResBuffer = new Framebuffer(width, height);
            lowResBuffer = new Framebuffer(lowResWidth, lowResHeight);
        }
        private Framebuffer InitFramebuffer(int texWidth, int texHeight)
        {
            var framebuffer = new Framebuffer();
            framebuffer.Bind();
            Texture texture = this.backface2DTexture;
            framebuffer.Attach(texture);
            Renderbuffer depthBuffer = Renderbuffer.CreateDepthbuffer(texWidth, texHeight, DepthComponentType.DepthComponent);
            framebuffer.Attach(depthBuffer);
            framebuffer.Unbind();

            return framebuffer;
        }
Пример #5
0
		/// <summary>
		/// Construct a RenderBufferState indicating a <see cref="RenderFramebuffer"/> as draw binding.
		/// </summary>
		public RenderBufferState(Framebuffer framebuffer)
		{
			if (framebuffer == null)
				throw new ArgumentNullException("framebuffer");
			
			mDrawBuffers = new int[GraphicsContext.CurrentCaps.Limits.MaxColorAttachments];
			mDrawBuffers[0] = Gl.COLOR_ATTACHMENT0;
			for (int i = 1; i < mDrawBuffers.Length; i++)
				mDrawBuffers[i] = Gl.NONE;
			
			mDrawFramebuffer = framebuffer;
			mDrawFramebuffer.IncRef();
		}
Пример #6
0
        private TextureFilter(GLProgram program)
        {
            _program = program;
            _uniforms = new TextureUniforms (_program, new Sampler2D (0).LinearFiltering ()
                .ClampToEdges (Axes.X | Axes.Y));

            _framebuffer = new Framebuffer (FramebufferTarget.Framebuffer);

            var rectangle = Quadrilateral<TexturedVertex>.Rectangle (2f, 2f);
            rectangle.ApplyTextureFront (1f, new Vec2 (0f), new Vec2 (1f));
            _vertexBuffer = new VBO<TexturedVertex> (rectangle.Vertices, BufferTarget.ArrayBuffer);
            _indexBuffer = new VBO<int> (rectangle.Indices, BufferTarget.ElementArrayBuffer);
        }
Пример #7
0
		public new void FixtureSetUp()
		{
			try {
				// Required to be current
				_Context.MakeCurrent(true);

				// Create window on which tests are run
				_Framebuffer = new Framebuffer();
				_Framebuffer.AttachColor(new RenderBuffer(RenderBuffer.Type.Color, PixelLayout.GRAY8, 16, 16));
				_Framebuffer.Create(_Context);
			} catch {
				// Release resources manually
				FixtureTearDown();
				throw;
			}
		}
Пример #8
0
		public EncodedRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle)
		{
			this.rfb = rfb;
			this.framebuffer = framebuffer;
			this.rectangle = rectangle;

			// Create the appropriate PixelReader depending on screen size
			switch (framebuffer.BitsPerPixel) {
				case 32:
					preader = new PixelReader32(rfb, framebuffer);
					break;
				case 16:
					preader = new PixelReader16(rfb, framebuffer);
					break;
				case 8:
					preader = new PixelReader8(rfb, framebuffer);
					break;
				default:
					throw new ArgumentOutOfRangeException("BitsPerPixel", framebuffer.BitsPerPixel, "Valid VNC Pixel Widths are 8, 16, or 32 bits.");
			}
		}
Пример #9
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // configurate opengl
            var openglInit = new InitializeOpenGl();
            openglInit.Execute();

            // preform a load and init of all the scene's and components
            //ServiceLocator.Current.GetAllInstances<FrameworkElement>().ToArray();

            _presenterWindow = ServiceLocator.Current.GetInstance<PresenterWindow>();

            var refreshRate = DisplayDevice.Default.RefreshRate;

            Timeline.DesiredFrameRateProperty.OverrideMetadata(
                typeof(Timeline),
                new FrameworkPropertyMetadata { DefaultValue = Convert.ToInt32(refreshRate) }
                );

            _framebuffer = new Framebuffer(Configuration.InternalResolution.Width,
                                           Configuration.InternalResolution.Height) {Name = "Framebuffer"};

            // by default the presenter window stands in WPF rendering mode.
            // this meens there is a layout root (canvas) that has the aspect correction
            // render transform applied to it and contains a transition presenter.
            // The WPF engine takes care of framebuffers and all the interal stuff.
            // In the opengl rendering we need to manage this.

            // first we clean the transition presenter from the rendering queue
            // The transition presenter is passed as a seperate instance toafter we've pushed
            // the rendering framebuffer.
            _presenterWindow.LayoutRoot.Children.Clear();

            // we replace the transition presenter with the framebuffer object
            _presenterWindow.LayoutRoot.Children.Add(_framebuffer);
        }
        protected override void DoInitialize()
        {
            base.DoInitialize();

            {
                var texture = new Texture(TextureTarget.Texture2D,
                    new NullImageFiller(TEXTURE_SIZE, TEXTURE_SIZE, OpenGL.GL_RGB, OpenGL.GL_RGB, OpenGL.GL_UNSIGNED_BYTE),
                    new SamplerParameters(
                        TextureWrapping.Repeat,
                        TextureWrapping.Repeat,
                        TextureWrapping.Repeat,
                        TextureFilter.Linear,
                        TextureFilter.Linear));
                texture.ActiveTextureIndex = 1;
                texture.Initialize();
                this.mirrorTexture = texture;
            }
            {
                Renderbuffer depthBuffer = Renderbuffer.CreateDepthbuffer(TEXTURE_SIZE, TEXTURE_SIZE, DepthComponentType.DepthComponent);
                var framebuffer = new Framebuffer();
                framebuffer.Bind();
                framebuffer.Attach(this.mirrorTexture);
                framebuffer.Attach(depthBuffer);
                framebuffer.CheckCompleteness();
                this.framebuffer = framebuffer;
            }

            {
                mat4 view = glm.lookAt(new vec3(0.0f, 0.0f, 5.0f), new vec3(0.0f, 0.0f, 0.0f), new vec3(0.0f, 1.0f, 0.0f));
                this.SetUniform("u_modelViewMatrix", view);
                mat4 projection = glm.ortho(-(float)TEXTURE_SIZE / 2, (float)TEXTURE_SIZE / 2, -(float)TEXTURE_SIZE / 2, (float)TEXTURE_SIZE / 2, 1.0f, 100.0f);
                this.SetUniform("u_projectionMatrix", projection);
                this.SetUniform("u_waterPlaneLength", (float)this.waterPlaneLength);
            }

            this.viewportState = new ViewportState(0, 0, TEXTURE_SIZE, TEXTURE_SIZE);
        }
Пример #11
0
 public CoRreRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle) : base(rfb, framebuffer, rectangle, RfbProtocol.CORRE_ENCODING)
 {
 }
        public void SetFramebuffer(Framebuffer fb)
        {
            NoAllocSetFramebufferEntry entry = new NoAllocSetFramebufferEntry(Track(fb));

            AddEntry(SetFramebufferEntryID, ref entry);
        }
Пример #13
0
 public NoAllocSetFramebufferEntry(Framebuffer fb)
 {
     Framebuffer = new HandleTracked <Framebuffer>(fb);
 }
Пример #14
0
 public RasterizerV1(ref Framebuffer framebuffer)
 {
     _framebuffer = framebuffer;
 }
Пример #15
0
 public CPixelReader(BinaryReader reader, Framebuffer framebuffer) : base(reader, framebuffer)
 {
 }
Пример #16
0
		public PixelReader16(RfbProtocol rfb, Framebuffer framebuffer) : base(rfb, framebuffer)
		{
		}
Пример #17
0
 public CopyRectRectangle(VncHost rfb, Framebuffer framebuffer, Rectangle2 rectangle)
     : base(rfb, framebuffer, rectangle)
 {
 }
Пример #18
0
        public Presenter(Context glContext)
        {
            this.glContext = glContext;
            glPipeline = glContext.Pipeline;

            sourceFramebuffer = new Framebuffer(glContext);
            destinationFramebuffer = new Framebuffer(glContext);

            vertices = new Buffer(glContext, BufferTarget.ArrayBuffer, 4 * 8 * sizeof(float), BufferUsageHint.StaticDraw, new Data(new[]
            {
                new Vertex(-1f, -1f),
                new Vertex(-1f, 1f),
                new Vertex(1f, 1f),
                new Vertex(1f, -1f)
            }));

            indices = new Buffer(glContext, BufferTarget.ElementArrayBuffer, 6 * sizeof(ushort), BufferUsageHint.StaticDraw, new Data(new ushort[]
            {
                0, 1, 2, 0, 2, 3
            }));

            sampler = new Sampler();
            sampler.SetMagFilter(TextureMagFilter.Nearest);
            sampler.SetMinFilter(TextureMinFilter.Nearest);

            string shaderErrors;
            if (!VertexShader.TryCompile(VertexShaderText, out vertexShader, out shaderErrors) ||
                !FragmentShader.TryCompile(FragmentShaderText, out fragmentShader, out shaderErrors) ||
                !ShaderProgram.TryLink(glContext, new ShaderProgramDescription
                    {
                        VertexShaders = vertexShader,
                        FragmentShaders = fragmentShader,
                        VertexAttributeNames = new[] { "in_position" },
                        SamplerNames = new[] { "Image" }
                    },
                    out program, out shaderErrors))
                throw new ArgumentException("Program errors:\n\n" + shaderErrors);

            vertexArray = new VertexArray(glContext);
            vertexArray.SetElementArrayBuffer(glContext, indices);
            vertexArray.SetVertexAttributeF(glContext, 0, vertices, VertexAttributeDimension.Two, VertexAttribPointerType.Float, false, 8, 0);
        }
Пример #19
0
        /// <summary>
        /// Converts an array of pixels represented as integers into a byte array of pixel data.
        /// </summary>
        /// <param name="pixels">The pixel array represented as integers.</param>
        /// <param name="rectangle">A sub-rectangle of the pixels which we should extract</param>
        /// <param name="fb">The Framebuffer that should be used.</param>
        /// <returns></returns>
        public static byte[] GrabPixels(int[] pixels, Rectangle rectangle, Framebuffer fb)
        {
            // Encode as bytes
            int x = rectangle.X;
            int y = rectangle.Y;
            int w = rectangle.Width;
            int h = rectangle.Height;

            byte[] bytes = null;

            int b = 0;
            int i = 0;
            int s = 0;
            int pixel;
            int size     = w * h;
            int scanline = w;
            int offsetX  = x;
            int offsetY  = y;
            int jump     = scanline - w;
            int p        = (y - offsetY) * w + x - offsetX;

            switch (fb.BitsPerPixel)
            {
            case 32:
                bytes = new byte[size << 2];
                for (; i < size; i++, s++, p++)
                {
                    if (s == w)
                    {
                        s  = 0;
                        p += jump;
                    }
                    int tmp = pixels[p];
                    pixel = fb.TranslatePixel(tmp);
                    //pixel = pixels[p];

                    bytes[b++] = (byte)(pixel & 0xFF);         //B
                    bytes[b++] = (byte)((pixel >> 8) & 0xFF);  //G
                    bytes[b++] = (byte)((pixel >> 16) & 0xFF); //R
                    bytes[b++] = (byte)((pixel >> 24) & 0xFF); //A
                }
                break;

            case 24:
                bytes = new byte[size << 2];
                for (; i < size; i++, s++, p++)
                {
                    if (s == w)
                    {
                        s  = 0;
                        p += jump;
                    }
                    pixel      = fb.TranslatePixel(pixels[p]);
                    bytes[b++] = (byte)(pixel & 0xFF);         //B
                    bytes[b++] = (byte)((pixel >> 8) & 0xFF);  //G
                    bytes[b++] = (byte)((pixel >> 16) & 0xFF); //R
                }
                break;

            case 16:
                bytes = new byte[size << 1];
                for (; i < size; i++, s++, p++)
                {
                    if (s == w)
                    {
                        s  = 0;
                        p += jump;
                    }
                    pixel      = fb.TranslatePixel(pixels[p]);
                    bytes[b++] = (byte)(pixel & 0xFF);        //B
                    bytes[b++] = (byte)((pixel >> 8) & 0xFF); //G
                }
                break;

            case 8:
                bytes = new byte[size];
                for (; i < size; i++, s++, p++)
                {
                    if (s == w)
                    {
                        s  = 0;
                        p += jump;
                    }
                    bytes[i] = (byte)fb.TranslatePixel(pixels[p]);     //B
                }
                break;
            }
            return(bytes);
        }
Пример #20
0
        protected override void CreateResources(ResourceFactory factory)
        {
            _vertexLayout = new VertexLayoutDescription(
                new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                new VertexElementDescription("UV", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3));

            using (Stream planeModelStream = OpenEmbeddedAssetStream("plane2.dae"))
            {
                _planeModel = new Model(
                    GraphicsDevice,
                    factory,
                    planeModelStream,
                    "dae",
                    new[] { VertexElementSemantic.Position, VertexElementSemantic.TextureCoordinate, VertexElementSemantic.Color, VertexElementSemantic.Normal },
                    new Model.ModelCreateInfo(new Vector3(0.5f, 0.5f, 0.5f), Vector2.One, Vector3.Zero));
            }

            using (Stream dragonModelStream = OpenEmbeddedAssetStream("chinesedragon.dae"))
            {
                _dragonModel = new Model(
                    GraphicsDevice,
                    factory,
                    dragonModelStream,
                    "dae",
                    new[] { VertexElementSemantic.Position, VertexElementSemantic.TextureCoordinate, VertexElementSemantic.Color, VertexElementSemantic.Normal },
                    new Model.ModelCreateInfo(new Vector3(0.3f, -0.3f, 0.3f), Vector2.One, Vector3.Zero));
            }

            using (Stream colorMapStream = OpenEmbeddedAssetStream("darkmetal_bc3_unorm.ktx"))
            {
                _colorMap = KtxFile.LoadTexture(
                    GraphicsDevice,
                    factory,
                    colorMapStream,
                    PixelFormat.BC3_UNorm);
            }
            _colorView = factory.CreateTextureView(_colorMap);

            _offscreenColor = factory.CreateTexture(TextureDescription.Texture2D(
                                                        OffscreenWidth, OffscreenHeight, 1, 1,
                                                        PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.RenderTarget | TextureUsage.Sampled));
            _offscreenView = factory.CreateTextureView(_offscreenColor);
            Texture offscreenDepth = factory.CreateTexture(TextureDescription.Texture2D(
                                                               OffscreenWidth, OffscreenHeight, 1, 1, PixelFormat.R16_UNorm, TextureUsage.DepthStencil));

            _offscreenFB = factory.CreateFramebuffer(new FramebufferDescription(offscreenDepth, _offscreenColor));

            ShaderSetDescription phongShaders = new ShaderSetDescription(
                new[] { _vertexLayout },
                factory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, ReadEmbeddedAssetBytes("Phong-vertex.glsl"), "main"),
                    new ShaderDescription(ShaderStages.Fragment, ReadEmbeddedAssetBytes("Phong-fragment.glsl"), "main")));

            ResourceLayout phongLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                          new ResourceLayoutElementDescription("UBO", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            GraphicsPipelineDescription pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.DepthOnlyLessEqual,
                new RasterizerStateDescription(FaceCullMode.Front, PolygonFillMode.Solid, FrontFace.Clockwise, true, false),
                PrimitiveTopology.TriangleList,
                phongShaders,
                phongLayout,
                _offscreenFB.OutputDescription);

            _offscreenPipeline = factory.CreateGraphicsPipeline(pd);

            pd.Outputs         = GraphicsDevice.SwapchainFramebuffer.OutputDescription;
            pd.RasterizerState = RasterizerStateDescription.Default;
            _dragonPipeline    = factory.CreateGraphicsPipeline(pd);

            ResourceLayout mirrorLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                           new ResourceLayoutElementDescription("UBO", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                           new ResourceLayoutElementDescription("ReflectionMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                           new ResourceLayoutElementDescription("ReflectionMapSampler", ResourceKind.Sampler, ShaderStages.Fragment),
                                                                           new ResourceLayoutElementDescription("ColorMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                           new ResourceLayoutElementDescription("ColorMapSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            ShaderSetDescription mirrorShaders = new ShaderSetDescription(
                new[] { _vertexLayout },
                factory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, ReadEmbeddedAssetBytes("Mirror-vertex.glsl"), "main"),
                    new ShaderDescription(ShaderStages.Fragment, ReadEmbeddedAssetBytes("Mirror-fragment.glsl"), "main")));

            GraphicsPipelineDescription mirrorPD = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.DepthOnlyLessEqual,
                new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Solid, FrontFace.Clockwise, true, false),
                PrimitiveTopology.TriangleList,
                mirrorShaders,
                mirrorLayout,
                GraphicsDevice.SwapchainFramebuffer.OutputDescription);

            _mirrorPipeline = factory.CreateGraphicsPipeline(ref mirrorPD);

            _uniformBuffers_vsShared    = factory.CreateBuffer(new BufferDescription(208, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _uniformBuffers_vsMirror    = factory.CreateBuffer(new BufferDescription(208, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            _uniformBuffers_vsOffScreen = factory.CreateBuffer(new BufferDescription(208, BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            _offscreenResourceSet = factory.CreateResourceSet(new ResourceSetDescription(phongLayout, _uniformBuffers_vsOffScreen));
            _dragonResourceSet    = factory.CreateResourceSet(new ResourceSetDescription(phongLayout, _uniformBuffers_vsShared));
            _mirrorResourceSet    = factory.CreateResourceSet(new ResourceSetDescription(mirrorLayout,
                                                                                         _uniformBuffers_vsMirror,
                                                                                         _offscreenView,
                                                                                         GraphicsDevice.LinearSampler,
                                                                                         _colorView,
                                                                                         GraphicsDevice.Aniso4xSampler));

            _cl = factory.CreateCommandList();
        }
Пример #21
0
 protected PixelReader(BinaryReader reader, Framebuffer framebuffer)
 {
     this.reader      = reader;
     this.framebuffer = framebuffer;
 }
Пример #22
0
 public abstract void RenderMirrorTexture(CommandList cl, Framebuffer fb, MirrorTextureEyeSource source);
Пример #23
0
 private static void WindowOnResized()
 {
     _graphicsDevice.MainSwapchain.Resize((uint)Width, (uint)Height);
     _framebuffer = _graphicsDevice.SwapchainFramebuffer;
     ImGuiRenderer.WindowResized(Width, Height);
 }
 public static void Init()
 {
     Filter = new Framebuffer(FramebufferTarget.Framebuffer,
                              640, 720, PixelInternalFormat.Rgba16f, 1);
 }
Пример #25
0
        public void Points_WithUShortColor()
        {
            Texture target = RF.CreateTexture(TextureDescription.Texture2D(
                                                  50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.RenderTarget));
            Texture staging = RF.CreateTexture(TextureDescription.Texture2D(
                                                   50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Staging));

            Framebuffer framebuffer = RF.CreateFramebuffer(new FramebufferDescription(null, target));

            DeviceBuffer infoBuffer  = RF.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            DeviceBuffer orthoBuffer = RF.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            Matrix4x4    orthoMatrix = Matrix4x4.CreateOrthographicOffCenter(
                0,
                framebuffer.Width,
                framebuffer.Height,
                0,
                -1,
                1);

            GD.UpdateBuffer(orthoBuffer, 0, ref orthoMatrix);

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2),
                    new VertexElementDescription("Color_UInt", VertexElementSemantic.Color, VertexElementFormat.UShort4))
            },
                new Shader[]
            {
                TestShaders.Load(RF, "U16VertexAttribs", ShaderStages.Vertex, "VS"),
                TestShaders.Load(RF, "U16VertexAttribs", ShaderStages.Fragment, "FS")
            });

            ResourceLayout layout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                new ResourceLayoutElementDescription("InfoBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                new ResourceLayoutElementDescription("Ortho", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceSet set = RF.CreateResourceSet(new ResourceSetDescription(layout, infoBuffer, orthoBuffer));

            GraphicsPipelineDescription gpd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                shaderSet,
                layout,
                framebuffer.OutputDescription);

            Pipeline pipeline = RF.CreateGraphicsPipeline(ref gpd);

            uint colorNormalizationFactor = 2500;

            VertexCPU_UShort[] vertices = new VertexCPU_UShort[]
            {
                new VertexCPU_UShort
                {
                    Position = new Vector2(0.5f, 0.5f),
                    R        = (ushort)(0.25f * colorNormalizationFactor),
                    G        = (ushort)(0.5f * colorNormalizationFactor),
                    B        = (ushort)(0.75f * colorNormalizationFactor),
                },
                new VertexCPU_UShort
                {
                    Position = new Vector2(10.5f, 12.5f),
                    R        = (ushort)(0.25f * colorNormalizationFactor),
                    G        = (ushort)(0.5f * colorNormalizationFactor),
                    B        = (ushort)(0.75f * colorNormalizationFactor),
                },
                new VertexCPU_UShort
                {
                    Position = new Vector2(25.5f, 35.5f),
                    R        = (ushort)(0.75f * colorNormalizationFactor),
                    G        = (ushort)(0.5f * colorNormalizationFactor),
                    B        = (ushort)(0.25f * colorNormalizationFactor),
                },
                new VertexCPU_UShort
                {
                    Position = new Vector2(49.5f, 49.5f),
                    R        = (ushort)(0.15f * colorNormalizationFactor),
                    G        = (ushort)(0.2f * colorNormalizationFactor),
                    B        = (ushort)(0.35f * colorNormalizationFactor),
                },
            };

            DeviceBuffer vb = RF.CreateBuffer(
                new BufferDescription((uint)(Unsafe.SizeOf <UIntVertexAttribs.Vertex>() * vertices.Length), BufferUsage.VertexBuffer));

            GD.UpdateBuffer(vb, 0, vertices);
            GD.UpdateBuffer(infoBuffer, 0, new UIntVertexAttribs.Info {
                ColorNormalizationFactor = colorNormalizationFactor
            });

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.SetFramebuffer(framebuffer);
            cl.SetFullViewports();
            cl.SetFullScissorRects();
            cl.ClearColorTarget(0, RgbaFloat.Black);
            cl.SetPipeline(pipeline);
            cl.SetVertexBuffer(0, vb);
            cl.SetGraphicsResourceSet(0, set);
            cl.Draw((uint)vertices.Length);
            cl.SetFramebuffer(GD.SwapchainFramebuffer);
            cl.ClearColorTarget(0, RgbaFloat.Red);
            cl.CopyTexture(target, staging);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            MappedResourceView <RgbaFloat> readView = GD.Map <RgbaFloat>(staging, MapMode.Read);

            foreach (VertexCPU_UShort vertex in vertices)
            {
                uint x = (uint)vertex.Position.X;
                uint y = (uint)vertex.Position.Y;
                if (GD.BackendType == GraphicsBackend.OpenGL)
                {
                    y = framebuffer.Height - y - 1;
                }

                RgbaFloat expectedColor = new RgbaFloat(
                    vertex.R / (float)colorNormalizationFactor,
                    vertex.G / (float)colorNormalizationFactor,
                    vertex.B / (float)colorNormalizationFactor,
                    1);
                Assert.Equal(expectedColor, readView[x, y], RgbaFloatFuzzyComparer.Instance);
            }
            GD.Unmap(staging);
        }
Пример #26
0
        public SolarSystemScene(GameWindow gw, PlanetParameters planetParams, ContentManager contentManager)
        {
            this.contentManager = contentManager;
            this.hoursPerSecond = 1;
            this.defaultShader  = contentManager.GetShader("default");
            this.sunShader      = contentManager.GetShader("sunShader");
            this.lineShader     = contentManager.GetShader("lineShader");
            this.earthShader    = contentManager.GetShader("earth");

            this.buffer = new Framebuffer(gw.Width, gw.Height);
            buffer.AttachColorBuffer(internalFormat: PixelInternalFormat.Rgba16f, type: PixelType.Float);
            buffer.AttachColorBuffer(internalFormat: PixelInternalFormat.Rgba16f, type: PixelType.Float);
            buffer.AttachDepthStencilBuffer();

            blur = new GaussianBlur((int)gw.Size.Width / 1, (int)gw.Size.Height / 1);

            frame = FrameRenderer.Instance;

            finalShader            = contentManager.LoadShader("final");
            finalShader.Initialize = () =>
            {
                finalShader.Bind();
                finalShader.SetUniform("frame", 0);
                finalShader.SetUniform("bloom", 1);
            };
            finalShader.Init();

            cam            = new Camera(60);
            cam.MaxDepth   = 600;
            cam.LightPos   = new Vector3(0, 0, 0);
            cam.Projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(70), gw.Width / (float)gw.Height, .1f, 100000f);

            this.loadContent(planetParams, contentManager);

            cam.SetFocus(earth);

            #region Gui
            guiManager = new GuiManager(gw);
            panel      = new Panel()
            {
                Size            = new System.Drawing.Size(200, gw.Height),
                BackgroundColor = new Vector4(36f / 255, 36f / 255, 36f / 255, 1),
                BorderColor     = new Vector4(1, 1, 1, 1),
                Location        = new System.Drawing.Point(-201, 0),
            };

            var titleLabel = new Label()
            {
                Size      = new System.Drawing.Size(200, 50),
                Location  = new System.Drawing.Point(0, 10),
                Font      = new System.Drawing.Font("Arial", 20, System.Drawing.FontStyle.Underline),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Options"
            };

            int y     = 70;
            var label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Axial Tilt"
            };
            var @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y), On = true
            };
            @switch.OnToggle += (o, e) =>
            {
                this.setAxialTiltDraw(((Switch)o).On);
            };
            panel.Controls.Add(titleLabel, label, @switch);

            y    += 30;
            label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Orbits"
            };
            @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y), On = true
            };
            @switch.OnToggle += (o, e) =>
            {
                this.setOrbitDraw(((Switch)o).On);
            };
            panel.Controls.Add(label, @switch);

            y    += 30;
            label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Bloom Buffer"
            };
            @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y)
            };
            @switch.OnToggle += (o, e) =>
            {
                this.showBloomBuffer = ((Switch)o).On;
            };
            panel.Controls.Add(label, @switch);

            y    += 30;
            label = new Label()
            {
                Size      = new System.Drawing.Size(120, 25),
                Location  = new System.Drawing.Point(10, y),
                TextColor = new Vector4(1, 1, 1, 1),
                Text      = "Bloom"
            };
            @switch = new Switch()
            {
                Location = new System.Drawing.Point(130, y), On = true
            };
            @switch.OnToggle += (o, e) =>
            {
                this.bloom = ((Switch)o).On;
            };
            panel.Controls.Add(label, @switch);

            guiManager.Controls.Add(panel);
            #endregion
        }
Пример #27
0
		public PixelReader8(BinaryReader reader, Framebuffer framebuffer, RfbProtocol rfb) : base(reader, framebuffer)
		{
			this.rfb = rfb;
		}
Пример #28
0
        public unsafe void Points_WithTexture_UpdateUnrelated(bool useTextureView)
        {
            // This is a regression test for the case where a user modifies an unrelated texture
            // at a time after a ResourceSet containing a texture has been bound. The OpenGL
            // backend was caching texture state improperly, resulting in wrong textures being sampled.

            Texture target = RF.CreateTexture(TextureDescription.Texture2D(
                                                  50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.RenderTarget));
            Texture staging = RF.CreateTexture(TextureDescription.Texture2D(
                                                   50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Staging));

            Framebuffer framebuffer = RF.CreateFramebuffer(new FramebufferDescription(null, target));

            DeviceBuffer orthoBuffer = RF.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            Matrix4x4    orthoMatrix = Matrix4x4.CreateOrthographicOffCenter(
                0,
                framebuffer.Width,
                framebuffer.Height,
                0,
                -1,
                1);

            GD.UpdateBuffer(orthoBuffer, 0, ref orthoMatrix);

            Texture sampledTexture = RF.CreateTexture(
                TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Sampled));

            RgbaFloat white = RgbaFloat.White;

            GD.UpdateTexture(sampledTexture, (IntPtr)(&white), (uint)Unsafe.SizeOf <RgbaFloat>(), 0, 0, 0, 1, 1, 1, 0, 0);

            Texture shouldntBeSampledTexture = RF.CreateTexture(
                TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Sampled));

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                TestShaders.LoadVertexFragment(RF, "TexturedPoints"));

            ResourceLayout layout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                new ResourceLayoutElementDescription("Ortho", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                new ResourceLayoutElementDescription("Smp", ResourceKind.Sampler, ShaderStages.Fragment)));

            ResourceSet set;

            if (useTextureView)
            {
                TextureView view = RF.CreateTextureView(sampledTexture);
                set = RF.CreateResourceSet(new ResourceSetDescription(layout, orthoBuffer, view, GD.PointSampler));
            }
            else
            {
                set = RF.CreateResourceSet(new ResourceSetDescription(layout, orthoBuffer, sampledTexture, GD.PointSampler));
            }

            GraphicsPipelineDescription gpd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                shaderSet,
                layout,
                framebuffer.OutputDescription);

            Pipeline pipeline = RF.CreateGraphicsPipeline(ref gpd);

            Vector2[] vertices = new Vector2[]
            {
                new Vector2(0.5f, 0.5f),
                new Vector2(15.5f, 15.5f),
                new Vector2(25.5f, 26.5f),
                new Vector2(3.5f, 25.5f),
            };

            DeviceBuffer vb = RF.CreateBuffer(
                new BufferDescription((uint)(Unsafe.SizeOf <Vector2>() * vertices.Length), BufferUsage.VertexBuffer));

            GD.UpdateBuffer(vb, 0, vertices);

            CommandList cl = RF.CreateCommandList();

            for (int i = 0; i < 2; i++)
            {
                cl.Begin();
                cl.SetFramebuffer(framebuffer);
                cl.ClearColorTarget(0, RgbaFloat.Black);
                cl.SetPipeline(pipeline);
                cl.SetVertexBuffer(0, vb);
                cl.SetGraphicsResourceSet(0, set);

                // Modify an unrelated texture.
                // This must have no observable effect on the next draw call.
                RgbaFloat pink = RgbaFloat.Pink;
                GD.UpdateTexture(shouldntBeSampledTexture,
                                 (IntPtr)(&pink), (uint)Unsafe.SizeOf <RgbaFloat>(),
                                 0, 0, 0,
                                 1, 1, 1,
                                 0, 0);

                cl.Draw((uint)vertices.Length);
                cl.End();
                GD.SubmitCommands(cl);
                GD.WaitForIdle();
            }

            cl.Begin();
            cl.CopyTexture(target, staging);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            MappedResourceView <RgbaFloat> readView = GD.Map <RgbaFloat>(staging, MapMode.Read);

            foreach (Vector2 vertex in vertices)
            {
                uint x = (uint)vertex.X;
                uint y = (uint)vertex.Y;
                if (!GD.IsUvOriginTopLeft || GD.IsClipSpaceYInverted)
                {
                    y = framebuffer.Height - y - 1;
                }

                Assert.Equal(white, readView[x, y], RgbaFloatFuzzyComparer.Instance);
            }
            GD.Unmap(staging);
        }
Пример #29
0
		public RawRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle) : base(rfb, framebuffer, rectangle)
		{
		}
Пример #30
0
 public OrthogonalCamera(Framebuffer renderTarget, Vector3 position, Vector3 direction, Vector3 up) : base(renderTarget,
                                                                                                           position, direction, up)
 {
 }
Пример #31
0
 public void Init()
 {
     fbo = new Framebuffer(shadowMapWidth, shadowMapHeight);
     s_cam = new OrthoCamera(-5, 5, -5, 5, -5, 5);
     fbo.Init();
     s_cam.Far = splitDist;
 }
Пример #32
0
        public void CmdDraw()
        {
            var renderPassCreateInfo = new RenderPassCreateInfo(
                new[] { new SubpassDescription(new[] { new AttachmentReference(0, ImageLayout.ColorAttachmentOptimal) }) },
                new[]
            {
                new AttachmentDescription
                {
                    Format      = Format.B8G8R8A8UNorm,
                    Samples     = SampleCounts.Count1,
                    FinalLayout = ImageLayout.ColorAttachmentOptimal,
                    LoadOp      = AttachmentLoadOp.DontCare
                }
            });
            var imageCreateInfo = new ImageCreateInfo
            {
                Usage       = ImageUsages.ColorAttachment,
                Format      = Format.B8G8R8A8UNorm,
                Extent      = new Extent3D(2, 2, 1),
                ImageType   = ImageType.Image2D,
                MipLevels   = 1,
                ArrayLayers = 1,
                Samples     = SampleCounts.Count1
            };
            var imageViewCreateInfo = new ImageViewCreateInfo(
                Format.B8G8R8A8UNorm,
                new ImageSubresourceRange(ImageAspects.Color, 0, 1, 0, 1));

            using (ShaderModule vertexShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.vert.spv"))))
                using (ShaderModule fragmentShader = Device.CreateShaderModule(new ShaderModuleCreateInfo(ReadAllBytes("Shader.frag.spv"))))
                    using (PipelineLayout pipelineLayout = Device.CreatePipelineLayout())
                        using (RenderPass renderPass = Device.CreateRenderPass(renderPassCreateInfo))
                            using (Image image = Device.CreateImage(imageCreateInfo))
                            {
                                MemoryRequirements imageMemReq = image.GetMemoryRequirements();
                                int memTypeIndex = PhysicalDeviceMemoryProperties.MemoryTypes.IndexOf(imageMemReq.MemoryTypeBits, MemoryProperties.DeviceLocal);
                                using (DeviceMemory imageMemory = Device.AllocateMemory(new MemoryAllocateInfo(imageMemReq.Size, memTypeIndex)))
                                {
                                    image.BindMemory(imageMemory);
                                    using (ImageView imageView = image.CreateView(imageViewCreateInfo))
                                        using (Framebuffer framebuffer = renderPass.CreateFramebuffer(new FramebufferCreateInfo(new[] { imageView }, 2, 2)))
                                            using (Pipeline pipeline = Device.CreateGraphicsPipeline(new GraphicsPipelineCreateInfo(
                                                                                                         pipelineLayout,
                                                                                                         renderPass,
                                                                                                         0,
                                                                                                         new[]
                                            {
                                                new PipelineShaderStageCreateInfo(ShaderStages.Vertex, vertexShader, "main"),
                                                new PipelineShaderStageCreateInfo(ShaderStages.Fragment, fragmentShader, "main")
                                            },
                                                                                                         new PipelineInputAssemblyStateCreateInfo(),
                                                                                                         new PipelineVertexInputStateCreateInfo(),
                                                                                                         new PipelineRasterizationStateCreateInfo {
                                                RasterizerDiscardEnable = true, LineWidth = 1.0f
                                            })))
                                            {
                                                CommandBuffer.Begin();
                                                CommandBuffer.CmdBeginRenderPass(new RenderPassBeginInfo(framebuffer, new Rect2D(0, 0, 2, 2)));
                                                CommandBuffer.CmdBindPipeline(PipelineBindPoint.Graphics, pipeline);
                                                CommandBuffer.CmdDraw(3);
                                                CommandBuffer.CmdEndRenderPass();
                                                CommandBuffer.End();
                                            }
                                }
                            }
        }
Пример #33
0
        public void ComputeGeneratedVertices()
        {
            if (!GD.Features.ComputeShader)
            {
                return;
            }

            uint    width  = 512;
            uint    height = 512;
            Texture output = RF.CreateTexture(
                TextureDescription.Texture2D(width, height, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.RenderTarget));
            Framebuffer framebuffer = RF.CreateFramebuffer(new FramebufferDescription(null, output));

            uint         vertexSize = (uint)Unsafe.SizeOf <ColoredVertex>();
            DeviceBuffer buffer     = RF.CreateBuffer(new BufferDescription(
                                                          vertexSize * 4,
                                                          BufferUsage.StructuredBufferReadWrite,
                                                          vertexSize,
                                                          true));

            ResourceLayout computeLayout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                       new ResourceLayoutElementDescription("OutputVertices", ResourceKind.StructuredBufferReadWrite, ShaderStages.Compute)));
            ResourceSet computeSet = RF.CreateResourceSet(new ResourceSetDescription(computeLayout, buffer));

            Pipeline computePipeline = RF.CreateComputePipeline(new ComputePipelineDescription(
                                                                    TestShaders.LoadCompute(RF, "ComputeColoredQuadGenerator"),
                                                                    computeLayout,
                                                                    1, 1, 1));

            ResourceLayout graphicsLayout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                        new ResourceLayoutElementDescription("InputVertices", ResourceKind.StructuredBufferReadOnly, ShaderStages.Vertex)));
            ResourceSet graphicsSet = RF.CreateResourceSet(new ResourceSetDescription(graphicsLayout, buffer));

            Pipeline graphicsPipeline = RF.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                      BlendStateDescription.SingleOverrideBlend,
                                                                      DepthStencilStateDescription.Disabled,
                                                                      RasterizerStateDescription.Default,
                                                                      PrimitiveTopology.TriangleStrip,
                                                                      new ShaderSetDescription(
                                                                          Array.Empty <VertexLayoutDescription>(),
                                                                          TestShaders.LoadVertexFragment(RF, "ColoredQuadRenderer")),
                                                                      graphicsLayout,
                                                                      framebuffer.OutputDescription));

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.SetPipeline(computePipeline);
            cl.SetComputeResourceSet(0, computeSet);
            cl.Dispatch(1, 1, 1);
            cl.SetFramebuffer(framebuffer);
            cl.ClearColorTarget(0, new RgbaFloat());
            cl.SetPipeline(graphicsPipeline);
            cl.SetGraphicsResourceSet(0, graphicsSet);
            cl.Draw(4);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            Texture readback = GetReadback(output);
            MappedResourceView <RgbaFloat> readView = GD.Map <RgbaFloat>(readback, MapMode.Read);

            for (uint y = 0; y < height; y++)
            {
                for (uint x = 0; x < width; x++)
                {
                    Assert.Equal(RgbaFloat.Red, readView[x, y]);
                }
            }
            GD.Unmap(readback);
        }
Пример #34
0
 /// <summary>
 /// Binds the texture to <paramref name="attachment"/> for
 /// <paramref name="target"/>.
 /// </summary>
 /// <param name="attachment">The attachment point</param>
 /// <param name="target">The target framebuffer for attachment</param>
 public void Attach(FramebufferAttachment attachment, Framebuffer target)
 {
     target.Bind();
     GL.FramebufferTexture(target.Target, attachment, Id, 0);
 }
Пример #35
0
 public RawRectangle(VncHost rfb, Framebuffer framebuffer, int[] pixels, Rectangle2 rectangle)
     : base(rfb, framebuffer, rectangle)
 {
     this.pixels = pixels;
 }
        unsafe public CommandList BuildCommandList(GraphicsDevice graphicsDevice, Framebuffer framebuffer)
        {
            ResourceFactory factory       = graphicsDevice.ResourceFactory;
            Shader          _vsShader     = null;
            Shader          _psShader     = null;
            DeviceBuffer    _vertexBuffer = null;
            Pipeline        _pipeline     = null;

            Veldrid.CommandList _commandList = null;
            try
            {
                #region --- try

                #region --- shaders
                {
                    string _vsname = null;
                    string _psname = null;

                    switch (graphicsDevice.BackendType)
                    {
                    case GraphicsBackend.Direct3D11:
                        _vsname = "Test_Colored2DVertices.vs";
                        _psname = "Test_Colored2DVertices.ps";
                        break;

                    case GraphicsBackend.Metal:
                        _vsname = "Test_Colored2DVertices_vs.msl";
                        _psname = "Test_Colored2DVertices_ps.msl";
                        break;

                    case GraphicsBackend.Vulkan:
                        _vsname = "Test_Colored2DVertices_vs.spv";
                        _psname = "Test_Colored2DVertices_ps.spv";
                        break;

                    case GraphicsBackend.OpenGL:
                        _vsname = "Test_Colored2DVertices_vs.glsl";
                        _psname = "Test_Colored2DVertices_ps.glsl";
                        break;

                    case GraphicsBackend.OpenGLES:
                        _vsname = "Test_Colored2DVertices_vs_es.glsl";
                        _psname = "Test_Colored2DVertices_ps_es.glsl";
                        break;
                    }

                    string _vs = loadResourceString(Assembly.GetExecutingAssembly(), _vsname);
                    if (string.IsNullOrEmpty(_vs))
                    {
                        return(null);
                    }
                    string _ps = loadResourceString(Assembly.GetExecutingAssembly(), _psname);
                    if (string.IsNullOrEmpty(_ps))
                    {
                        return(null);
                    }

                    ShaderDescription vertexShaderDesc = new ShaderDescription(
                        ShaderStages.Vertex,
                        Encoding.UTF8.GetBytes(_vs),
                        "_VertexShader");
                    ShaderDescription fragmentShaderDesc = new ShaderDescription(
                        ShaderStages.Fragment,
                        Encoding.UTF8.GetBytes(_ps),
                        "_PixelShader");

                    _vsShader = factory.CreateShader(vertexShaderDesc);
                    _psShader = factory.CreateShader(fragmentShaderDesc);
                }
                #endregion

                VertexLayoutDescription _vertexLayout = new VertexLayoutDescription();
                int _vertexCount;

                #region --- _vertexBuffer + _vertexLayout
                {
                    int    _count = 10;
                    byte[] _data  = Build_2DColoredQuads_16SNorm_8UNorm(_count, _count, out _vertexCount);
                    //
                    Veldrid.BufferDescription vbDescription = new Veldrid.BufferDescription(
                        (uint)_data.Length,
                        BufferUsage.VertexBuffer);
                    _vertexBuffer = factory.CreateBuffer(vbDescription);

                    fixed(byte *_pdata = _data)
                    {
                        graphicsDevice.UpdateBuffer(_vertexBuffer, bufferOffsetInBytes: 0, (IntPtr)_pdata, (uint)_data.Length);
                    }

                    _vertexLayout = new VertexLayoutDescription(
                        new VertexElementDescription("Position",
                                                     VertexElementSemantic.Position,
                                                     VertexElementFormat.Short2_Norm,
                                                     offset: 0),
                        new VertexElementDescription("Color",
                                                     VertexElementSemantic.Color,
                                                     VertexElementFormat.Byte4_Norm,
                                                     offset: 2 * sizeof(short)));
                }
                #endregion

                #region --- pipeline
                {
                    GraphicsPipelineDescription _pipelineDescription = new GraphicsPipelineDescription();

                    _pipelineDescription.BlendState = Veldrid.BlendStateDescription.SingleOverrideBlend;

                    _pipelineDescription.DepthStencilState = new Veldrid.DepthStencilStateDescription(
                        depthTestEnabled: false,
                        depthWriteEnabled: false,
                        comparisonKind: ComparisonKind.LessEqual);

                    _pipelineDescription.RasterizerState = new Veldrid.RasterizerStateDescription(
                        cullMode: FaceCullMode.None,
                        fillMode: PolygonFillMode.Solid,
                        frontFace: FrontFace.Clockwise,
                        depthClipEnabled: true, // Android ?
                        scissorTestEnabled: false);

                    _pipelineDescription.PrimitiveTopology = Veldrid.PrimitiveTopology.TriangleList;
                    _pipelineDescription.ResourceLayouts   = System.Array.Empty <ResourceLayout>();

                    _pipelineDescription.ShaderSet = new ShaderSetDescription(
                        vertexLayouts: new VertexLayoutDescription[] { _vertexLayout },
                        shaders: new Shader[] { _vsShader, _psShader });

                    _pipelineDescription.Outputs = framebuffer.OutputDescription; // _offscreenFB.OutputDescription;

                    _pipeline = factory.CreateGraphicsPipeline(_pipelineDescription);
                }
                #endregion

                #region --- commandList
                {
                    _commandList = factory.CreateCommandList();

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

                    _commandList.SetPipeline(_pipeline);

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

                    _commandList.SetFullViewports();
                    _commandList.ClearColorTarget(0, RgbaFloat.DarkRed);

                    // Set all relevant state to draw our quad.
                    _commandList.SetVertexBuffer(0, _vertexBuffer);

                    _commandList.Draw(vertexCount: (uint)_vertexCount);

                    // End() must be called before commands can be submitted for execution.
                    _commandList.End();
                }
                #endregion

                CommandList vret = _commandList;
                _commandList = null;

                return(vret);

                #endregion
            }
            catch (Exception e)
            {
                return(null);
            }
            finally
            {
                _vsShader?.Dispose();
                _psShader?.Dispose();
                _vertexBuffer?.Dispose();
                _pipeline?.Dispose();
                _commandList?.Dispose();
            }
        }
Пример #37
0
 public CoRreRectangle(RfbProtocol rfb, Framebuffer framebuffer, int[] pixels, Rectangle rectangle)
     : base(rfb, framebuffer, rectangle, RfbProtocol.Encoding.CORRE_ENCODING)
 {
     this.pixels = pixels;
 }
Пример #38
0
 public CoRRE(RfbProtocol rfb, Framebuffer framebuffer, int[] pixels, Rectangle rectangle)
     : base(rfb, framebuffer, pixels, rectangle)
 {
     this.pixels = pixels;
 }
Пример #39
0
 public ZrleRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle)
     : base(rfb, framebuffer, rectangle, RfbProtocol.ZRLE_ENCODING)
 {
 }
Пример #40
0
        public override void Init()
        {
            //Window.SetIcon("textures/icon.png");

            Platform.RelativeMouseMode = true;
            //Platform.ShowCursor = false; // Default true

            Camera.FoV         = 75f;
            Camera.AspectRatio = width / (float)height;
            Camera.Position    = new Vector3(0f, 2f, -5f);
            //Camera.Projection = Projection.Orthographic;
            //Camera.Width = Window.Width / 10;
            //Camera.Height = Window.Height / 10;
            Camera.zNear = 0.1f;
            Camera.zFar  = 150f;

            surface = Framebuffer.Create(width, height, 1, TextureFormat.RGB8, TextureFormat.Depth24);

            vertexFormat = new VertexFormat(
                4,                                                                    // Pack
                new VertexAttribute(DataType.Float, 3, false),                        // Position
                new VertexAttribute(DataType.Float, 3, false),                        // Normal
                new VertexAttribute(DataType.UnsignedByte, 4, true),                  // Colour
                new VertexAttribute(DataType.UnsignedShort, 2, true),                 // UV
                new VertexAttribute(DataType.UnsignedByte, 1, true)                   // Textured
                );

            Geometry cubeGeometry = Geometry.Cube();

            cubeVertices = new Vertex[cubeGeometry.Vertices.Length];
            for (int i = 0; i < cubeGeometry.Vertices.Length; i++)
            {
                cubeVertices[i] = new Vertex(cubeGeometry.Vertices[i].Position, cubeGeometry.Vertices[i].Normal, cubeGeometry.Vertices[i].Colour, cubeGeometry.Vertices[i].UV, false);
            }
            cubeIndices = cubeGeometry.Indices16;

            //Geometry icosphereGeometry = Geometry.Icosphere(0.5f, 4, false);
            Geometry icosphereGeometry = Geometry.Octahedron(0.5f, 2, true);

            icosphereVertices = new Vertex[icosphereGeometry.Vertices.Length];
            for (int i = 0; i < icosphereGeometry.Vertices.Length; i++)
            {
                icosphereVertices[i] = new Vertex(icosphereGeometry.Vertices[i].Position, icosphereGeometry.Vertices[i].Normal, icosphereGeometry.Vertices[i].Colour, icosphereGeometry.Vertices[i].UV, true);
            }
            icosphereIndices = icosphereGeometry.Indices16;

            cubeVertexBuffer       = VertexBuffer.Create(BufferUsage.Static);
            cubeIndexBuffer        = IndexBuffer.Create(BufferUsage.Static);
            icosphereVertexBuffer  = VertexBuffer.Create(BufferUsage.Static);
            icosphereIndexBuffer   = IndexBuffer.Create(BufferUsage.Static);
            planeVertexBuffer      = VertexBuffer.Create(BufferUsage.Static);
            planeIndexBuffer       = IndexBuffer.Create(BufferUsage.Static);
            cubeGeometryInput      = GeometryInput.Create(cubeIndexBuffer, new VertexStream(cubeVertexBuffer, vertexFormat));
            icosphereGeometryInput = GeometryInput.Create(icosphereIndexBuffer, new VertexStream(icosphereVertexBuffer, vertexFormat));
            planeGeometryInput     = GeometryInput.Create(planeIndexBuffer, new VertexStream(planeVertexBuffer, vertexFormat));
            cubeVertexBuffer.LoadData(cubeVertices);
            cubeIndexBuffer.LoadData(cubeIndices);
            icosphereVertexBuffer.LoadData(icosphereVertices);
            icosphereIndexBuffer.LoadData(icosphereIndices);
            planeVertexBuffer.LoadData(planeVertices);
            planeIndexBuffer.LoadData(planeIndices);

            light1Transform.Parent = light1ParentTransform;
            light2Transform.Parent = light2ParentTransform;
            light3Transform.Parent = light3ParentTransform;
        }
 public HextileRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle) : base(rfb, framebuffer, rectangle)
 {
 }
Пример #42
0
 public PixelReader8(BinaryReader reader, Framebuffer framebuffer, RfbProtocol rfb) : base(reader, framebuffer)
 {
     this.rfb = rfb;
 }
Пример #43
0
 public EncodedRectangle(VncHost rfb, Framebuffer framebuffer, Rectangle2 rectangle)
 {
     this.rfb = rfb;
     this.framebuffer = framebuffer;
     this.rectangle = rectangle;
 }
        public RenderManager(GameWindow window, CsTerrainGenerator generator)
        {
            _window    = window;
            _generator = generator;

            _fgJobs = new ConcurrentQueue <IJob>();
            _bgJobs = new ConcurrentQueue <IJob>();

            _nvg = GlNanoVg.CreateGl(NvgCreateFlags.StencilStrokes | NvgCreateFlags.AntiAlias);
            _ui  = new KuatWindow(window, new KuatFont("sans", 16));

            // KuatButton b;
            // KuatKnob k;
            // KuatIndicator i;
            // _ui.Controls.Add(b = new KuatButton("bTest")
            // {
            //     Location = new Point(50, 50),
            //     Size = new Size(60, 23),
            //     Text = "Button"
            // });
            // b.Click += (sender, args) => { Lumberjack.Info("Click!"); };
            // _ui.Controls.Add(new KuatCheckbox("cbTest")
            // {
            //     Location = new Point(50, 90),
            //     Size = new Size(14, 14),
            //     Text = "Checkbox"
            // });
            // _ui.Controls.Add(k = new KuatKnob("kTest")
            // {
            //     Location = new Point(50, 130)
            // });
            // _ui.Controls.Add(i = new KuatIndicator("iTest")
            // {
            //     Location = new Point(120, 130)
            // });
            // k.ValueChanged += (sender, args) => { i.Lit = k.Value > 0; };
            // _ui.Controls.Add(new KuatTextBox("tbTest")
            // {
            //     Location = new Point(170, 90),
            //     Size = new Size(120, 23),
            //     ForeColor = Color.Black
            // });

            var rMono = _nvg.CreateFont("mono", EmbeddedFiles.ibmplexmono);

            if (rMono == -1)
            {
                throw new ApplicationException("Unable to load mono font");
            }

            var rSans = _nvg.CreateFont("sans", EmbeddedFiles.ibmplexsans);

            if (rSans == -1)
            {
                throw new ApplicationException("Unable to load sans font");
            }

            _perfGraphFps = new PerfGraph(GraphRenderStyle.Fps, null, 40);

            _framebuffer = new Framebuffer(8);
            _framebuffer.Init(window.Width, window.Height);
            _framebufferUi = new Framebuffer(1);
            _framebufferUi.Init(window.Width, window.Height);
            _texRandom   = LoadGlTexture(EmbeddedFiles.random);
            _shaderModel = new ShaderProgram(EmbeddedFiles.fs_model, EmbeddedFiles.vs_model);
            _shaderModel.Init();
            _shaderScreen = new ShaderProgram(EmbeddedFiles.fs_screen, EmbeddedFiles.vs_screen);
            _shaderScreen.Init();
            _workerHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

            CreateChunks();
            CreateScreenVao();
        }
Пример #45
0
		public HextileRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle)
			: base(rfb, framebuffer, rectangle, RfbProtocol.HEXTILE_ENCODING) 
		{
		}
Пример #46
0
		public PixelReader16(BinaryReader reader, Framebuffer framebuffer) : base(reader, framebuffer)
		{
		}
        public static void Run()
        {
            ShaderProgram prog = null, terrProg = null;
            Texture tex = null, t2 = null;

            GraphicsContext context = new GraphicsContext()
            {
                Camera = new FirstPersonCamera(new Vector3(4, 3, 3), Vector3.UnitY)
            };

            BitmapTextureSource bmpTex, b2, b3;
            bmpTex = TextDrawer.CreateWriter("Times New Roman", FontStyle.Regular).Write("Hello!", 200, System.Drawing.Color.White);
            b2 = new BitmapTextureSource("test.jpg", 0);
            b3 = new BitmapTextureSource("test.png", 0);

            Texture fbufTex = null, t3 = null;
            FramebufferTextureSource fbufTexSrc = new FramebufferTextureSource(256, 256, 0);
            Framebuffer fbuf = null;

            Matrix4 World = Matrix4.Identity;
            EngineObject eObj = null, fsq = null;
            float timer = 0;

            CubeMapTextureSource tFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.PositiveY, b3),
                bFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.PositiveX, b3),
                lFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.PositiveZ, b3),
                rFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.NegativeX, b3),
                fFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.NegativeY, b3),
                hFace = new CubeMapTextureSource(CubeMapTextureSource.CubeMapFace.NegativeZ, b3);

            GraphicsDevice.Load += () =>
            {
                // setup settings, load textures, sounds
                GraphicsDevice.Wireframe = false;
                GraphicsDevice.AlphaEnabled = true;
                GraphicsDevice.DepthTestEnabled = true;
                GraphicsDevice.CullEnabled = false;
                GraphicsDevice.CullMode = CullFaceMode.Back;

                eObj = new EngineObject();
                float[] data =
                {     -1, -1, 1,
                       1, -1, 1,
                       0, 1, 1
                };

                uint[] indexData = new uint[]
                {
                    0, 1, 2
                };

                ShaderSource vert = ShaderSource.Load(ShaderType.VertexShader, "Testing/TG_A/vertex.glsl");
                ShaderSource frag = ShaderSource.Load(ShaderType.FragmentShader, "Testing/TG_A/fragment.glsl");
                ShaderSource tctrl = ShaderSource.Load(ShaderType.TessControlShader, "Testing/TG_A/tesscontrol.glsl");
                ShaderSource teval = ShaderSource.Load(ShaderType.TessEvaluationShader, "Testing/TG_A/tessdomain.glsl");

                ShaderSource vA = ShaderSource.Load(ShaderType.VertexShader, "Shaders/TerrainGen/vertex.glsl");
                ShaderSource fA = ShaderSource.Load(ShaderType.FragmentShader, "Shaders/TerrainGen/fragment.glsl");
                terrProg = new ShaderProgram(vA, fA);
                terrProg.Set("World", Matrix4.Identity);

                fbuf = new Framebuffer(256, 256);
                fbufTex = new Texture();
                fbufTex.SetData(fbufTexSrc);
                fbuf[FramebufferAttachment.ColorAttachment0] = fbufTex;

                fsq = FullScreenQuadFactory.Create();

                t3 = new Texture();
                t3.SetData(tFace);
                t3.SetData(bFace);
                t3.SetData(lFace);
                t3.SetData(rFace);
                t3.SetData(fFace);
                t3.SetData(hFace);
                t3.SetEnableLinearFilter(true);
                t3.SetAnisotropicFilter(Texture.MaxAnisotropy);

                tex = new Texture();
                tex.SetData(bmpTex);
                tex.SetAnisotropicFilter(Texture.MaxAnisotropy);

                t2 = new Texture();
                t2.SetData(b3);
                t2.SetAnisotropicFilter(Texture.MaxAnisotropy);

                prog = new ShaderProgram(vert, tctrl, teval, frag);
                prog.Set("img", 0);
                prog.Set("heightmap", 1);
                prog.Set("World", World);

                vert.Dispose();
                frag.Dispose();
                tctrl.Dispose();
                teval.Dispose();

                //eObj = FullScreenQuadFactory.Create();
                eObj = CubeFactory.Create();
                eObj.SetTexture(0, t2);
                eObj.SetTexture(1, t3);

                b3.Dispose();
            };
            bool eyePosStill = false;
            GraphicsDevice.Update += (e) =>
            {
                // add game logic, input handling
                if (GraphicsDevice.Keyboard[Key.Escape])
                {
                    GraphicsDevice.Exit();
                }

                if(GraphicsDevice.Keyboard[Key.Z])
                {
                    GraphicsDevice.Wireframe = !GraphicsDevice.Wireframe;
                    //GraphicsDevice.CullEnabled = !GraphicsDevice.Wireframe;
                }

                if(GraphicsDevice.Keyboard[Key.F])
                {
                    eyePosStill = !eyePosStill;
                    Console.WriteLine("EyePosStill = " + eyePosStill);
                }

                context.Update(e);
                //context.Projection = Matrix4.Identity;
                //context.View = Matrix4.Identity;

                prog.Set("View", context.View);
                prog.Set("Proj", context.Projection);
                if(!eyePosStill)prog.Set("eyePos", context.Camera.Position);

                prog.Set("Fcoef", (float)(2.0f / Math.Log(1000001)/Math.Log(2)));

                //timer += 0.001f;
                //World = Matrix4.RotateY(timer);
                World = Matrix4.CreateScale(10);
                prog.Set("World", World);

                prog.Set("timer", timer);
                terrProg.Set("timer", timer);
            };

            bool te1 = false;

            GraphicsDevice.Render += (e) =>
            {
                GraphicsDevice.SetFramebuffer(fbuf);
                GraphicsDevice.Clear();

                fsq.Bind();
                GraphicsDevice.SetShaderProgram(terrProg);
                GraphicsDevice.SetViewport(0, 0, 256, 256);
                GraphicsDevice.Draw(PrimitiveType.Triangles, 0, fsq.IndexCount);

                eObj.Bind();
                GraphicsDevice.SetShaderProgram(prog);
                GraphicsDevice.SetViewport(0, 0, GraphicsDevice.WindowSize.Width, GraphicsDevice.WindowSize.Height);
                GraphicsDevice.PatchCount = 3;
                GraphicsDevice.Draw(PrimitiveType.Patches, 0, eObj.IndexCount);

                GraphicsDevice.SwapBuffers();
                if (!te1)
                {
                    te1 = true;
                    GraphicsDevice.SaveTexture(fbufTex, "test1.png");
                }
            };

            GraphicsDevice.Name = "The Julis Faction";
            // Run the game at 60 updates per second
            GraphicsDevice.Run(60.0, 60.0);
            if(GraphicsDevice.Cleanup != null)GraphicsDevice.Cleanup();
        }
Пример #48
0
		public CopyRectRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle)
			: base(rfb, framebuffer, rectangle, RfbProtocol.COPYRECT_ENCODING) 
		{
		}
Пример #49
0
 public PostProcessor(RenderManager rm, Camera cam)
 {
     this.renderManager = rm;
     this.cam = cam;
     fbo = new Framebuffer(cam.Width, cam.Height);
 }
Пример #50
0
 /// <summary>
 ///     Converts an integer pixel into a byte array
 /// </summary>
 /// <param name="pixel">The pixel represented as an integer value</param>
 /// <param name="fb">The framebuffer that should be used</param>
 /// <returns>A byte array containing the pixels BGRA data.</returns>
 public static byte[] GrabBytes(int pixel, Framebuffer fb)
 {
     var b = 0;
     byte[] bytes = null;
     switch (fb.BitsPerPixel)
     {
         case 32:
             bytes = new byte[4];
             bytes[b++] = (byte) (pixel & 0xFF); //B
             bytes[b++] = (byte) ((pixel >> 8) & 0xFF); //G
             bytes[b++] = (byte) ((pixel >> 16) & 0xFF); //R
             bytes[b++] = (byte) ((pixel >> 24) & 0xFF); //A
             break;
         case 16:
             bytes = new byte[2];
             bytes[b++] = (byte) (pixel & 0xFF); //B
             bytes[b++] = (byte) ((pixel >> 8) & 0xFF); //G
             break;
         case 8:
             bytes = new byte[1];
             bytes[b++] = (byte) (pixel & 0xFF); //B
             break;
     }
     return bytes;
 }
Пример #51
0
		public CoRreRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle) : base(rfb, framebuffer, rectangle, RfbProtocol.CORRE_ENCODING)
		{
		}
Пример #52
0
        public void Points_WithFloat16Color()
        {
            Texture target = RF.CreateTexture(TextureDescription.Texture2D(
                                                  50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.RenderTarget));
            Texture staging = RF.CreateTexture(TextureDescription.Texture2D(
                                                   50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Staging));

            Framebuffer framebuffer = RF.CreateFramebuffer(new FramebufferDescription(null, target));

            DeviceBuffer infoBuffer  = RF.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            DeviceBuffer orthoBuffer = RF.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            Matrix4x4    orthoMatrix = Matrix4x4.CreateOrthographicOffCenter(
                0,
                framebuffer.Width,
                framebuffer.Height,
                0,
                -1,
                1);

            GD.UpdateBuffer(orthoBuffer, 0, ref orthoMatrix);

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("Color_Half", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Half4))
            },
                TestShaders.LoadVertexFragment(RF, "F16VertexAttribs"));

            ResourceLayout layout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                new ResourceLayoutElementDescription("InfoBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                new ResourceLayoutElementDescription("OrthoBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceSet set = RF.CreateResourceSet(new ResourceSetDescription(layout, infoBuffer, orthoBuffer));

            GraphicsPipelineDescription gpd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                shaderSet,
                layout,
                framebuffer.OutputDescription);

            Pipeline pipeline = RF.CreateGraphicsPipeline(ref gpd);

            uint colorNormalizationFactor = 2500;

            const ushort f16_375  = 0x5DDC; // 375.0
            const ushort f16_500  = 0x5FD0; // 500.0
            const ushort f16_625  = 0x60E2; // 625.0
            const ushort f16_875  = 0x62D6; // 875.0
            const ushort f16_1250 = 0x64E2; // 1250.0
            const ushort f16_1875 = 0x6753; // 1875.0

            VertexCPU_UShort[] vertices = new VertexCPU_UShort[]
            {
                new VertexCPU_UShort
                {
                    Position = new Vector2(0.5f, 0.5f),
                    R        = f16_625,
                    G        = f16_1250,
                    B        = f16_1875,
                },
                new VertexCPU_UShort
                {
                    Position = new Vector2(10.5f, 12.5f),
                    R        = f16_625,
                    G        = f16_1250,
                    B        = f16_1875,
                },
                new VertexCPU_UShort
                {
                    Position = new Vector2(25.5f, 35.5f),
                    R        = f16_1875,
                    G        = f16_1250,
                    B        = f16_625,
                },
                new VertexCPU_UShort
                {
                    Position = new Vector2(49.5f, 49.5f),
                    R        = f16_375,
                    G        = f16_500,
                    B        = f16_875,
                },
            };

            RgbaFloat[] expectedColors = new[]
            {
                new RgbaFloat(
                    625.0f / colorNormalizationFactor,
                    1250.0f / colorNormalizationFactor,
                    1875.0f / colorNormalizationFactor,
                    1),
                new RgbaFloat(
                    625.0f / colorNormalizationFactor,
                    1250.0f / colorNormalizationFactor,
                    1875.0f / colorNormalizationFactor,
                    1),
                new RgbaFloat(
                    1875.0f / colorNormalizationFactor,
                    1250.0f / colorNormalizationFactor,
                    625.0f / colorNormalizationFactor,
                    1),
                new RgbaFloat(
                    375.0f / colorNormalizationFactor,
                    500.0f / colorNormalizationFactor,
                    875.0f / colorNormalizationFactor,
                    1),
            };

            DeviceBuffer vb = RF.CreateBuffer(
                new BufferDescription((uint)(Unsafe.SizeOf <UIntVertexAttribsVertex>() * vertices.Length), BufferUsage.VertexBuffer));

            GD.UpdateBuffer(vb, 0, vertices);
            GD.UpdateBuffer(infoBuffer, 0, new UIntVertexAttribsInfo {
                ColorNormalizationFactor = colorNormalizationFactor
            });

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.SetFramebuffer(framebuffer);
            cl.SetFullViewports();
            cl.SetFullScissorRects();
            cl.ClearColorTarget(0, RgbaFloat.Black);
            cl.SetPipeline(pipeline);
            cl.SetVertexBuffer(0, vb);
            cl.SetGraphicsResourceSet(0, set);
            cl.Draw((uint)vertices.Length);
            cl.CopyTexture(target, staging);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            MappedResourceView <RgbaFloat> readView = GD.Map <RgbaFloat>(staging, MapMode.Read);

            for (int i = 0; i < vertices.Length; i++)
            {
                VertexCPU_UShort vertex = vertices[i];
                uint             x      = (uint)vertex.Position.X;
                uint             y      = (uint)vertex.Position.Y;
                if (!GD.IsUvOriginTopLeft || GD.IsClipSpaceYInverted)
                {
                    y = framebuffer.Height - y - 1;
                }

                RgbaFloat expectedColor = expectedColors[i];
                Assert.Equal(expectedColor, readView[x, y], RgbaFloatFuzzyComparer.Instance);
            }
            GD.Unmap(staging);
        }
Пример #53
0
        void init()
        {
            //Shadow map renderpass
            shadowPass = new RenderPass(dev, VkSampleCountFlags.SampleCount1);
            shadowPass.AddAttachment(SHADOWMAP_FORMAT, VkImageLayout.DepthStencilReadOnlyOptimal, SHADOWMAP_NUM_SAMPLES);
            shadowPass.ClearValues.Add(new VkClearValue {
                depthStencil = new VkClearDepthStencilValue(1.0f, 0)
            });

            SubPass subpass0 = new SubPass();

            subpass0.SetDepthReference(0);
            shadowPass.AddSubpass(subpass0);

            shadowPass.AddDependency(Vk.SubpassExternal, 0,
                                     VkPipelineStageFlags.FragmentShader, VkPipelineStageFlags.EarlyFragmentTests,
                                     VkAccessFlags.ShaderRead, VkAccessFlags.DepthStencilAttachmentWrite);
            shadowPass.AddDependency(0, Vk.SubpassExternal,
                                     VkPipelineStageFlags.LateFragmentTests, VkPipelineStageFlags.FragmentShader,
                                     VkAccessFlags.DepthStencilAttachmentWrite, VkAccessFlags.ShaderRead);

            descLayoutShadow = new DescriptorSetLayout(dev,
                                                       new VkDescriptorSetLayoutBinding(0, VkShaderStageFlags.Geometry, VkDescriptorType.UniformBuffer),  //matrices
                                                       new VkDescriptorSetLayoutBinding(1, VkShaderStageFlags.Geometry, VkDescriptorType.UniformBuffer)); //lights

            GraphicPipelineConfig cfg = GraphicPipelineConfig.CreateDefault(VkPrimitiveTopology.TriangleList);

            cfg.rasterizationState.cullMode        = VkCullModeFlags.Back;
            cfg.rasterizationState.depthBiasEnable = true;
            cfg.dynamicStates.Add(VkDynamicState.DepthBias);

            cfg.RenderPass = shadowPass;

            cfg.Layout = new PipelineLayout(dev, descLayoutShadow);
            cfg.Layout.AddPushConstants(
                new VkPushConstantRange(VkShaderStageFlags.Vertex, (uint)Marshal.SizeOf <Matrix4x4> ())
                );

            cfg.AddVertexBinding <PbrModel.Vertex> (0);
            cfg.AddVertexAttributes(0, VkFormat.R32g32b32Sfloat);

            cfg.AddShader(VkShaderStageFlags.Vertex, "shaders/shadow.vert.spv");
            cfg.AddShader(VkShaderStageFlags.Geometry, "shaders/shadow.geom.spv");

            shadowPipeline = new GraphicPipeline(cfg);

            //shadow map image
            shadowMap = new Image(dev, SHADOWMAP_FORMAT, VkImageUsageFlags.DepthStencilAttachment | VkImageUsageFlags.Sampled, VkMemoryPropertyFlags.DeviceLocal, SHADOWMAP_SIZE, SHADOWMAP_SIZE,
                                  VkImageType.Image2D, SHADOWMAP_NUM_SAMPLES, VkImageTiling.Optimal, 1, (uint)renderer.lights.Length);
            shadowMap.CreateView(VkImageViewType.ImageView2DArray, VkImageAspectFlags.Depth, shadowMap.CreateInfo.arrayLayers);
            shadowMap.CreateSampler(VkSamplerAddressMode.ClampToBorder);
            shadowMap.Descriptor.imageLayout = VkImageLayout.DepthStencilReadOnlyOptimal;

            fbShadowMap = new Framebuffer(shadowPass, SHADOWMAP_SIZE, SHADOWMAP_SIZE, (uint)renderer.lights.Length);
            fbShadowMap.attachments.Add(shadowMap);
            fbShadowMap.Activate();

            dsShadow = descriptorPool.Allocate(descLayoutShadow);

            DescriptorSetWrites dsWrite = new DescriptorSetWrites(dsShadow, descLayoutShadow);

            dsWrite.Write(dev, renderer.uboMatrices.Descriptor, renderer.uboLights.Descriptor);
        }
Пример #54
0
		public ZrleRectangle(RfbProtocol rfb, Framebuffer framebuffer, Rectangle rectangle)
			: base(rfb, framebuffer, rectangle, RfbProtocol.ZRLE_ENCODING)
		{
		}
Пример #55
0
		protected PixelReader(BinaryReader reader, Framebuffer framebuffer)
		{
			this.reader = reader;
			this.framebuffer = framebuffer;
		}
Пример #56
0
        public PeelingResource(int width, int height)
        {
            this.width  = width;
            this.height = height;

            for (int i = 0; i < 2; i++)
            {
                var depthStorage = new TexImage2D(TexImage2D.Target.TextureRectangle, 0, GL.GL_DEPTH_COMPONENT32, width, height, 0, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT);
                var depthTexture = new Texture(TextureTarget.TextureRectangle, depthStorage,
                                               new TexParameteri(TexParameter.PropertyName.TextureWrapS, (int)GL.GL_CLAMP),
                                               new TexParameteri(TexParameter.PropertyName.TextureWrapT, (int)GL.GL_CLAMP),
                                               new TexParameteri(TexParameter.PropertyName.TextureMagFilter, (int)GL.GL_NEAREST),
                                               new TexParameteri(TexParameter.PropertyName.TextureMinFilter, (int)GL.GL_NEAREST)
                                               );
                depthTexture.Initialize();

                var colorStorage = new TexImage2D(TexImage2D.Target.TextureRectangle, 0, GL.GL_RGBA, width, height, 0, GL.GL_RGBA, GL.GL_FLOAT);
                var colorTexture = new Texture(TextureTarget.TextureRectangle, colorStorage,
                                               new TexParameteri(TexParameter.PropertyName.TextureWrapS, (int)GL.GL_CLAMP),
                                               new TexParameteri(TexParameter.PropertyName.TextureWrapT, (int)GL.GL_CLAMP),
                                               new TexParameteri(TexParameter.PropertyName.TextureMagFilter, (int)GL.GL_NEAREST),
                                               new TexParameteri(TexParameter.PropertyName.TextureMinFilter, (int)GL.GL_NEAREST)
                                               );
                colorTexture.Initialize();

                var framebuffer = new Framebuffer(width, height);
                framebuffer.Bind();

                framebuffer.Attach(depthTexture, true);
                framebuffer.Attach(colorTexture, false);

                framebuffer.CheckCompleteness();
                framebuffer.Unbind();

                this.framebuffers[i]     = framebuffer;
                this.colorAttachments[i] = colorTexture;
                this.depthAttachments[i] = depthTexture;
            }

            {
                var colorStorage = new TexImage2D(TexImage2D.Target.TextureRectangle, 0, GL.GL_RGBA, width, height, 0, GL.GL_RGBA, GL.GL_FLOAT);
                var colorTexture = new Texture(TextureTarget.TextureRectangle, colorStorage,
                                               new TexParameteri(TexParameter.PropertyName.TextureWrapS, (int)GL.GL_CLAMP),
                                               new TexParameteri(TexParameter.PropertyName.TextureWrapT, (int)GL.GL_CLAMP),
                                               new TexParameteri(TexParameter.PropertyName.TextureMagFilter, (int)GL.GL_NEAREST),
                                               new TexParameteri(TexParameter.PropertyName.TextureMinFilter, (int)GL.GL_NEAREST)
                                               );
                colorTexture.Initialize();

                var framebuffer = new Framebuffer(width, height);
                framebuffer.Bind();

                framebuffer.Attach(this.depthAttachments[0], true);
                framebuffer.Attach(colorTexture, false);

                framebuffer.CheckCompleteness();
                framebuffer.Unbind();

                this.colorBlenderFramebuffer     = framebuffer;
                this.colorBlenderColorAttachment = colorTexture;
            }
        }
Пример #57
0
        /// <summary>
        ///     Converts an array of pixels represented as integers into a byte array of pixel data.
        /// </summary>
        /// <param name="pixels">The pixel array represented as integers.</param>
        /// <param name="rectangle">A sub-rectangle of the pixels which we should extract</param>
        /// <param name="fb">The Framebuffer that should be used.</param>
        /// <returns></returns>
        public static byte[] GrabPixels(int[] pixels, Rectangle rectangle, Framebuffer fb)
        {
            // Encode as bytes
            var x = rectangle.X;
            var y = rectangle.Y;
            var w = rectangle.Width;
            var h = rectangle.Height;

            byte[] bytes = null;

            var b = 0;
            var i = 0;
            var s = 0;
            int pixel;
            var size = w*h;
            var scanline = w;
            var offsetX = x;
            var offsetY = y;
            var jump = scanline - w;
            var p = (y - offsetY)*w + x - offsetX;

            switch (fb.BitsPerPixel)
            {
                case 32:
                    bytes = new byte[size << 2];
                    for (; i < size; i++, s++, p++)
                    {
                        if (s == w)
                        {
                            s = 0;
                            p += jump;
                        }
                        var tmp = pixels[p];
                        pixel = fb.TranslatePixel(tmp);
                        //pixel = pixels[p];

                        bytes[b++] = (byte) (pixel & 0xFF); //B
                        bytes[b++] = (byte) ((pixel >> 8) & 0xFF); //G
                        bytes[b++] = (byte) ((pixel >> 16) & 0xFF); //R
                        bytes[b++] = (byte) ((pixel >> 24) & 0xFF); //A
                    }
                    break;
                case 24:
                    bytes = new byte[size << 2];
                    for (; i < size; i++, s++, p++)
                    {
                        if (s == w)
                        {
                            s = 0;
                            p += jump;
                        }
                        pixel = fb.TranslatePixel(pixels[p]);
                        bytes[b++] = (byte) (pixel & 0xFF); //B
                        bytes[b++] = (byte) ((pixel >> 8) & 0xFF); //G
                        bytes[b++] = (byte) ((pixel >> 16) & 0xFF); //R
                    }
                    break;
                case 16:
                    bytes = new byte[size << 1];
                    for (; i < size; i++, s++, p++)
                    {
                        if (s == w)
                        {
                            s = 0;
                            p += jump;
                        }
                        pixel = fb.TranslatePixel(pixels[p]);
                        bytes[b++] = (byte) (pixel & 0xFF); //B
                        bytes[b++] = (byte) ((pixel >> 8) & 0xFF); //G
                    }
                    break;
                case 8:
                    bytes = new byte[size];
                    for (; i < size; i++, s++, p++)
                    {
                        if (s == w)
                        {
                            s = 0;
                            p += jump;
                        }
                        bytes[i] = (byte) fb.TranslatePixel(pixels[p]); //B
                    }
                    break;
            }
            return bytes;
        }
Пример #58
0
        private void CreateResources()
        {
            _factory = new DisposeCollectorResourceFactory(_gd.ResourceFactory);

            _cl = _factory.CreateCommandList();

            _cl.Begin();
            _projectionBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBuffer       = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _modelBuffer      = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            _projectionBufferForShadowShader = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBufferShadow  = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _modelBufferShadow = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            // TODO: no idea why this buffer requires 48 bytes instead of 32 bytes, padding?
            //_directionLightBuffer = _factory.CreateBuffer(new BufferDescription(48, BufferUsage.UniformBuffer));
            // addition of shadowmatrix, now requires (48+64=) 112 bytes
            _directionLightBuffer = _factory.CreateBuffer(new BufferDescription(112, BufferUsage.UniformBuffer));

            _cl.End();
            _gd.SubmitCommands(_cl);
            _gd.WaitForIdle();

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                    new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3))
            },
                new[]
            {
                LoadShader(_factory, "ColorShader", ShaderStages.Vertex, "VS"),
                LoadShader(_factory, "ColorShader", ShaderStages.Fragment, "FS")
            });

            ShaderSetDescription shaderSetShadow = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                    new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3))
            },
                new[]
            {
                LoadShader(_factory, "ShadowShader", ShaderStages.Vertex, "VS"),
                LoadShader(_factory, "ShadowShader", ShaderStages.Fragment, "FS")
            });

            ResourceLayout projectionViewMatricesLightLayout = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("DirectionalLight", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("ShadowMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("ShadowMapSampler", ResourceKind.Sampler, ShaderStages.Fragment)
                    ));

            ResourceLayout perObjectLayout = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Model", ResourceKind.UniformBuffer, ShaderStages.Vertex)
                    ));

            ResourceLayout projectionViewMatricesLayoutShadow = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex)
                    ));

            ResourceLayout modelLayoutShadow = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Model", ResourceKind.UniformBuffer, ShaderStages.Vertex)
                    ));

            _pipeline = _factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                            BlendStateDescription.SingleOverrideBlend,
                                                            DepthStencilStateDescription.DepthOnlyLessEqual,
                                                            RasterizerStateDescription.Default,
                                                            PrimitiveTopology.TriangleList,
                                                            shaderSet,
                                                            new[] { projectionViewMatricesLightLayout, perObjectLayout },
                                                            _gd.SwapchainFramebuffer.OutputDescription));

            TextureDescription desc = TextureDescription.Texture2D(2048, 2048, 1, 1, PixelFormat.D32_Float_S8_UInt, TextureUsage.DepthStencil | TextureUsage.Sampled);

            _shadowMap            = _factory.CreateTexture(desc);
            _shadowMap.Name       = "Shadow Map";
            _shadowMapView        = _factory.CreateTextureView(_shadowMap);
            _shadowMapFramebuffer = _factory.CreateFramebuffer(new FramebufferDescription(
                                                                   new FramebufferAttachmentDescription(_shadowMap, 0), Array.Empty <FramebufferAttachmentDescription>()));


            _pipelineShadow = _factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                  BlendStateDescription.Empty,
                                                                  DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                  RasterizerStateDescription.Default,
                                                                  PrimitiveTopology.TriangleList,
                                                                  shaderSetShadow,
                                                                  new[] { projectionViewMatricesLayoutShadow, modelLayoutShadow },
                                                                  _shadowMapFramebuffer.OutputDescription));

            _projectionViewMatricesLightSet = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                             projectionViewMatricesLightLayout,
                                                                             _projectionBuffer,
                                                                             _viewBuffer,
                                                                             _directionLightBuffer,
                                                                             _shadowMapView,
                                                                             _gd.PointSampler));

            _perObjectSet = _factory.CreateResourceSet(new ResourceSetDescription(
                                                           perObjectLayout,
                                                           _modelBuffer));

            _projectionViewMatricesSetShadow = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                              projectionViewMatricesLayoutShadow,
                                                                              _projectionBufferForShadowShader,
                                                                              _viewBufferShadow));

            _modelMatrixSetShadow = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                   modelLayoutShadow,
                                                                   _modelBufferShadow));
        }
Пример #59
0
 public CoRreRectangle(VncHost rfb, Framebuffer framebuffer, int[] pixels, Rectangle2 rectangle)
     : base(rfb, framebuffer, rectangle)
 {
     this.pixels = pixels;
 }
Пример #60
0
        public void Points_WithUShortNormColor()
        {
            Texture target = RF.CreateTexture(TextureDescription.Texture2D(
                                                  50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.RenderTarget));
            Texture staging = RF.CreateTexture(TextureDescription.Texture2D(
                                                   50, 50, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Staging));

            Framebuffer framebuffer = RF.CreateFramebuffer(new FramebufferDescription(null, target));

            DeviceBuffer orthoBuffer = RF.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            Matrix4x4    orthoMatrix = Matrix4x4.CreateOrthographicOffCenter(
                0,
                framebuffer.Width,
                framebuffer.Height,
                0,
                -1,
                1);

            GD.UpdateBuffer(orthoBuffer, 0, ref orthoMatrix);

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.UShort4_Norm))
            },
                TestShaders.LoadVertexFragment(RF, "U16NormVertexAttribs"));

            ResourceLayout layout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                new ResourceLayoutElementDescription("Ortho", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceSet set = RF.CreateResourceSet(new ResourceSetDescription(layout, orthoBuffer));

            GraphicsPipelineDescription gpd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                shaderSet,
                layout,
                framebuffer.OutputDescription);

            Pipeline pipeline = RF.CreateGraphicsPipeline(ref gpd);

            VertexCPU_UShortNorm[] vertices = new VertexCPU_UShortNorm[]
            {
                new VertexCPU_UShortNorm
                {
                    Position = new Vector2(0.5f, 0.5f),
                    R        = UShortNorm(0.25f),
                    G        = UShortNorm(0.5f),
                    B        = UShortNorm(0.75f),
                },
                new VertexCPU_UShortNorm
                {
                    Position = new Vector2(10.5f, 12.5f),
                    R        = UShortNorm(0.25f),
                    G        = UShortNorm(0.5f),
                    B        = UShortNorm(0.75f),
                },
                new VertexCPU_UShortNorm
                {
                    Position = new Vector2(25.5f, 35.5f),
                    R        = UShortNorm(0.75f),
                    G        = UShortNorm(0.5f),
                    B        = UShortNorm(0.25f),
                },
                new VertexCPU_UShortNorm
                {
                    Position = new Vector2(49.5f, 49.5f),
                    R        = UShortNorm(0.15f),
                    G        = UShortNorm(0.25f),
                    B        = UShortNorm(0.35f),
                },
            };

            DeviceBuffer vb = RF.CreateBuffer(
                new BufferDescription((uint)(Unsafe.SizeOf <VertexCPU_UShortNorm>() * vertices.Length), BufferUsage.VertexBuffer));

            GD.UpdateBuffer(vb, 0, vertices);

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.SetFramebuffer(framebuffer);
            cl.SetFullViewports();
            cl.SetFullScissorRects();
            cl.ClearColorTarget(0, RgbaFloat.Black);
            cl.SetPipeline(pipeline);
            cl.SetVertexBuffer(0, vb);
            cl.SetGraphicsResourceSet(0, set);
            cl.Draw((uint)vertices.Length);
            cl.CopyTexture(target, staging);
            cl.End();
            GD.SubmitCommands(cl);
            GD.WaitForIdle();

            MappedResourceView <RgbaFloat> readView = GD.Map <RgbaFloat>(staging, MapMode.Read);

            foreach (VertexCPU_UShortNorm vertex in vertices)
            {
                uint x = (uint)vertex.Position.X;
                uint y = (uint)vertex.Position.Y;
                if (!GD.IsUvOriginTopLeft || GD.IsClipSpaceYInverted)
                {
                    y = framebuffer.Height - y - 1;
                }

                RgbaFloat expectedColor = new RgbaFloat(
                    vertex.R / (float)ushort.MaxValue,
                    vertex.G / (float)ushort.MaxValue,
                    vertex.B / (float)ushort.MaxValue,
                    1);
                Assert.Equal(expectedColor, readView[x, y], RgbaFloatFuzzyComparer.Instance);
            }
            GD.Unmap(staging);
        }