Esempio n. 1
0
        /// <summary>
        /// Function to enumerate and update the active controllers list.
        /// </summary>
        private void UpdateActiveControllers()
        {
            IReadOnlyList <IGorgonGamingDeviceInfo> controllers = _driver.EnumerateGamingDevices(true);

            // Enumerate the active controllers.  We'll only take 3 of the 4 available xbox controllers, and only if they have the correct capabilities.
            _controllers = controllers.Where(item => (item.Capabilities & GamingDeviceCapabilityFlags.SupportsThrottle) == GamingDeviceCapabilityFlags.SupportsThrottle &&
                                             (item.Capabilities & GamingDeviceCapabilityFlags.SupportsSecondaryXAxis) == GamingDeviceCapabilityFlags.SupportsSecondaryXAxis &&
                                             (item.Capabilities & GamingDeviceCapabilityFlags.SupportsSecondaryYAxis) == GamingDeviceCapabilityFlags.SupportsSecondaryYAxis &&
                                             (item.Capabilities & GamingDeviceCapabilityFlags.SupportsVibration) == GamingDeviceCapabilityFlags.SupportsVibration &&
                                             (item.Capabilities & GamingDeviceCapabilityFlags.SupportsRudder) == GamingDeviceCapabilityFlags.SupportsRudder)
                           .Take(3)
                           .Select(item => _driver.CreateGamingDevice(item)).ToArray();

            for (int i = 0; i < _controllers.Count; i++)
            {
                if (!_controllers[i].IsConnected)
                {
                    continue;
                }

                // Start at a random spot.
                _stickPosition[i] = new Point(GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Width - 64),
                                              GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Height - 64));

                // Turn off spray for all controllers.
                _sprayStates[i] = new SprayCan(_controllers[i], i);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Spray" /> class.
        /// </summary>
        /// <param name="size">Size of the drawing surface.</param>
        public Spray(Size size)
        {
            Surface   = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
            _graphics = DrawingGraphics.FromImage(Surface);

            _brushes = new SolidBrush[64];

            for (int i = 0; i < _brushes.Length; ++i)
            {
                _brushes[i] = new SolidBrush(Color.FromArgb(GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255)));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Function to randomly "spray" a point on the surface.
        /// </summary>
        /// <param name="point">Origin point for the spray.</param>
        public void SprayPoint(Point point)
        {
            var   randomArea  = new Point(GorgonRandom.RandomInt32(-10, 10), GorgonRandom.RandomInt32(-10, 10));
            Color randomColor = Color.FromArgb(GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255));

            using (var brush = new SolidBrush(randomColor))
            {
                _graphics.FillEllipse(brush, new Rectangle(point.X + randomArea.X
                                                           , point.Y + randomArea.Y
                                                           , 10
                                                           , 10));
            }
        }
Esempio n. 4
0
        public void Test2ViewsSameShaderStage()
        {
            GorgonTexture2D texture = null;

            _framework.CreateTestScene(Shaders, Shaders, true);

            try
            {
                using (var data = new GorgonImageData(new GorgonTexture2DSettings
                {
                    Width = 256,
                    Height = 256,
                    ArrayCount = 1,
                    Format = BufferFormat.R8G8B8A8,
                    MipCount = 1,
                    ShaderViewFormat = BufferFormat.R8G8B8A8_Int,
                    AllowUnorderedAccessViews = false,
                    Usage = BufferUsage.Default
                }))
                {
                    for (int i = 0; i < 5000; i++)
                    {
                        data.Buffers[0].Data.Position = ((GorgonRandom.RandomInt32(0, 256) * data.Buffers[0].PitchInformation.RowPitch)
                                                         + GorgonRandom.RandomInt32(0, 256) * 4);
                        data.Buffers[0].Data.Write((int)((GorgonRandom.RandomSingle() * 2.0f - 1.0f) * (Int32.MaxValue - 2)));
                    }

                    texture = _framework.Graphics.Textures.CreateTexture <GorgonTexture2D>("Test2D", data);
                }

                GorgonTextureShaderView view = texture.GetShaderView(BufferFormat.R8G8B8A8_UIntNormal);

                _framework.Graphics.Shaders.PixelShader.Resources[0] = texture;
                _framework.Graphics.Shaders.PixelShader.Resources[1] = view;

                Assert.IsTrue(_framework.Run() == DialogResult.Yes);
            }
            finally
            {
                if (texture != null)
                {
                    texture.Dispose();
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);
            FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "Post Processing");

            try
            {
                IReadOnlyList <IGorgonVideoAdapterInfo> videoDevices = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (videoDevices.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate,
                                              "Gorgon requires at least a Direct3D 11.4 capable video device.\nThere is no suitable device installed on the system.");
                }

                // Find the best video device.
                _graphics = new GorgonGraphics(videoDevices.OrderByDescending(item => item.FeatureSet).First());

                _screen = new GorgonSwapChain(_graphics,
                                              window,
                                              new GorgonSwapChainInfo("Gorgon2D Effects Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                // Tell the graphics API that we want to render to the "screen" swap chain.
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                // Initialize the renderer so that we are able to draw stuff.
                _renderer = new Gorgon2D(_graphics);

                GorgonExample.LoadResources(_graphics);

                // Load the Gorgon logo to show in the lower right corner.
                var ddsCodec = new GorgonCodecDds();

                // Import the images we'll use in our post process chain.
                if (!LoadImageFiles(ddsCodec))
                {
                    return(window);
                }

                // Initialize the effects that we'll use for compositing, and the compositor itself.
                InitializeEffects();

                // Set up our quick and dirty GUI.
                _buttons = new Button[_compositor.Passes.Count];
                LayoutGUI();

                // Select a random image to start
                _currentImage = GorgonRandom.RandomInt32(0, _images.Length - 1);

                window.KeyUp     += Window_KeyUp;
                window.MouseUp   += Window_MouseUp;
                window.MouseMove += Window_MouseMove;
                window.MouseDown += Window_MouseDown;
                window.IsLoaded   = true;

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
Esempio n. 6
0
        public void BindRawBuffer()
        {
            _framework.CreateTestScene(_rbShaders, _rbShaders, false);

            var   values = new byte[256 * 256 * 4];
            float angle  = 0.0f;

            using (var buffer = _framework.Graphics.Buffers.CreateBuffer("RB", new GorgonBufferSettings
            {
                AllowRawViews = true,
                AllowShaderViews = true,
                DefaultShaderViewFormat = BufferFormat.R32_UInt,
                SizeInBytes = values.Length
            }))
            {
                _framework.Graphics.Shaders.PixelShader.Resources[0] = buffer;

                _framework.IdleFunc = () =>
                {
                    using (var stream = new GorgonDataStream(values))
                    {
                        float rads = (angle * GorgonRandom.RandomSingle(8.0f, 32.0f) + 16.0f).Radians();
                        float x    = 128 + GorgonRandom.RandomInt32(0, 5) + (rads * rads.Cos());
                        float y    = 128 + GorgonRandom.RandomInt32(0, 5) + (rads * rads.Sin());

                        if (x > 255)
                        {
                            x = 255;
                        }

                        if (y > 255)
                        {
                            y = 255;
                        }

                        if (x < 0)
                        {
                            x = 0;
                        }

                        if (y < 0)
                        {
                            y = 0;
                        }

                        int pos = (((int)y * 1024) + ((int)x * 4));

                        for (int i = 0; i < pos - 50; i++)
                        {
                            values[i] = (byte)(values[i] * 0.95f);
                        }

                        values[pos]     = 255;
                        values[pos + 3] = values[pos + 2] = values[pos + 1] = (byte)GorgonRandom.RandomInt32(64, 128);

                        angle += GorgonRandom.RandomSingle(1, 180) * GorgonTiming.Delta;
                        if (angle > 360.0f)
                        {
                            angle = 0.0f;
                        }

                        buffer.Update(stream);

                        return(false);
                    }
                };
                _framework.MaxTimeout = 15000;
                _framework.Run();
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Function to perform the transformation of the balls.
        /// </summary>
        /// <param name="frameTime">Frame delta time.</param>
        private static void Transform(float frameTime)
        {
            // Transform balls.
            for (int i = 0; i < _ballCount; i++)
            {
                Ball currentBall = _ballList[i];

                currentBall.Position  = Vector2.Add(currentBall.Position, Vector2.Multiply(currentBall.PositionDelta, frameTime));
                currentBall.Scale    += currentBall.ScaleDelta * frameTime;
                currentBall.Rotation += currentBall.RotationDelta * frameTime;
                currentBall.Opacity  += currentBall.OpacityDelta * frameTime;

                if (currentBall.Rotation > 360.0f)
                {
                    currentBall.Rotation = currentBall.Rotation - 360.0f;
                }

                if (currentBall.Rotation < 0.0f)
                {
                    currentBall.Rotation = currentBall.Rotation + 360.0f;
                }

                // Adjust position.
                if ((currentBall.Position.X > _mainScreen.Settings.Width) || (currentBall.Position.X < 0))
                {
                    currentBall.PositionDelta.X = -currentBall.PositionDelta.X;
                    currentBall.RotationDelta   = -currentBall.RotationDelta;
                }

                if ((currentBall.Position.Y > _mainScreen.Settings.Height) || (currentBall.Position.Y < 0))
                {
                    currentBall.PositionDelta.Y = -currentBall.PositionDelta.Y;
                    currentBall.RotationDelta   = -currentBall.RotationDelta;
                }

                // Adjust scale.
                if ((currentBall.Scale > 2.0f) || (currentBall.Scale < 0.5f))
                {
                    currentBall.ScaleDelta = -currentBall.ScaleDelta;

                    if (currentBall.Scale < 0.5f)
                    {
                        currentBall.OpacityDelta = GorgonRandom.RandomSingle() * 0.5f * (currentBall.OpacityDelta / currentBall.OpacityDelta.Abs());
                    }
                }

                // Adjust opacity.
                if ((currentBall.Opacity <= 1.0f) &&
                    (currentBall.Opacity >= 0.0f))
                {
                    continue;
                }

                if (currentBall.Opacity > 1.0f)
                {
                    currentBall.Opacity      = 1.0f;
                    currentBall.OpacityDelta = -currentBall.OpacityDelta;
                    continue;
                }

                currentBall.Opacity   = 0.0f;
                currentBall.Checkered = !currentBall.Checkered;
                currentBall.Color     = Color.FromArgb(255, GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255),
                                                       GorgonRandom.RandomInt32(0, 255));
                currentBall.OpacityDelta = GorgonRandom.RandomSingle() * 0.5f;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Function to generate the Gorgon bitmap fonts.
        /// </summary>
        /// <param name="fontFamilies">The list of TrueType font families to use.</param>
        /// <param name="window">The window that contains the loading message.</param>
        private static void GenerateGorgonFonts(IReadOnlyList <Drawing.FontFamily> fontFamilies, FormMain window)
        {
            // Pick a font to use with outlines.
            int fontWithOutlineIndex = GorgonRandom.RandomInt32(1, 5);

            _glowIndex = GorgonRandom.RandomInt32(fontWithOutlineIndex + 1, fontWithOutlineIndex + 5);
            int fontWithGradient = GorgonRandom.RandomInt32(_glowIndex + 1, _glowIndex + 5);
            int fontWithTexture  = GorgonRandom.RandomInt32(fontWithGradient + 1, fontWithGradient + 5).Min(_fontFamilies.Count - 1);

            var pngCodec = new GorgonCodecPng();

            using (IGorgonImage texture = pngCodec.LoadFromFile(Path.Combine(GorgonExample.GetResourcePath(@"Textures\Fonts\").FullName, "Gradient.png")))
            {
                for (int i = 0; i < _fontFamilies.Count; ++i)
                {
                    string fontFamily = _fontFamilies[i];

                    // Use this to determine if the font is avaiable.
                    if (fontFamilies.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        // Can't locate this one, move on...
                        continue;
                    }

                    bool isExternal =
                        Drawing.FontFamily.Families.All(item => !string.Equals(item.Name, fontFamily, StringComparison.InvariantCultureIgnoreCase));
                    string           fontName;
                    int              outlineSize   = 0;
                    GorgonColor      outlineColor1 = GorgonColor.BlackTransparent;
                    GorgonColor      outlineColor2 = GorgonColor.BlackTransparent;
                    GorgonGlyphBrush brush         = null;

                    if (i == fontWithOutlineIndex)
                    {
                        fontName      = $"{fontFamily} 32px Outlined{(isExternal ? " External TTF" : string.Empty)}";
                        outlineColor1 = GorgonColor.Black;
                        outlineColor2 = GorgonColor.Black;
                        outlineSize   = 3;
                    }
                    else if (i == _glowIndex)
                    {
                        fontName      = $"{fontFamily} 32px Outline as Glow{(isExternal ? " External TTF" : string.Empty)}";
                        outlineColor1 = new GorgonColor(GorgonColor.YellowPure, 1.0f);
                        outlineColor2 = new GorgonColor(GorgonColor.DarkRed, 0.0f);
                        outlineSize   = 16;
                    }
                    else if (i == fontWithGradient)
                    {
                        fontName = $"{fontFamily} 32px Gradient{(isExternal ? " External TTF" : string.Empty)}";
                        brush    = new GorgonGlyphLinearGradientBrush
                        {
                            StartColor = GorgonColor.White,
                            EndColor   = GorgonColor.Black,
                            Angle      = 45.0f
                        };
                    }
                    else if (i == fontWithTexture)
                    {
                        fontName = $"{fontFamily} 32px Textured{(isExternal ? " External TTF" : string.Empty)}";
                        brush    = new GorgonGlyphTextureBrush(texture);
                    }
                    else
                    {
                        fontName = $"{fontFamily} 32px{(isExternal ? " External TTF" : string.Empty)}";
                    }

                    window.UpdateStatus($"Generating Font: {fontFamily}".Ellipses(50));

                    var fontInfo = new GorgonFontInfo(fontFamily,
                                                      30.25f,
                                                      name:
                                                      fontName)
                    {
                        AntiAliasingMode         = FontAntiAliasMode.AntiAlias,
                        OutlineSize              = outlineSize,
                        OutlineColor1            = outlineColor1,
                        OutlineColor2            = outlineColor2,
                        UsePremultipliedTextures = false,
                        Brush = brush
                    };

                    _font.Add(_fontFactory.GetFont(fontInfo));

                    // Texture brushes have to be disposed when we're done with them.
                    var disposableBrush = brush as IDisposable;
                    disposableBrush?.Dispose();
                }
            }
        }
Esempio n. 9
0
        public void Init()
        {
            _form = new TestForm
            {
                ShowTestPanel = true,
                ClientSize    = new Size(1280, 800)
            };
            _form.WindowState = FormWindowState.Minimized;
            _form.Show();
            _form.WindowState = FormWindowState.Normal;

            _graphics = new GorgonGraphics();
            _swap     = _graphics.Output.CreateSwapChain("Screen", new GorgonSwapChainSettings()
            {
                Window             = _form.panelDisplay,
                DepthStencilFormat = BufferFormat.D24_UIntNormal_S8_UInt
            });

            _swap.AfterSwapChainResized += (sender, args) =>
            {
                var currentMatrix = new MatrixBuffer();

                _graphics.Rasterizer.SetViewport(_swap.Viewport);
                _aspect = (_swap.Settings.VideoMode.Width) / (float)(_swap.Settings.VideoMode.Height);
                currentMatrix.Projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f, 1000.0f);
                currentMatrix.View       = Matrix.LookAtLH(new Vector3(0, 0, -0.75f), new Vector3(0, 0, 1.0f), Vector3.UnitY);

                _graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer);

                pvw = currentMatrix.View * currentMatrix.Projection;
            };

            _swap.AfterStateTransition += (sender, args) =>
            {
                var currentMatrix = new MatrixBuffer();

                _graphics.Rasterizer.SetViewport(_swap.Viewport);
                _aspect = (_swap.Settings.VideoMode.Width) / (float)(_swap.Settings.VideoMode.Height);
                currentMatrix.Projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f, 1000.0f);
                currentMatrix.View       = Matrix.LookAtLH(new Vector3(0, 0, -0.75f), new Vector3(0, 0, 1.0f), Vector3.UnitY);

                _graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer);

                pvw = currentMatrix.View * currentMatrix.Projection;
            };

            var button = new Button()
            {
                Text     = "3D",
                Location = new Point(90, 3)
            };

            button.Click += (sender, args) =>
            {
                _3d = !_3d;
                Matrix currentMatrix = Matrix.LookAtLH(new Vector3(0, 0, _camPos), new Vector3(0, 0, 1.0f), Vector3.UnitY);
                Matrix projection    = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f,
                                                               1000.0f);
                pvw = currentMatrix * projection;
            };

            _form.panelInput.Controls.Add(button);

            _sprite = new vertex[Count * 4];

            for (int i = 0; i < Count; i++)
            {
                _balls[i].Scale       = 1.0f;
                _balls[i].ScaleDelta  = (GorgonRandom.RandomSingle() * 1.5f) + 0.25f;
                _balls[i].AlphaBounce = _balls[i].ScaleBouce = false;
                _balls[i].XBounce     = GorgonRandom.RandomInt32(0, 100) > 50;
                _balls[i].YBounce     = GorgonRandom.RandomInt32(0, 100) > 50;
                _balls[i].ZBounce     = GorgonRandom.RandomInt32(0, 100) > 50;
                _balls[i].Velocity    = new Vector3((GorgonRandom.RandomSingle() * 0.5f), (GorgonRandom.RandomSingle() * 0.5f), (GorgonRandom.RandomSingle() * 0.5f));
                _balls[i].Angle       = 0.0f;
                _balls[i].AngleDelta  = 1.0f;
                _balls[i].Color       = new Vector4(1.0f);
                _balls[i].AlphaDelta  = GorgonRandom.RandomSingle() * 0.5f;
                _balls[i].Checkered   = true;          // GorgonRandom.RandomInt32(0, 100) > 50;
                _balls[i].Position    = new Vector3((GorgonRandom.RandomSingle() * 2.0f) - 1.0f, (GorgonRandom.RandomSingle() * 2.0f) - 1.0f, GorgonRandom.RandomSingle());
            }

            _vs = _graphics.Shaders.CreateShader <GorgonVertexShader>("TestVShader", "VS", _shader, null, true);
            _ps = _graphics.Shaders.CreateShader <GorgonPixelShader>("TestPShader", "PS", _shader, null, true);

            _layout = _graphics.Input.CreateInputLayout("Input", typeof(vertex), _vs);

            int vertexSize = _layout.Size;
            int index      = 0;
            var indices    = new int[Count * 6 * sizeof(int)];

            for (int i = 0; i < indices.Length; i += 6)
            {
                indices[i]     = index;
                indices[i + 1] = index + 1;
                indices[i + 2] = index + 2;
                indices[i + 3] = index + 1;
                indices[i + 4] = index + 3;
                indices[i + 5] = index + 2;
                index         += 4;
            }

            _vertices = _graphics.Buffers.CreateVertexBuffer("Vertex", new GorgonBufferSettings()
            {
                SizeInBytes = 4 * vertexSize * Count,
                Usage       = BufferUsage.Dynamic
            });
            _index = _graphics.Buffers.CreateIndexBuffer("Index", indices, BufferUsage.Immutable);

            _texture  = _graphics.Textures.FromFile <GorgonTexture2D>("Balls", @"..\..\..\..\Resources\BallDemo\BallDemo.png", new GorgonCodecPNG());
            _texture2 = _graphics.Textures.FromFile <GorgonTexture2D>("VBBack", @"..\..\..\..\Resources\Images\VBback.jpg", new GorgonCodecJPEG());

            var matrix = new MatrixBuffer();

            _aspect = _swap.Settings.VideoMode.Width / (float)(_swap.Settings.VideoMode.Height);

            matrix.Projection = Matrix.PerspectiveFovLH(100.39f.Radians(), _aspect, 0.1f,
                                                        1000.0f);
            matrix.View      = Matrix.LookAtLH(new Vector3(0, 0, _camPos), new Vector3(0, 0, 1.0f), Vector3.UnitY);
            matrix.Array     = new Vector4[3];
            matrix.Array[0]  = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            matrix.Array[1]  = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            matrix.Array[2]  = new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            matrix.valueType = new TEMPGUY
            {
                value2    = matrix.View,
                tempArray = new Vector4[3]
            };

            _depthStateAlpha.IsDepthEnabled      = false;
            _depthStateAlpha.IsDepthWriteEnabled = false;

            _graphics.Input.Layout = _layout;
            _graphics.Shaders.VertexShader.Current = _vs;
            _graphics.Shaders.PixelShader.Current  = _ps;

            _graphics.Shaders.PixelShader.TextureSamplers.SetRange(0, new[] { GorgonTextureSamplerStates.LinearFilter, GorgonTextureSamplerStates.LinearFilter });

            _graphics.Rasterizer.SetViewport(_swap.Viewport);
            _graphics.Output.DepthStencilState.States = _depthStateAlpha;
            _graphics.Output.SetRenderTarget(_swap, _swap.DepthStencilBuffer);
            _graphics.Input.VertexBuffers[0] = new GorgonVertexBufferBinding(_vertices, vertexSize);
            _graphics.Input.IndexBuffer      = _index;
            _graphics.Shaders.PixelShader.Resources.SetRange(0, new GorgonShaderView[] { _texture, _texture2 });
            _graphics.Output.BlendingState.States = GorgonBlendStates.ModulatedBlending;
            pvw = matrix.valueType.value2 * matrix.Projection;

            _tempStream = new GorgonDataStream(_sprite.Length * vertexSize);
        }
Esempio n. 10
0
        public void TestTextureUpdate()
        {
            float diver = 1.0f;

            var shader = _framework.Graphics.Shaders.FromMemory <GorgonPixelShader>("PS",
                                                                                    "TestPSUpdateSub",
                                                                                    Resources.TextureShaders);

            var texture = _framework.Graphics.Textures.CreateTexture("Texture",
                                                                     new GorgonTexture2DSettings
            {
                ArrayCount = 1,
                Format     = BufferFormat.R8G8B8A8_UIntNormal,
                MipCount   = 4,
                Height     = 256,
                Width      = 256,
                Usage      = BufferUsage.Default
            });

            var dynTexture = _framework.Graphics.Textures.CreateTexture("DynTexture",
                                                                        new GorgonTexture2DSettings
            {
                ArrayCount = 1,
                Format     = BufferFormat.R8G8B8A8_UIntNormal,
                MipCount   = 1,
                Height     = 256,
                Width      = 256,
                Usage      = BufferUsage.Dynamic
            });

            var imageData = GorgonImageData.CreateFromGDIImage(Resources.Glass,
                                                               ImageType.Image2D,
                                                               new GorgonGDIOptions
            {
                MipCount = 4
            });

            _framework.CreateTestScene(Shaders, Shaders, true);
            _framework.Graphics.Shaders.PixelShader.Current      = shader;
            _framework.Graphics.Shaders.PixelShader.Resources[1] = texture;

            texture.UpdateSubResource(imageData.Buffers[0],
                                      new Rectangle
            {
                Width  = 128,
                Height = 128,
                X      = 0,
                Y      = 0
            });

            texture.UpdateSubResource(imageData.Buffers[1],
                                      new Rectangle
            {
                Width  = 64,
                Height = 64,
                X      = 128,
                Y      = 0
            });

            GorgonTexture2D testIntFormat = _framework.Graphics.Textures.CreateTexture("asas",
                                                                                       new GorgonTexture2DSettings
            {
                Format = BufferFormat.R8G8B8A8_Int,
                Usage  = BufferUsage.Dynamic,
                Width  = 64,
                Height = 64
            });

            _framework.IdleFunc = () =>
            {
                _framework.Graphics.Shaders.PixelShader.Resources[2] = null;

                using (var lockData = dynTexture.Lock(BufferLockFlags.Write | BufferLockFlags.Discard))
                {
                    for (int i = 0; i < 4096; ++i)
                    {
                        int y = GorgonRandom.RandomInt32(0, imageData.Buffers[0].Height);
                        int x = GorgonRandom.RandomInt32(0, imageData.Buffers[0].Width);

                        // 95417E

                        imageData.Buffers[0].Data.Position = (y * imageData.Buffers[0].PitchInformation.RowPitch)
                                                             + (x * 4);

                        lockData.Data.Position = (y * lockData.PitchInformation.RowPitch)
                                                 + (x * dynTexture.FormatInformation.SizeInBytes);

                        var color = new GorgonColor(imageData.Buffers[0].Data.ReadInt32());

                        color = new GorgonColor(color.Red / diver, color.Green / diver, color.Blue / diver);

                        lockData.Data.Write(color.ToARGB());
                        //lockData.Data.Write(0xFF00FF00);

                        /*lockData.Data.Write(Color.FromArgb(color.ToARGB()).R);
                        *  lockData.Data.Write(Color.FromArgb(color.ToARGB()).G);
                        *  lockData.Data.Write(Color.FromArgb(color.ToARGB()).B);
                        *  lockData.Data.Write(Color.FromArgb(color.ToARGB()).A);*/
                    }
                }

                diver += 0.5f * GorgonTiming.Delta;

                if (diver > 32.0f)
                {
                    diver = 1.0f;
                }

                _framework.Graphics.Shaders.PixelShader.Resources[2] = dynTexture;

                return(false);
            };



            Assert.IsTrue(_framework.Run() == DialogResult.Yes);
        }
Esempio n. 11
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
            {
                // Load the XInput plug-in assembly.
                Gorgon.PlugIns.LoadPlugInAssembly(Program.PlugInPath + "Gorgon.Input.XInput.dll");

                // Create our factory.
                _factory = GorgonInputFactory.CreateInputFactory("GorgonLibrary.Input.GorgonXInputPlugIn");

                // Ensure that we have and XBox controller to work with.
                if (_factory.JoystickDevices.Count == 0)
                {
                    GorgonDialogs.ErrorBox(this, "No XBox controllers were found on this system.\nThis example requires an XBox controller.");
                    Gorgon.Quit();
                    return;
                }

                // Enumerate the active joysticks.  We'll only take 3 of the 4 available xbox controllers.
                _joystick      = new GorgonJoystick[3];
                _stickPosition = new PointF[_joystick.Count];
                _sprayStates   = new SprayCan[_joystick.Count];

                for (int i = 0; i < _joystick.Count; i++)
                {
                    var joystick = _factory.CreateJoystick(this, _factory.JoystickDevices[i].Name);

                    // Set a dead zone on the joystick.
                    // A dead zone will stop input from the joystick until it reaches the outside
                    // of the specified coordinates.
                    joystick.DeadZone.X          = new GorgonRange(joystick.Capabilities.XAxisRange.Minimum / 4, joystick.Capabilities.XAxisRange.Maximum / 4);
                    joystick.DeadZone.Y          = new GorgonRange(joystick.Capabilities.YAxisRange.Minimum / 4, joystick.Capabilities.YAxisRange.Maximum / 4);
                    joystick.DeadZone.SecondaryX = new GorgonRange(joystick.Capabilities.XAxisRange.Minimum / 128, joystick.Capabilities.XAxisRange.Maximum / 128);
                    joystick.DeadZone.SecondaryY = new GorgonRange(joystick.Capabilities.YAxisRange.Minimum / 128, joystick.Capabilities.YAxisRange.Maximum / 128);

                    _joystick[i] = joystick;

                    // Start at a random spot.
                    _stickPosition[i] = new Point(GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Width - 64), GorgonRandom.RandomInt32(64, panelDisplay.ClientSize.Height - 64));

                    // Turn off spray for all controllers.
                    _sprayStates[i] = new SprayCan(joystick, i);
                }

                // Check for connected controllers.
                while (!_joystick.Any(item => item.IsConnected))
                {
                    if (MessageBox.Show(this,
                                        "There are no XBox controllers connected.\nPlease plug in an XBox controller and click OK.",
                                        "No Controllers", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) != DialogResult.Cancel)
                    {
                        continue;
                    }

                    Gorgon.Quit();
                    return;
                }

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

                // Set up our idle loop.
                Gorgon.ApplicationIdleLoopMethod += 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.
                GorgonException.Catch(ex, () => GorgonDialogs.ErrorBox(this, ex));
                Gorgon.Quit();
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Function to perform operations while the CPU is idle.
        /// </summary>
        /// <returns><b>true</b> to continue processing, <b>false</b> to stop.</returns>
        private static bool Idle()
        {
            _postTarget1.Clear(GorgonColor.Black);

            DX.Vector2 textureSize = _background.Texture.ToTexel(new DX.Vector2(_postTarget1.Width, _postTarget1.Height));

            // Blit the background texture.
            _graphics.SetRenderTarget(_postTarget1);
            _renderer.Begin();
            _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _postTarget1.Width, _postTarget1.Height),
                                          GorgonColor.White,
                                          _background,
                                          new DX.RectangleF(_backgroundOffset.X, _backgroundOffset.Y, textureSize.X, textureSize.Y));
            _shipSprite.Color = new GorgonColor(GorgonColor.White, _cloakController.Opacity);
            _renderer.DrawSprite(_shipSprite);
            _renderer.End();

            // No sense in rendering the effect if it's not present.
            float strength = _cloakController.CloakAmount;

            if (strength > 0.0f)
            {
                // Don't bother recording the current state, we're going to be updating it shortly, so it'd be redundant.
                _displacement.Strength = strength;
                _displacement.Render((passIndex, _, __) => DrawDisplacement(passIndex),
                                     _postTarget2);
            }
            else
            {
                // Send the undisplaced image to the 2nd post process target.
                _graphics.SetRenderTarget(_postTarget2);

                _renderer.Begin();
                _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _postTarget1.Width, _postTarget1.Height),
                                              GorgonColor.White,
                                              _postView1,
                                              new DX.RectangleF(0, 0, 1, 1));
                _renderer.End();
            }

            // Smooth our results.
            int blurRadiusUpdate = GorgonRandom.RandomInt32(0, 1000000);

            if (blurRadiusUpdate > 997000)
            {
                _gaussBlur.BlurRadius = (_gaussBlur.BlurRadius + 1).Min(_gaussBlur.MaximumBlurRadius / 2);
            }
            else if (blurRadiusUpdate < 3000)
            {
                _gaussBlur.BlurRadius = (_gaussBlur.BlurRadius - 1).Max(1);
            }

            // If we didn't blur (radius = 0), then just use the original view.
            if (_gaussBlur.BlurRadius > 0)
            {
                _gaussBlur.Render((_, __, outputSize) =>
                {
                    _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, outputSize.Width, outputSize.Height),
                                                  GorgonColor.White,
                                                  _postView2,
                                                  new DX.RectangleF(0, 0, 1, 1));
                },
                                  _postTarget2);
            }

            // Render as an old film effect.
            _oldFilm.Time = GorgonTiming.SecondsSinceStart * 2;
            DX.Vector2 offset = DX.Vector2.Zero;
            if (GorgonRandom.RandomInt32(0, 100) > 95)
            {
                offset = new DX.Vector2(GorgonRandom.RandomSingle(-2.0f, 2.0f), GorgonRandom.RandomSingle(-1.5f, 1.5f));
            }

            _oldFilm.Render((_, __, size) =>
                            _renderer.DrawFilledRectangle(new DX.RectangleF(offset.X, offset.Y, size.Width, size.Height),
                                                          GorgonColor.White,
                                                          _postView2,
                                                          new DX.RectangleF(0, 0, 1, 1)),
                            _postTarget1);

            // Send to our screen.
            _screen.RenderTargetView.Clear(GorgonColor.Black);
            _graphics.SetRenderTarget(_screen.RenderTargetView);

            _renderer.Begin(Gorgon2DBatchState.NoBlend);
            if (GorgonRandom.RandomInt32(0, 100) < 2)
            {
                _finalBrightness = GorgonRandom.RandomSingle(0.65f, 1.0f);
            }

            _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _finalView.Width, _finalView.Height),
                                          new GorgonColor(_finalBrightness, _finalBrightness, _finalBrightness, 1.0f),
                                          _postView1,
                                          new DX.RectangleF(0, 0, 1, 1));
            _renderer.End();

            _renderer.Begin();
            if (_showHelp)
            {
                _renderer.DrawString(HelpText, new DX.Vector2(0, 64), color: new GorgonColor(1.0f, 1.0f, 0));
            }
            _renderer.End();

            GorgonExample.DrawStatsAndLogo(_renderer);

            // Flip our back buffers over.
            _screen.Present(1);

            _cloakController.Update();

            return(true);
        }
Esempio n. 13
0
        /// <summary>
        /// Function called after a pass has been rendered.
        /// </summary>
        /// <param name="pass">Pass that was rendered.</param>
        protected override void OnAfterPassRender(GorgonEffectPass pass)
        {
            // We must set the pixel shader back to the default here.
            // Otherwise our current shader may not like that we're trying to
            // render lines and points with no textures attached.

            // If this shader is nested with another (e.g. gauss blur), then
            // this situation can throw warnings up in the debug spew.

            // Setting the pixel shader to the proper shader when rendering
            // primitives with no textures is the best way to correct this.
            Gorgon2D.PixelShader.Current = null;

            var blend = Gorgon2D.Drawing.Blending;

            // Render dust and dirt.
            for (int i = 0; i < DirtAmount; ++i)
            {
                float grayDust  = GorgonRandom.RandomSingle(0.1f, 0.25f);
                var   dustColor = new GorgonColor(grayDust, grayDust, grayDust, GorgonRandom.RandomSingle(0.25f, 0.95f));

                // Render dust points.
                _point.Color          = dustColor;
                _point.PointThickness = new Vector2(1);
                _point.Position       = new Vector2(GorgonRandom.RandomSingle(0, _currentTargetSize.X - 1),
                                                    GorgonRandom.RandomSingle(0, _currentTargetSize.Y - 1));
                _point.Draw();

                if (GorgonRandom.RandomInt32(100) >= DirtPercent)
                {
                    continue;
                }

                // Render dirt/hair lines.
                var dirtStart = new Vector2(GorgonRandom.RandomSingle(0, _currentTargetSize.X - 1),
                                            GorgonRandom.RandomSingle(0, _currentTargetSize.Y - 1));

                float dirtWidth      = GorgonRandom.RandomSingle(1.0f, 3.0f);
                bool  isHair         = GorgonRandom.RandomInt32(100) > 50;
                bool  isHairVertical = isHair && GorgonRandom.RandomInt32(100) > 50;

                grayDust  = GorgonRandom.RandomSingle(0.1f, 0.15f);
                dustColor = new GorgonColor(grayDust, grayDust, grayDust, GorgonRandom.RandomSingle(0.25f, 0.95f));

                for (int j = 0; j < GorgonRandom.RandomInt32(4, (int)_currentTargetSize.X / 4); j++)
                {
                    _point.Color          = dustColor;
                    _point.Position       = new Vector2(dirtStart.X, dirtStart.Y);
                    _point.PointThickness = isHair ? new Vector2(1) : new Vector2(dirtWidth, dirtWidth);
                    _point.Draw();

                    if ((!isHair) || (isHairVertical))
                    {
                        if (GorgonRandom.RandomInt32(100) > 50)
                        {
                            dirtStart.X++;
                        }
                        else
                        {
                            dirtStart.X--;
                        }
                    }
                    else
                    {
                        if (grayDust < 0.25f)
                        {
                            dirtStart.X++;
                        }
                        else
                        {
                            dirtStart.X--;
                        }
                    }

                    if ((!isHair) || (!isHairVertical))
                    {
                        if (GorgonRandom.RandomInt32(100) > 50)
                        {
                            dirtStart.Y++;
                        }
                        else
                        {
                            dirtStart.Y--;
                        }
                    }
                    else
                    {
                        if (dirtWidth < 1.5f)
                        {
                            dirtStart.Y++;
                        }
                        else
                        {
                            dirtStart.Y--;
                        }
                    }
                }
            }

            // Restore the previous blend state.
            Gorgon2D.Drawing.Blending = blend;

            base.OnAfterPassRender(pass);
        }
Esempio n. 14
0
        /// <summary>
        /// Function to draw the pretty picture.
        /// </summary>
        private void DrawAPrettyPicture()
        {
            // Paint color.
            Color paintColor;

            // Clear the back buffer.
            _screen.RenderTargetView.Clear(Color.FromArgb(0, 0, 64));

            // First, we need to inform the renderer that we're about draw some stuff.
            _renderer.Begin();

            // Draw some points as stars.
            for (int x = 0; x < 1000; x++)
            {
                // Color.
                int colorSwitch = GorgonRandom.RandomInt32(160) + 95;   // Color component for the points.

                // Get the star color.
                paintColor = Color.FromArgb(colorSwitch, colorSwitch, colorSwitch);

                _renderer.DrawFilledRectangle(new DX.RectangleF(GorgonRandom.RandomSingle(_screen.Width), GorgonRandom.RandomSingle(_screen.Height), 1, 1), paintColor);
            }

            // Draw lines.
            for (int x = 0; x < 360; x++)
            {
                float cos = (x + (x / 2.0f)).FastCos();     // Cosine.
                float sin = (x + (x / 3.0f)).FastSin();     // Sin.

                // Set up a random color.
                paintColor = Color.FromArgb((byte)GorgonRandom.RandomInt32(128, 255), GorgonRandom.RandomInt32(64, 255), GorgonRandom.RandomInt32(64, 255), 0);
                var startPosition = new DX.Vector2(sin + _halfSize.Width, cos + _halfSize.Height);
                var endPosition   = new DX.Vector2((cos * (GorgonRandom.RandomSingle(_halfSize.Width * 0.82f))) + startPosition.X, (sin * (GorgonRandom.RandomSingle(_halfSize.Height * 0.82f))) + startPosition.Y);
                _renderer.DrawLine(startPosition.X, startPosition.Y, endPosition.X, endPosition.Y, paintColor);
                //Gorgon.Screen.Line(sin + _halfWidth, cos + _halfHeight, cos * (RandomValue * _halfWidth), sin * (RandomValue * _halfHeight), paintColor);
            }

            // Draw a filled circle.
            float size = (_halfSize.Width / 2.0f) + (GorgonRandom.RandomInt32(10) - 8);
            float half = size / 2.0f;

            _renderer.DrawFilledEllipse(new DX.RectangleF(_halfSize.Width - half, _halfSize.Height - half, size, size), Color.Yellow);

            // Draw some circles in the filled circle (sunspots).
            for (int x = 0; x < 25; x++)
            {
                float radius       = GorgonRandom.RandomSingle(5.0f);
                var   spotPosition = new DX.Vector2((GorgonRandom.RandomSingle((_halfSize.Height / 2.0f)) + _halfSize.Width - (_halfSize.Height / 4.0f)),
                                                    (GorgonRandom.RandomSingle((_halfSize.Height / 2.0f)) + _halfSize.Height - (_halfSize.Height / 4.0f)));
                _renderer.DrawEllipse(new DX.RectangleF(spotPosition.X - (radius * 0.5f),
                                                        spotPosition.Y - (radius * 0.5f),
                                                        radius,
                                                        radius),
                                      Color.Black);
            }

            // Draw some black bars.
            _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _screen.Width, _screen.Height / 6.0f), Color.Black);
            _renderer.DrawFilledRectangle(new DX.RectangleF(0, _screen.Height - (_screen.Height / 6.0f), _screen.Width, _screen.Height / 6.0f), Color.Black);

            // Tell the renderer that we're done drawing so we can actually render the shapes.
            _renderer.End();

            GorgonExample.DrawStatsAndLogo(_renderer);

            // Always call this when done or you won't see anything.
            _screen.Present(1);
        }
Esempio n. 15
0
        /// <summary>
        /// Function to randomly "spray" a point on the surface.
        /// </summary>
        /// <param name="point">Origin point for the spray.</param>
        public void SprayPoint(Point point)
        {
            var randomArea = new Point(GorgonRandom.RandomInt32(-10, 10), GorgonRandom.RandomInt32(-10, 10));

            _graphics.FillEllipse(_brushes[GorgonRandom.RandomInt32(0, _brushes.Length - 1)], new Rectangle(point.X + randomArea.X, point.Y + randomArea.Y, 10, 10));
        }