Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Gorgon2DTarget"/> struct.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="depthStencil">The depth/stencil view.</param>
        public Gorgon2DTarget(GorgonRenderTargetView target, GorgonDepthStencilView depthStencil)
        {
            Target       = target;
            DepthStencil = null;
            SwapChain    = null;
            Height       = 1;

            switch (target.Resource.ResourceType)
            {
            case ResourceType.Buffer:
                var buffer = (GorgonBuffer)target.Resource;
                var info   = GorgonBufferFormatInfo.GetInfo(buffer.Settings.DefaultShaderViewFormat);

                Width    = buffer.SizeInBytes / info.SizeInBytes;
                Viewport = new GorgonViewport(0, 0, Width, Height, 0, 1.0f);
                break;

            case ResourceType.Texture1D:
                var target1D = (GorgonRenderTarget1D)target.Resource;

                Width        = target1D.Settings.Width;
                Viewport     = target1D.Viewport;
                DepthStencil = depthStencil ?? target1D.DepthStencilBuffer;
                break;

            case ResourceType.Texture2D:
                var target2D = (GorgonRenderTarget2D)target.Resource;

                Width    = target2D.Settings.Width;
                Height   = target2D.Settings.Height;
                Viewport = target2D.Viewport;
                if (target2D.IsSwapChain)
                {
                    SwapChain = (GorgonSwapChain)target2D;
                }
                DepthStencil = depthStencil ?? target2D.DepthStencilBuffer;
                break;

            case ResourceType.Texture3D:
                var target3D = (GorgonRenderTarget3D)target.Resource;

                Width    = target3D.Settings.Width;
                Height   = target3D.Settings.Height;
                Viewport = target3D.Viewport;
                break;

            default:
                throw new GorgonException(GorgonResult.CannotBind, "Could not bind a render target.  Resource type is unknown.  Should not see this error.");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            var depthFormat = BufferFormat.D24_UIntNormal_S8_UInt;                              // Depth buffer format.

            // Create our form.
            _mainForm = new formMain();

            // Add a keybinding to switch to full screen or windowed.
            _mainForm.KeyDown += _mainForm_KeyDown;

            // Create the main graphics interface.
            Graphics = new GorgonGraphics();

            // Validate depth buffer for this device.
            // Odds are good that if this fails, you should probably invest in a
            // better video card.  Preferably something created after 2005.
            if (!Graphics.VideoDevice.SupportsDepthFormat(depthFormat))
            {
                depthFormat = BufferFormat.D16_UIntNormal;

                if (Graphics.VideoDevice.SupportsDepthFormat(depthFormat))
                {
                    return;
                }

                GorgonDialogs.ErrorBox(_mainForm, "Video device does not support a 24 or 16 bit depth buffer.");
                return;
            }

            // Create a 1280x800 window with a depth buffer.
            // We can modify the resolution in the config file for the application, but
            // like other Gorgon examples, the default is 1280x800.
            _swap = Graphics.Output.CreateSwapChain("Main", new GorgonSwapChainSettings
            {
                Window             = _mainForm,                                         // Assign to our form.
                Format             = BufferFormat.R8G8B8A8_UIntNormal,                  // Set up for 32 bit RGBA normalized display.
                Size               = Settings.Default.Resolution,                       // Get the resolution from the config file.
                DepthStencilFormat = depthFormat,                                       // Get our depth format.
                IsWindowed         = Settings.Default.IsWindowed                        // Set up for windowed or full screen (depending on config file).
            });

            // Center on the primary monitor.
            // This is necessary because we already created the window, so it'll be off center at this point.
            _mainForm.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - _mainForm.Width / 2,
                                           Screen.PrimaryScreen.WorkingArea.Height / 2 - _mainForm.Height / 2);

            // Handle any resizing.
            // This is here because the base graphics library will NOT handle state loss due to resizing.
            // This is up to the developer to handle.
            _swap.AfterSwapChainResized += _swap_Resized;

            // Create the 2D interface for our text.
            _2D = Graphics.Output.Create2DRenderer(_swap);

            // Create our shaders.
            // Our vertex shader.  This is a simple shader, it just processes a vertex by multiplying it against
            // the world/view/projection matrix and spits it back out.
            _vertexShader = Graphics.Shaders.CreateShader <GorgonVertexShader>("VertexShader", "BoingerVS", Resources.Shader);
            // Our main pixel shader.  This is a very simple shader, it just reads a texture and spits it back out.  Has no
            // diffuse capability.
            _pixelShader = Graphics.Shaders.CreateShader <GorgonPixelShader>("PixelShader", "BoingerPS", Resources.Shader);
            // Our shadow shader for our ball "shadow".  This is hard coded to send back black (R:0, G:0, B:0) at 50% opacity (A: 0.5).
            _pixelShaderShadow = Graphics.Shaders.CreateShader <GorgonPixelShader>("ShadowShader", "BoingerShadowPS", Resources.Shader);

            // Create the vertex input layout.
            // We need to create a layout for our vertex type because the shader won't know
            // how to interpret the data we're sending it otherwise.  This is why we need a
            // vertex shader before we even create the layout.
            _inputLayout = Graphics.Input.CreateInputLayout("InputLayout", typeof(BoingerVertex), _vertexShader);

            // Create the view port.
            // This just tells the renderer how big our display is.
            var view = new GorgonViewport(0, 0, _mainForm.ClientSize.Width, _mainForm.ClientSize.Height, 0.0f, 1.0f);

            // Load our textures from the resources.
            // This contains our textures for the walls and ball.
            _texture = Graphics.Textures.CreateTexture <GorgonTexture2D>("PlaneTexture", Resources.Texture);

            // Set up our view matrix.
            // Move the camera (view matrix) back 2.2 units.  This will give us enough room to see what's
            // going on.
            Matrix.Translation(0, 0, 2.2f, out _viewMatrix);

            // Set up our projection matrix.
            // This matrix is probably the cause of almost EVERY problem you'll ever run into in 3D programming.
            // Basically we're telling the renderer that we want to have a vertical FOV of 75 degrees, with the aspect ratio
            // based on our form width and height.  The final values indicate how to distribute Z values across depth (tip:
            // it's not linear).
            _projMatrix = Matrix.PerspectiveFovLH((75.0f).Radians(), _mainForm.Width / (float)_mainForm.Height, 0.125f, 500.0f);

            // Create our constant buffer and backing store.
            // Our constant buffers are how we send data to our shaders.  This one in particular will be responsible
            // for sending our world/view/projection matrix to the vertex shader.  The stream we're creating after
            // the constant buffer is our system memory store for the data.  Basically we write to the system
            // memory and then upload that data to the video card.  This is very different from how things used to
            // work, but allows a lot more flexibility.
            _wvpBuffer = Graphics.Buffers.CreateConstantBuffer("WVPBuffer", new GorgonConstantBufferSettings
            {
                SizeInBytes = Matrix.SizeInBytes
            });
            _wvpBufferStream = new GorgonDataStream(_wvpBuffer.SizeInBytes);

            // Create our planes.
            // Here's where we create the 2 planes for our rear wall and floor.  We set the texture size to texel units
            // because that's how the video card expects them.  However, it's a little hard to eyeball 0.67798223f by looking
            // at the texture image display, so we use the ToTexel function to determine our texel size.
            var textureSize = _texture.ToTexel(new Vector2(500, 500));

            _planes = new[] {
                new Plane(new Vector2(3.5f), new RectangleF(Vector2.Zero, textureSize)),
                new Plane(new Vector2(3.5f), new RectangleF(Vector2.Zero, textureSize))
            };

            // Set up default positions and orientations.
            _planes[0].Position = new Vector3(0, 0, 3.0f);
            _planes[1].Position = new Vector3(0, -3.5f, 3.5f);
            _planes[1].Rotation = new Vector3(90.0f, 0, 0);

            // Create our sphere.
            // Again, here we're using texels to align the texture coordinates to the other image
            // packed into the texture (atlasing).
            var textureOffset = _texture.ToTexel(new Vector2(516, 0));

            // This is to scale our texture coordinates because the actual image is much smaller
            // (256x256) than the full texture (1024x512).
            textureSize.X = 0.245f;
            textureSize.Y = 0.5f;
            // Give the sphere a place to live.
            _sphere = new Sphere(1.0f, textureOffset, textureSize)
            {
                Position = new Vector3(2.2f, 1.5f, 2.5f)
            };


            // Bind our objects to the pipeline and set default states.
            // At this point we need to give the graphics card a bunch of things
            // it needs to do its job.

            // Give our current input layout.
            Graphics.Input.Layout = _inputLayout;
            // We're drawing individual triangles for this (and this is usyally the case).
            Graphics.Input.PrimitiveType = PrimitiveType.TriangleList;

            // Bind our current vertex shader and send over our world/view/projection matrix
            // constant buffer.
            Graphics.Shaders.VertexShader.Current            = _vertexShader;
            Graphics.Shaders.VertexShader.ConstantBuffers[0] = _wvpBuffer;

            // Do the same with the pixel shader, only we're binding our texture to it as well.
            // We also need to bind a sampler to the texture because without it, the shader won't
            // know how to interpret the texture data (e.g. how will the shader know if the texture
            // is supposed to be bilinear filtered or point filtered?)
            Graphics.Shaders.PixelShader.Current            = _pixelShader;
            Graphics.Shaders.PixelShader.Resources[0]       = _texture;
            Graphics.Shaders.PixelShader.TextureSamplers[0] = GorgonTextureSamplerStates.LinearFilter;

            // Turn on alpha blending.
            Graphics.Output.BlendingState.States = GorgonBlendStates.ModulatedBlending;

            // Turn on depth writing.
            // This is our depth writing state.  When this is on, all polygon data sent to the card
            // will write to our depth buffer.  Normally we want this, but for translucent objects, it's
            // problematic....
            _depth = new GorgonDepthStencilStates
            {
                DepthComparison     = ComparisonOperator.LessEqual,
                IsDepthEnabled      = true,
                IsDepthWriteEnabled = true,
                IsStencilEnabled    = false
            };

            // Turn off depth writing.
            // So, we copy the depth state and turn off depth writing so that translucent objects
            // won't write to the depth buffer but can still read it.
            _noDepth = _depth;
            _noDepth.IsDepthWriteEnabled             = false;
            Graphics.Output.DepthStencilState.States = _depth;

            // Bind our swap chain and set up the default rasterizer states.
            Graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer);
            Graphics.Rasterizer.States = GorgonRasterizerStates.CullBackFace;
            Graphics.Rasterizer.SetViewport(view);

            // I know, there's a lot in here.  Thing is, if this were Direct 3D 11 code, it'd probably MUCH
            // more code and that's even before creating our planes and sphere.
        }