Exemple #1
0
 /// <summary>
 /// Function to build the shaders required for the application.
 /// </summary>
 private static void LoadShaders()
 {
     _renderer.ShaderCache["VertexShader"]  = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, Resources.Shaders, "PrimVS", true);
     _renderer.ShaderCache["PixelShader"]   = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.Shaders, "PrimPS", true);
     _renderer.ShaderCache["BumpMapShader"] = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.Shaders, "PrimPSBump", true);
     _renderer.ShaderCache["WaterShader"]   = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.Shaders, "PrimPSWaterBump", true);
 }
        /// <summary>Function called to initialize the effect.</summary>
        /// <remarks>Applications must implement this method to ensure that any required resources are created, and configured for the effect.</remarks>
        protected override void OnInitialize()
        {
            // Initialize the default look up table.
            using (IGorgonImage image = new GorgonImage(new GorgonImageInfo(ImageType.Image1D, BufferFormat.R8G8B8A8_UNorm)
            {
                Width = 3
            }))
            {
                image.ImageData.ReadAs <int>(0) = GorgonColor.RedPure.ToABGR();
                image.ImageData.ReadAs <int>(4) = GorgonColor.BluePure.ToABGR();
                image.ImageData.ReadAs <int>(8) = GorgonColor.GreenPure.ToABGR();

                _defaultLut = GorgonTexture1DView.CreateTexture(Graphics, new GorgonTexture1DInfo("Default Spectral LUT")
                {
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable,
                    Width   = 3
                }, image);
            }

            _chromeAbShader       = GorgonShaderFactory.Compile <GorgonPixelShader>(Graphics, Resources.ChromaticAberration, "ChromaticAberration", GorgonGraphics.IsDebugEnabled);
            _simpleChromeAbShader = GorgonShaderFactory.Compile <GorgonPixelShader>(Graphics, Resources.ChromaticAberration, "ChromaticAberrationSimple", GorgonGraphics.IsDebugEnabled);

            _settings = GorgonConstantBufferView.CreateConstantBuffer(Graphics, new GorgonConstantBufferInfo("Chromatic Aberration Settings Buffer")
            {
                SizeInBytes = DX.Vector4.SizeInBytes,
                Usage       = ResourceUsage.Default
            });
        }
Exemple #3
0
        /// <summary>
        /// Function to initialize the example and prepare the required components.
        /// </summary>
        private static void Initialize()
        {
            // We will need to access the graphics device in order to use compute functionality, so we'll use the first usable device in the system.
            // Find out which devices we have installed in the system.
            IReadOnlyList <IGorgonVideoAdapterInfo> deviceList = GorgonGraphics.EnumerateAdapters();

            Console.WriteLine("Enumerating video devices...");

            IGorgonVideoAdapterInfo firstDevice = deviceList.FirstOrDefault(item => item.FeatureSet >= FeatureSet.Level_12_0);

            // If a device with a feature set of at least 12.0 not found, then we cannot run this example. The compute engine requires a minimum
            // of feature level 12.0 to run.
            if (firstDevice == null)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("No Level 12.0 or better adapters found in the system. This example requires a FeatureLevel 12.0 or better adapter.");
                Console.ResetColor();
                return;
            }

            Console.WriteLine($"Using the '{firstDevice.Name}' video device.\n");

            // We have to create a graphics interface to allow the compute engine to communicate with the GPU.
            _graphics = new GorgonGraphics(firstDevice);

            // We will also need to compile a compute shader so we can actually perform the work.
            Console.WriteLine("Compiling the compute shader (SimpleCompute)...");
            _computeShader = GorgonShaderFactory.Compile <GorgonComputeShader>(_graphics, Resources.ComputeShader, "SimpleCompute");

            // Finally, the star of the show, the compute engine.
            Console.WriteLine("Creating compute engine...");
            _engine = new GorgonComputeEngine(_graphics);
        }
Exemple #4
0
        /// <summary>
        /// Function to create a new vertex and pixel shader for use when rendering our triangle.
        /// </summary>
        private static void CreateShaders()
        {
            // We compile the vertex shader program into byte code for use by the GPU.  When we do this we have to provide the shader source code, and the name of the function
            // that represents the entry point for the vertex shader.
            _vertexShader = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, Resources.MiniTriShaders, "MiniTriVS");

            // Next, we'll compile the pixel shader.
            _pixelShader = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.MiniTriShaders, "MiniTriPS");
        }
Exemple #5
0
        /// <summary>
        /// Function to load the shaders for the application.
        /// </summary>
        private static void LoadShaders()
        {
            string shaderCode = Resources.Shaders;

            _bufferless     = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, shaderCode, "BufferlessVs", Debugger.IsAttached);
            _vertexShader   = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, shaderCode, "VsMain", Debugger.IsAttached);
            _pixelShader    = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, shaderCode, "PsMain", Debugger.IsAttached);
            _geometryShader = GorgonShaderFactory.Compile <GorgonGeometryShader>(_graphics, shaderCode, "GsMain", Debugger.IsAttached);
        }
        /// <summary>
        /// Function to load all the resources from the file system.
        /// </summary>
        /// <returns>A task for asynchronous operation.</returns>
        public async Task LoadResourcesAsync()
        {
            foreach (KeyValuePair <string, GorgonTexture2DView> texture in _textures)
            {
                texture.Value.Dispose();
            }

            _textures.Clear();
            IReadOnlyDictionary <string, IGorgonImage> images = await Task.Run(() => LoadImageData("/images/"));

            foreach (KeyValuePair <string, IGorgonImage> image in images)
            {
                var texture = GorgonTexture2DView.CreateTexture(_graphics, new GorgonTexture2DInfo(image.Key)
                {
                    Width      = image.Value.Width,
                    Height     = image.Value.Height,
                    Format     = image.Value.Format,
                    ArrayCount = image.Value.ArrayCount,
                    MipLevels  = image.Value.MipCount,
                    Binding    = TextureBinding.ShaderResource,
                    Usage      = ResourceUsage.Immutable
                }, image.Value);

                _textures.Add(Path.GetFileNameWithoutExtension(image.Key), texture);
            }

            Sprites = await Task.Run(() => LoadSpriteData("/sprites/"));

            await Task.Run(() =>
            {
                _vertexShaders["PlanetVS"]     = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, Resources.Shaders3D, "PrimVS", GorgonGraphics.IsDebugEnabled);
                _pixelShaders["PlanetPS"]      = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.Shaders3D, "PrimPSBump", GorgonGraphics.IsDebugEnabled);
                _pixelShaders["PlanetCloudPS"] = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.Shaders3D, "PrimPSNoBump", GorgonGraphics.IsDebugEnabled);
            });

            await Task.Run(() => Generate3DModels());

            await Task.Run(() => BuildPostProcessCompositors());

            // No need to make this async, should be plenty fast.
            GenerateAnimations();
        }
Exemple #7
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                // Find out which devices we have installed in the system.
                IReadOnlyList <IGorgonVideoAdapterInfo> deviceList = GorgonGraphics.EnumerateAdapters();

                if (deviceList.Count == 0)
                {
                    GorgonDialogs.ErrorBox(this, "There are no suitable video adapters available in the system. This example is unable to continue and will now exit.");
                    GorgonApplication.Quit();
                    return;
                }

                _graphics = new GorgonGraphics(deviceList[0]);
                _renderer = new GraphicsRenderer(_graphics);
                _renderer.SetPanel(PanelDisplay);

                // Load the compute shader.
#if DEBUG
                _sobelShader = GorgonShaderFactory.Compile <GorgonComputeShader>(_graphics, Resources.ComputeShader, "SobelCS", true);
#else
                _sobelShader = GorgonShaderFactory.Compile <GorgonComputeShader>(_graphics, Resources.ComputeShader, "SobelCS");
#endif
                _sobel = new Sobel(_graphics, _sobelShader);

                GorgonApplication.IdleMethod = Idle;
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Exemple #8
0
 /// <summary>
 /// Function to create a shader for use with the effect.
 /// </summary>
 /// <typeparam name="T">The type of shader. Must inherit from <see cref="GorgonShader"/>.</typeparam>
 /// <param name="shaderSource">The source code for the shader.</param>
 /// <param name="entryPoint">The entry point function in the shader to execute.</param>
 /// <returns>A new shader.</returns>
 protected T CompileShader <T>(string shaderSource, string entryPoint)
     where T : GorgonShader => GorgonShaderFactory.Compile <T>(Graphics, shaderSource, entryPoint, GorgonGraphics.IsDebugEnabled, Macros);
Exemple #9
0
 /// <summary>Function called to create the pixel shader.</summary>
 /// <param name="graphics">The graphics interface used to create the shader.</param>
 /// <param name="shader">The source code for the shader.</param>
 /// <returns>The pixel shader for the viewer.</returns>
 protected override GorgonPixelShader OnGetPixelShader(GorgonGraphics graphics, string shader) => GorgonShaderFactory.Compile <GorgonPixelShader>(graphics, shader, "Gorgon2DTextureArrayView");
Exemple #10
0
        /// <summary>
        /// Function to initialize the blitter.
        /// </summary>
        public void Initialize()
        {
            try
            {
                // We've been initialized, so leave.
                if ((_vertexShader != null) || (Interlocked.Increment(ref _initializedFlag) > 1))
                {
                    // Trap other threads until we're done initializing and then release them.
                    while ((_vertexShader == null) && (_initializedFlag > 0))
                    {
                        var wait = new SpinWait();
                        wait.SpinOnce();
                    }

                    return;
                }


                _vertexShader = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics,
                                                                                 Resources.GraphicsShaders,
                                                                                 "GorgonBltVertexShader",
                                                                                 GorgonGraphics.IsDebugEnabled);
                _pixelShader = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics,
                                                                               Resources.GraphicsShaders,
                                                                               "GorgonBltPixelShader",
                                                                               GorgonGraphics.IsDebugEnabled);

                _inputLayout = GorgonInputLayout.CreateUsingType <BltVertex>(_graphics, _vertexShader);

                _vertexBufferBindings = new GorgonVertexBufferBindings(_inputLayout)
                {
                    [0] = GorgonVertexBufferBinding.CreateVertexBuffer <BltVertex>(_graphics,
                                                                                   4,
                                                                                   ResourceUsage.Dynamic,
                                                                                   bufferName: "Gorgon Blitter Vertex Buffer")
                };

                _wvpBuffer = GorgonConstantBufferView.CreateConstantBuffer(_graphics,
                                                                           new GorgonConstantBufferInfo("Gorgon Blitter WVP Buffer")
                {
                    Usage       = ResourceUsage.Dynamic,
                    SizeInBytes = DX.Matrix.SizeInBytes
                });

                // Finish initalizing the draw call.
                _pipelineState = _pipeStateBuilder.VertexShader(_vertexShader)
                                 .BlendState(GorgonBlendState.NoBlending)
                                 .DepthStencilState(GorgonDepthStencilState.Default)
                                 .PrimitiveType(PrimitiveType.TriangleStrip)
                                 .RasterState(GorgonRasterState.Default)
                                 .PixelShader(_pixelShader)
                                 .Build();

                _drawCallBuilder.VertexBuffers(_inputLayout, _vertexBufferBindings)
                .VertexRange(0, 4)
                .SamplerState(ShaderType.Pixel, GorgonSamplerState.Default)
                .PipelineState(_pipelineState)
                .ConstantBuffer(ShaderType.Vertex, _wvpBuffer);


                _defaultTexture = Resources.White_2x2.ToTexture2D(_graphics,
                                                                  new GorgonTexture2DLoadOptions
                {
                    Name    = "Gorgon_Default_White_Texture",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                }).GetShaderResourceView();
            }
            finally
            {
                Interlocked.Decrement(ref _initializedFlag);
            }
        }
Exemple #11
0
        /// <summary>
        /// Function to initialize the GPU resource objects.
        /// </summary>
        private static void InitializeGpuResources()
        {
            _graphics = CreateGraphicsInterface();

            // If we couldn't create the graphics interface, then leave.
            if (_graphics == null)
            {
                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 = new GorgonSwapChain(_graphics,
                                        _mainForm,
                                        new GorgonSwapChainInfo("Main")
            {
                // Set up for 32 bit RGBA normalized display.
                Format = BufferFormat.R8G8B8A8_UNorm,
                Width  = Settings.Default.Resolution.Width,
                Height = Settings.Default.Resolution.Height
            });

            // Build the depth buffer for our swap chain.
            BuildDepthBuffer(_swap.Width, _swap.Height);


            if (!Settings.Default.IsWindowed)
            {
                // Get the output for the main window.
                var currentScreen             = Screen.FromControl(_mainForm);
                IGorgonVideoOutputInfo output = _graphics.VideoAdapter.Outputs[currentScreen.DeviceName];

                // If we've asked for full screen mode, then locate the correct video mode and set us up.
                _selectedVideoMode = new GorgonVideoMode(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height, BufferFormat.R8G8B8A8_UNorm);
                _swap.EnterFullScreen(in _selectedVideoMode, output);
            }

            // Handle resizing because the projection matrix and depth buffer needs to be updated to reflect the new view size.
            _swap.BeforeSwapChainResized += Swap_BeforeResized;
            _swap.AfterSwapChainResized  += Swap_AfterResized;

            // Set the current render target output so we can see something.
            _graphics.SetRenderTarget(_swap.RenderTargetView, _depthBuffer);

            // 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 = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, Resources.Shader, "BoingerVS");

            // 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 = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.Shader, "BoingerPS");

            // 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 = GorgonInputLayout.CreateUsingType <BoingerVertex>(_graphics, _vertexShader);

            // Resources are stored as System.Drawing.Bitmap files, so we need to convert into an IGorgonImage so we can upload it to a texture.
            // We also will generate mip-map levels for this image so that scaling the texture will look better.
            using (IGorgonImage image = Resources.Texture.ToGorgonImage())
            {
                _texture = image.ToTexture2D(_graphics,
                                             new GorgonTexture2DLoadOptions
                {
                    Usage = ResourceUsage.Immutable,
                    Name  = "Texture"
                })
                           .GetShaderResourceView();
            }

            // Create our constant buffer.
            // 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.
            _wvpBuffer = GorgonConstantBufferView.CreateConstantBuffer(_graphics,
                                                                       new GorgonConstantBufferInfo("WVPBuffer")
            {
                Usage       = ResourceUsage.Dynamic,
                SizeInBytes = DX.Matrix.SizeInBytes
            });
            // This one will hold our material information.
            _materialBuffer = GorgonConstantBufferView.CreateConstantBuffer(_graphics,
                                                                            new GorgonConstantBufferInfo("MaterialBuffer")
            {
                Usage       = ResourceUsage.Dynamic,
                SizeInBytes = Unsafe.SizeOf <GorgonColor>()
            });
            GorgonColor defaultMaterialColor = GorgonColor.White;

            _materialBuffer.Buffer.SetData(ref defaultMaterialColor);

            GorgonExample.LoadResources(_graphics);
        }
Exemple #12
0
        /// <summary>
        /// Function used to build the resources required by the volume renderer.
        /// </summary>
        public void CreateResources()
        {
            _cubeVs        = GorgonShaderFactory.Compile <GorgonVertexShader>(_graphics, Resources.VolumeRenderShaders, "VolumeVS", true);
            _cubePosShader = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.VolumeRenderShaders, "VolumePositionPS", true);
            _cubeDirShader = GorgonShaderFactory.Compile <GorgonPixelShader>(_graphics, Resources.VolumeRenderShaders, "VolumeRayCastPS", true);
            _inputLayout   = GorgonInputLayout.CreateUsingType <CubeVertex>(_graphics, _cubeVs);
            _cube          = new Cube(_graphics, _inputLayout);

            _cubeTransform = new GorgonConstantBuffer(_graphics, new GorgonConstantBufferInfo
            {
                SizeInBytes = DX.Matrix.SizeInBytes
            });

            _volumeRayParams = new GorgonConstantBuffer(_graphics, new GorgonConstantBufferInfo
            {
                SizeInBytes = Unsafe.SizeOf <VolumeRayParameters>()
            });

            _volumeScaleFactor = new GorgonConstantBuffer(_graphics, new GorgonConstantBufferInfo
            {
                SizeInBytes = DX.Vector4.SizeInBytes
            });

            // Our camera is never changing, so we only need to define it here.
            DX.Matrix.Translation(0, 0, 1.5f, out _view);
            ResizeRenderRegion();

            UpdateCubeTransform();

            var pipelineBuilder = new GorgonPipelineStateBuilder(_graphics);
            var drawBuilder     = new GorgonDrawIndexCallBuilder();

            pipelineBuilder
            .PixelShader(_cubePosShader)
            .VertexShader(_cubeVs);

            // Position draw calls.
            _cubePosDrawCull = drawBuilder
                               .ConstantBuffer(ShaderType.Vertex, _cubeTransform.GetView())
                               .ConstantBuffer(ShaderType.Vertex, _volumeScaleFactor.GetView(), 1)
                               .PipelineState(pipelineBuilder)
                               .IndexBuffer(_cube.IndexBuffer, indexCount: _cube.IndexBuffer.IndexCount)
                               .VertexBuffer(_inputLayout, _cube.VertexBuffer[0])
                               .Build();

            pipelineBuilder
            .RasterState(GorgonRasterState.CullFrontFace);

            _cubePosDrawFrontCull = drawBuilder
                                    .PipelineState(pipelineBuilder)
                                    .Build();

            // Raycasting draw call.
            pipelineBuilder
            .PixelShader(_cubeDirShader)
            .RasterState(GorgonRasterState.Default);

            _cubeDirDrawCall = drawBuilder
                               .ConstantBuffer(ShaderType.Pixel, _volumeRayParams.GetView(), 0)
                               .PipelineState(pipelineBuilder)
                               .Build();
        }