Ejemplo n.º 1
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);

            _gifAnim = new GifAnimator(SynchronizationContext.Current);
            _gallery = new ImageGallery(Font, DeviceDpi, _gifAnim);

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                // Load our image data.
                _gallery.LoadImages(GorgonApplication.StartupPath.FullName);


                // Begin our animation.
                _gifAnim.Animate(() =>
                {
                    using (System.Drawing.Graphics graphics = CreateGraphics())
                    {
                        _gallery.RefreshGif(graphics);
                    }
                });
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 2
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);

            try
            {
                Show();

                Cursor.Current = Cursors.WaitCursor;

                Initialize();

                _originalSize = new DX.Vector2(GroupControl1.ClientSize.Width, GroupControl2.ClientSize.Height);

                GorgonApplication.IdleMethod = Idle;
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Function to load the images for use with the example.
        /// </summary>
        /// <param name="codec">The codec for the images.</param>
        /// <returns><b>true</b> if files were loaded successfully, <b>false</b> if not.</returns>
        private static bool LoadImageFiles(IGorgonImageCodec codec)
        {
            DirectoryInfo dirInfo = GorgonExample.GetResourcePath(@"\Textures\PostProcess");

            FileInfo[] files = dirInfo.GetFiles("*.dds", SearchOption.TopDirectoryOnly);

            if (files.Length == 0)
            {
                GorgonDialogs.ErrorBox(null, $"No DDS images found in {dirInfo.FullName}.");
                GorgonApplication.Quit();
                return(false);
            }

            _images = new GorgonTexture2DView[files.Length];

            // Load all the DDS files from the resource area.
            for (int i = 0; i < files.Length; ++i)
            {
                _images[i] = GorgonTexture2DView.FromFile(_graphics,
                                                          files[i].FullName,
                                                          codec,
                                                          new GorgonTexture2DLoadOptions
                {
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable,
                    Name    = Path.GetFileNameWithoutExtension(files[i].Name)
                });
            }

            return(true);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Handles the KeyUp event of the Window control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
        private static void Window_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
            case Keys.Escape:
                GorgonApplication.Quit();
                break;

            case Keys.Right:
                ++_currentImage;

                if (_currentImage >= _images.Length)
                {
                    _currentImage = 0;
                }
                break;

            case Keys.Left:
                --_currentImage;

                if (_currentImage < 0)
                {
                    _currentImage = _images.Length - 1;
                }
                break;
            }
        }
Ejemplo n.º 5
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);

            try
            {
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);
                GorgonExample.ResourceBaseDirectory   = new DirectoryInfo(Settings.Default.ResourceLocation);

                // Create our virtual file system.
                _fileSystem = new GorgonFileSystem(Program.Log);
                _writer     = new GorgonFileSystemWriter(_fileSystem, Program.WriteDirectory.FullName);

                LoadText();

                labelFileSystem.Text    = $"{GorgonExample.GetResourcePath(@"FolderSystem\").FullName.Ellipses(100, true)} mounted as '/'.";
                labelWriteLocation.Text = $"{Program.WriteDirectory.FullName.Ellipses(100, true)} mounted as '/'";
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                CommandEnable(!string.Equals(_originalText, _changedText, StringComparison.CurrentCulture));
                UpdateInfo();
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handles the KeyUp event of the Window control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
        private static void Window_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
            case Keys.Escape:
                GorgonApplication.Quit();
                return;

            case Keys.F1:
                _showHelp = !_showHelp;
                return;
            }

            if (e.KeyCode != Keys.C)
            {
                return;
            }

            switch (_cloakController.Direction)
            {
            case CloakDirection.Cloak:
            case CloakDirection.CloakPulse:
                _cloakController.Uncloak();
                break;

            case CloakDirection.Uncloak:
            case CloakDirection.UncloakStopPulse:
            case CloakDirection.None:
                _cloakController.Cloak();
                break;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            GorgonExample.ShowStatistics = false;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                Show();
                Application.DoEvents();

                // Initialize Gorgon
                // Set it up so that we won't be rendering in the background, but allow the screensaver to activate.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);
                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "No suitable video adapter found in the system.\nGorgon requires a minimum of a Direct3D 11.4 capable video device.");
                }

                _graphics = new GorgonGraphics(adapters[0]);

                // Set the video mode.
                ClientSize = new Size(640, 400);
                _screen    = new GorgonSwapChain(_graphics,
                                                 this,
                                                 new GorgonSwapChainInfo("FunWithShapes SwapChain")
                {
                    Width  = ClientSize.Width,
                    Height = ClientSize.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _screen.AfterSwapChainResized += Screen_AfterSwapChainResized;
                _graphics.SetRenderTarget(_screen.RenderTargetView);
                _halfSize = new DX.Size2F(_screen.Width / 2.0f, _screen.Height / 2.0f);

                // Create our 2D renderer so we can draw stuff.
                _renderer = new Gorgon2D(_graphics);

                LabelPleaseWait.Visible = false;

                GorgonExample.LoadResources(_graphics);

                // Draw the image.
                DrawAPrettyPicture();
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 8
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);

            try
            {
                // Set our default cursor.
                _currentCursor = Resources.hand_icon;

                // Create our input factory.
                _rawInput = new GorgonRawInput(this);

                // Ensure that we have the necessary input devices.
                // This enumeration method could be used to retrieve only a single specific mouse out of many.
                if (_rawInput.EnumerateMice().Count == 0)
                {
                    GorgonDialogs.ErrorBox(this, "There were no mice detected on this computer.  The application requires a mouse.");
                    GorgonApplication.Quit();
                }

                // This enumeration method could be used to retrieve only a single specific keyboard out of many.
                if (_rawInput.EnumerateKeyboards().Count == 0)
                {
                    GorgonDialogs.ErrorBox(this, "There were no keyboards detected on this computer.  The application requires a keyboard.");
                    GorgonApplication.Quit();
                }

                // Get our input devices.
                CreateMouse();
                CreateKeyboard();

                // When the display area changes size, update the spray effect
                // and limit the mouse.
                panelDisplay.Resize += PanelDisplay_Resize;

                // Set up our spray object.
                _spray  = new Spray(panelDisplay.ClientSize);
                _cursor = new MouseCursor(panelDisplay)
                {
                    Hotspot = new Point(-16, -3)
                };

                // Set up our idle method.
                GorgonApplication.IdleMethod = Idle;
            }
            catch (Exception ex)
            {
                // We do this here instead of just calling the dialog because this
                // function will send the exception to the Gorgon log file.
                ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), GorgonApplication.Log);
                GorgonApplication.Quit();
            }
        }
Ejemplo n.º 9
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);

            try
            {
                // Picture box.
                _picture = new PictureBox
                {
                    Name = "pictureImage"
                };

                // Text display.
                _textDisplay = new TextBox
                {
                    Name = "textDisplay"
                };
                _textFont         = new Font("Consolas", 10.0f, FontStyle.Regular, GraphicsUnit.Point);
                _textDisplay.Font = _textFont;

                _instructions = new Label
                {
                    Name      = "labelInstructions",
                    Text      = "Double click on a file node in the tree to display it.",
                    AutoSize  = false,
                    TextAlign = ContentAlignment.MiddleCenter,
                    Dock      = DockStyle.Fill,
                    Font      = Font
                };

                // Add the instructions.
                splitFileSystem.Panel2.Controls.Add(_instructions);

                // Get the zip file provider.
                LoadZipFileSystemProvider();

                // Mount the physical file system directory.
                _fileSystem.Mount(Program.GetResourcePath(@"VFSRoot\"));

                // Mount the zip file into a sub directory.
                _fileSystem.Mount(Program.GetResourcePath("VFSRoot.zip"), "/ZipFile");

                // Fill the root of the tree.
                FillTree(null);
            }
            catch (Exception ex)
            {
                ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), Program.Log);
                GorgonApplication.Quit();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Windows the key down.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="KeyEventArgs" /> instance containing the event data.</param>
        private static void Window_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
            case Keys.Escape:
                GorgonApplication.Quit();
                return;

            case Keys.Z:
                _lightEffect.Lights[0].Position =
                    !e.Shift
                            ? new DX.Vector3(_lightEffect.Lights[0].Position.X, _lightEffect.Lights[0].Position.Y, _lightEffect.Lights[0].Position.Z + 1.0f)
                            : new DX.Vector3(_lightEffect.Lights[0].Position.X, _lightEffect.Lights[0].Position.Y, _lightEffect.Lights[0].Position.Z - 1.0f);
                break;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Handles the KeyUp event of the Window control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
        private static void Window_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
            case Keys.F1:
                _showHelp = !_showHelp;
                break;

            case Keys.S:
                GorgonExample.ShowStatistics = !GorgonExample.ShowStatistics;
                break;

            case Keys.Escape:
                GorgonApplication.Quit();
                break;
            }
        }
Ejemplo n.º 12
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);

            try
            {
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Create the assembly cache.
                _assemblies = new GorgonMefPlugInCache(GorgonApplication.Log);
                _assemblies.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.XInput.dll");

                // Create the plug services.
                IGorgonPlugInService pluginService = new GorgonMefPlugInService(_assemblies);

                // Create the gaming device driver factory.
                var factory = new GorgonGamingDeviceDriverFactory(pluginService, GorgonApplication.Log);

                // Create our factory.
                _driver = factory.LoadDriver("Gorgon.Input.XInput.GorgonXInputDriver");

                _stickPosition = new PointF[3];
                _sprayStates   = new SprayCan[3];

                // Get our list of active controllers.
                UpdateActiveControllers();

                // Get the graphics interface for our panel.
                _surface = new DrawingSurface(panelDisplay);

                // Set up our idle loop.
                GorgonApplication.IdleMethod += Idle;

                // Launch a background task to check for connected devices.
                Task.Run(CheckForConnectedDevices);
            }
            catch (Exception ex)
            {
                // We do this here instead of just calling the dialog because this
                // function will send the exception to the Gorgon log file.
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.KeyDown" /> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.KeyEventArgs" /> that contains the event data.</param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            if (e.KeyCode == Keys.Escape)
            {
                GorgonApplication.Quit();
            }

            if (e.KeyCode == Keys.F1)
            {
                _showHelp = !_showHelp;
            }

            if (e.KeyCode == Keys.S)
            {
                _showStats = !_showStats;
            }
        }
Ejemplo n.º 14
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;
            }
        }
Ejemplo n.º 15
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);

            try
            {
                Cursor = Cursors.WaitCursor;

                Visible = true;
                Application.DoEvents();

                // Initialize.
                Initialize();
            }
            catch (Exception ex)
            {
                ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), GorgonApplication.Log);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Function used to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

            // Build the form so we can actually show something.
            _mainForm = GorgonExample.Initialize(new DX.Size2(1280, 800), "Geometry Shaders");

            try
            {
                // Now we create and enumerate the list of video devices installed in the computer.
                // We must do this in order to tell Gorgon which video device we intend to use. Note that this method may be quite slow (particularly when running DEBUG versions of
                // Direct 3D). To counter this, this object and its Enumerate method are thread safe so this can be run in the background while keeping the main UI responsive.
                //
                // If no suitable device was found (no Direct 3D 11.4 support) in the computer, this method will return an empty list. However, if it succeeds, then the devices list
                // will be populated with an IGorgonVideoDeviceInfo for each suitable video device in the system.
                //
                // Using this method, we could also enumerate the WARP software rasterizer, and/of the D3D Reference device (only if the DEBUG functionality provided by the Windows
                // SDK is installed). These devices are typically used to determine if there's a driver error, and can be terribly slow to render (reference moreso than WARP). It is
                // recommended that these only be used in diagnostic scenarios only.
                IReadOnlyList <IGorgonVideoAdapterInfo> devices = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (devices.Count == 0)
                {
                    GorgonDialogs.ErrorBox(_mainForm, "This example requires a video adapter that supports Direct3D 11.4 or better.");
                    GorgonApplication.Quit();
                    return;
                }

                // Now we create the main graphics interface with the first applicable video device.
                _graphics = new GorgonGraphics(devices[0], log: GorgonApplication.Log);

                // Check to ensure that we can support the format required for our swap chain.
                // If a video device can't support this format, then the odds are good it won't render anything. Since we're asking for a very common display format, this will
                // succeed nearly 100% of the time. Regardless, it's good form to the check for a working display format prior to setting up the swap chain.
                //
                // This is also used to determine if a format can be used for other objects (e.g. a texture, render target, etc...) And like the swap chain format, it is also best
                // practice to check if the object you're creating supports the desired format.
                if (!_graphics.FormatSupport[BufferFormat.R8G8B8A8_UNorm].IsDisplayFormat)
                {
                    // We should never see this unless you've got some very esoteric hardware.
                    GorgonDialogs.ErrorBox(_mainForm, "We should not see this error.");
                    return;
                }

                // Finally, create a swap chain to display our output.
                // In this case we're setting up our swap chain to bind with our main window, and we use its client size to determine the width/height of the swap chain back buffers.
                // This width/height does not need to be the same size as the window, but, except for some scenarios, that would produce undesirable image quality.
                _swap = new GorgonSwapChain(_graphics,
                                            _mainForm,
                                            new GorgonSwapChainInfo("Main Swap Chain")
                {
                    Format = BufferFormat.R8G8B8A8_UNorm, Width = _mainForm.ClientSize.Width, Height = _mainForm.ClientSize.Height
                });

                // Assign events so we can update our projection with our window size.
                _swap.BeforeSwapChainResized += Swap_BeforeSwapChainResized;
                _swap.AfterSwapChainResized  += Swap_AfterSwapChainResized;

                // We'll need a depth buffer for this example, or else our pyramid will look weird when rotating as back faces will appear through front faces.
                // So, first we should check for support of a proper depth/stencil format.  That said, if we don't have this format, then we're likely not running hardware from the last decade or more.
                if (!_graphics.FormatSupport[BufferFormat.D24_UNorm_S8_UInt].IsDepthBufferFormat)
                {
                    GorgonDialogs.ErrorBox(_mainForm, "A 24 bit depth buffer is required for this example.");
                    return;
                }

                _depthStencil = GorgonDepthStencil2DView.CreateDepthStencil(_graphics,
                                                                            new GorgonTexture2DInfo
                {
                    Format  = BufferFormat.D24_UNorm_S8_UInt,
                    Binding = TextureBinding.DepthStencil,
                    Usage   = ResourceUsage.Default,
                    Width   = _swap.Width,
                    Height  = _swap.Height
                });

                // Load the shaders from a file on disc.
                LoadShaders();

                // Load the texture.
                _texture = GorgonTexture2DView.FromFile(_graphics,
                                                        Path.Combine(GorgonExample.GetResourcePath(@"Textures\GeometryShader\").FullName, "GSTexture.png"),
                                                        new GorgonCodecPng());

                // Create our builders so we can compose a draw call and pipeline state.
                _drawCallBuilder  = new GorgonDrawCallBuilder();
                _pipeStateBuilder = new GorgonPipelineStateBuilder(_graphics);

                // Create a constant buffer so we can adjust the positioning of the data.
                DX.Matrix.PerspectiveFovLH((65.0f).ToRadians(), (float)_swap.Width / _swap.Height, 0.125f, 1000.0f, out _projection);
                _vsConstants = GorgonConstantBufferView.CreateConstantBuffer(_graphics,
                                                                             new GorgonConstantBufferInfo("WorldProjection CBuffer")
                {
                    SizeInBytes = (DX.Matrix.SizeInBytes * 2) + DX.Vector4.SizeInBytes
                });
                _vsConstants.Buffer.SetData(ref _projection, copyMode: CopyMode.Discard);
                _vsConstants.Buffer.SetData(ref _worldMatrix, 64, CopyMode.NoOverwrite);

                // Create a draw call so we actually have something we can draw.
                _drawCall = _drawCallBuilder.VertexRange(0, 3)
                            .PipelineState(_pipeStateBuilder.PixelShader(_pixelShader)
                                           .VertexShader(_bufferless)
                                           .GeometryShader(_geometryShader)
                                           .DepthStencilState(GorgonDepthStencilState.DepthEnabled))
                            .ShaderResource(ShaderType.Pixel, _texture)
                            .ConstantBuffer(ShaderType.Vertex, _vsConstants)
                            .ConstantBuffer(ShaderType.Geometry, _vsConstants)
                            .Build();
                // Finally set our swap chain as the active rendering target and the depth/stencil buffer.
                _graphics.SetRenderTarget(_swap.RenderTargetView, _depthStencil);

                GorgonExample.LoadResources(_graphics);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Form.Load"></see> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                GorgonExample.PlugInLocationDirectory = new DirectoryInfo(Settings.Default.PlugInLocation);

                // Load the assembly.
                _assemblyCache = new GorgonMefPlugInCache(GorgonApplication.Log);

                // Create the plugin service.
                IGorgonPlugInService plugInService = new GorgonMefPlugInService(_assemblyCache);

                // Create the factory to retrieve gaming device drivers.
                var factory = new GorgonGamingDeviceDriverFactory(plugInService);

                // Create the raw input interface.
                _input = new GorgonRawInput(this, GorgonApplication.Log);

                // Get available gaming device driver plug ins.
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.DirectInput.dll");
                _assemblyCache.LoadPlugInAssemblies(GorgonExample.GetPlugInPath().FullName, "Gorgon.Input.XInput.dll");

                _drivers = factory.LoadAllDrivers();

                _joystickList = new List <IGorgonGamingDevice>();

                // Get all gaming devices from the drivers.
                foreach (IGorgonGamingDeviceDriver driver in _drivers)
                {
                    IReadOnlyList <IGorgonGamingDeviceInfo> infoList = driver.EnumerateGamingDevices(true);

                    foreach (IGorgonGamingDeviceInfo info in infoList)
                    {
                        IGorgonGamingDevice device = driver.CreateGamingDevice(info);

                        // Turn off dead zones for this example.
                        foreach (GorgonGamingDeviceAxis axis in device.Axis)
                        {
                            axis.DeadZone = GorgonRange.Empty;
                        }

                        _joystickList.Add(device);
                    }
                }

                // Create mouse.
                _mouse = new GorgonRawMouse();

                // Create the graphics interface.
                ClientSize = Settings.Default.Resolution;

                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters();
                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);
                _screen   = new GorgonSwapChain(_graphics, this, new GorgonSwapChainInfo("INeedYourInput Swapchain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                if (!Settings.Default.IsWindowed)
                {
                    _screen.EnterFullScreen();
                }

                // For the backup image. Used to make it as large as the monitor that we're on.
                var currentScreen = Screen.FromHandle(Handle);

                // Relocate the window to the center of the screen.
                Location = new Point(currentScreen.Bounds.Left + (currentScreen.WorkingArea.Width / 2) - (ClientSize.Width / 2),
                                     currentScreen.Bounds.Top + (currentScreen.WorkingArea.Height / 2) - (ClientSize.Height / 2));


                // Create the 2D renderer.
                _2D = new Gorgon2D(_graphics);

                // Create the text font.
                var fontFactory = new GorgonFontFactory(_graphics);
                _font = fontFactory.GetFont(new GorgonFontInfo("Arial", 9.0f, FontHeightMode.Points, "Arial 9pt")
                {
                    FontStyle        = FontStyle.Bold,
                    AntiAliasingMode = FontAntiAliasMode.AntiAlias
                });

                // Create text sprite.
                _messageSprite = new GorgonTextSprite(_font, "Using mouse and keyboard (Windows Forms).")
                {
                    Color = Color.Black
                };

                // Create a back buffer.
                _backBuffer = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo("Backbuffer storage")
                {
                    Width  = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                });
                _backBuffer.Clear(Color.White);
                _backBufferView = _backBuffer.GetShaderResourceView();

                // Clear our backup image to white to match our primary screen.
                using (IGorgonImage image = new GorgonImage(new GorgonImageInfo(ImageType.Image2D, _screen.Format)
                {
                    Width = _screen.Width,
                    Height = _screen.Height,
                    Format = _screen.Format
                }))
                {
                    image.Buffers[0].Fill(0xff);
                    _backupImage = image.ToTexture2D(_graphics,
                                                     new GorgonTexture2DLoadOptions
                    {
                        Binding = TextureBinding.None,
                        Usage   = ResourceUsage.Staging
                    });
                }

                // Set gorgon events.
                _screen.BeforeSwapChainResized += BeforeSwapChainResized;
                _screen.AfterSwapChainResized  += AfterSwapChainResized;

                // Enable the mouse.
                Cursor = Cursors.Cross;
                _mouse.MouseButtonDown += MouseInput;
                _mouse.MouseMove       += MouseInput;
                _mouse.MouseWheelMove  += (sender, args) =>
                {
                    _radius += args.WheelDelta.Sign();

                    if (_radius < 2.0f)
                    {
                        _radius = 2.0f;
                    }
                    if (_radius > 10.0f)
                    {
                        _radius = 10.0f;
                    }
                };

                // Set the mouse position.
                _mouse.Position = new Point(ClientSize.Width / 2, ClientSize.Height / 2);

                _noBlending = _blendBuilder.BlendState(GorgonBlendState.NoBlending)
                              .Build();
                _inverted = _blendBuilder.BlendState(GorgonBlendState.Inverted)
                            .Build();

                // Set up blending states for our pen.
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _currentBlend = _drawModulatedBlend = _blendBuilder.BlendState(blendStateBuilder
                                                                               .ResetTo(GorgonBlendState.Default)
                                                                               .DestinationBlend(alpha: Blend.One)
                                                                               .Build())
                                                      .Build();

                _drawAdditiveBlend = _blendBuilder.BlendState(blendStateBuilder
                                                              .ResetTo(GorgonBlendState.Additive)
                                                              .DestinationBlend(alpha: Blend.One)
                                                              .Build())
                                     .Build();

                _drawNoBlend = _blendBuilder.BlendState(blendStateBuilder
                                                        .ResetTo(GorgonBlendState.NoBlending)
                                                        .DestinationBlend(alpha: Blend.One)
                                                        .Build())
                               .Build();

                GorgonApplication.IdleMethod = Gorgon_Idle;
            }
            catch (ReflectionTypeLoadException refEx)
            {
                string refErr = string.Join("\n", refEx.LoaderExceptions.Select(item => item.Message));
                GorgonDialogs.ErrorBox(this, refErr);
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
        }
Ejemplo n.º 18
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
            {
                GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

                // Load the custom codec.
                if (!LoadCodec())
                {
                    GorgonDialogs.ErrorBox(this, "Unable to load the image codec plug in.");
                    GorgonApplication.Quit();
                    return;
                }


                // Set up the graphics interface.
                // 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]);

                _swap = new GorgonSwapChain(_graphics,
                                            this,
                                            new GorgonSwapChainInfo("Codec PlugIn SwapChain")
                {
                    Width  = ClientSize.Width,
                    Height = ClientSize.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                _graphics.SetRenderTarget(_swap.RenderTargetView);

                // Load the image to use as a texture.
                IGorgonImageCodec png = new GorgonCodecPng();
                _image = png.LoadFromFile(Path.Combine(GorgonExample.GetResourcePath(@"Textures\CodecPlugIn\").FullName, "SourceTexture.png"));

                GorgonExample.LoadResources(_graphics);

                ConvertImage();

                GorgonApplication.IdleMethod = Idle;
            }
            catch (Exception ex)
            {
                GorgonExample.HandleException(ex);
                GorgonApplication.Quit();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }