示例#1
0
        /// <summary>
        /// Function to build the layer that contains the sun.
        /// </summary>
        /// <param name="renderer">The 2D renderer for the application.</param>
        /// <param name="resources">The resources for the application.</param>
        /// <returns>The sprite layer that will contain the sun sprite.</returns>
        public static SpritesLayer GetSunLayer(Gorgon2D renderer, ResourceManagement resources)
        {
            GorgonSprite sunSprite = resources.Sprites["Star"];
            var          sunLayer  = new SpritesLayer(renderer)
            {
                ParallaxLevel = 2980.0f,                        // The sun is pretty far away the last I checked.
                Sprites       =
                {
                    new SpriteEntity("Sun")
                    {
                        Sprite        = sunSprite,
                        LocalPosition = new DX.Vector2(1200, -650)
                    }
                },
                PostProcessGroup = "Final Pass",
                Lights           =
                {
                    new Light
                    {
                        Attenuation        = float.MaxValue.Sqrt(),
                        Color              = GorgonColor.White,
                        SpecularPower      = 6.0f,
                        LocalLightPosition = new DX.Vector3(1200, -650, -1.0f),
                        Intensity          = 13.07f
                    }
                }
            };

            sunLayer.LoadResources();

            return(sunLayer);
        }
示例#2
0
 /// <summary>
 /// Function to save the sprite data to a stream.
 /// </summary>
 /// <param name="sprite">The sprite to serialize into the stream.</param>
 /// <param name="stream">The stream that will contain the sprite.</param>
 protected override void OnSaveToStream(GorgonSprite sprite, Stream stream)
 {
     using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
     {
         writer.Write(sprite.ToJson());
     }
 }
示例#3
0
        /// <summary>Function to retrieve the default content name, and data.</summary>
        /// <param name="generatedName">A default name generated by the application.</param>
        /// <returns>The default content name along with the content data serialized as a byte array. If either the name or data are <b>null</b>, then the user cancelled..</returns>
        /// <remarks>
        /// <para>
        /// Plug in authors may override this method so a custom UI can be presented when creating new content, or return a default set of data and a default name, or whatever they wish.
        /// </para>
        /// <para>
        /// If an empty string (or whitespace) is returned for the name, then the <paramref name="generatedName"/> will be used.
        /// </para>
        /// </remarks>
        protected override Task <(string name, byte[] data)> OnGetDefaultContentAsync(string generatedName)
        {
            var sprite = new GorgonSprite
            {
                Anchor = new DX.Vector2(0.5f, 0.5f),
                Size   = new DX.Size2F(1, 1)
            };

            byte[] data;

            using (var stream = new MemoryStream())
            {
                _defaultCodec.Save(sprite, stream);
                data = stream.ToArray();
            }

            using (var formName = new FormName
            {
                Text = Resources.GORSPR_CAPTION_SPRITE_NAME,
                ObjectName = generatedName ?? string.Empty,
                ObjectType = ContentType
            })
            {
                if (formName.ShowDialog(GorgonApplication.MainForm) == DialogResult.OK)
                {
                    return(Task.FromResult((formName.ObjectName, data)));
                }
            }

            return(Task.FromResult <(string, byte[])>((null, null)));
        }
示例#4
0
        /// <summary>
        /// Function called when the content has changed.
        /// </summary>
        public override void RefreshContent()
        {
            base.RefreshContent();

            if (_content == null)
            {
                throw new InvalidCastException(string.Format(Resources.GORSPR_ERR_CONTENT_NOT_SPRITE, Content.Name));
            }

            SetUpScrolling();

            if (_anchorImage == null)
            {
                _anchorImage                = ContentObject.Graphics.Textures.CreateTexture <GorgonTexture2D>("AnchorTexture", Resources.anchor_24x24);
                _anchorSprite               = _content.Renderer.Renderables.CreateSprite("AnchorSprite", _anchorImage.Settings.Size, _anchorImage);
                _anchorSprite.Anchor        = new Vector2(_anchorSprite.Size.X / 2.0f, _anchorSprite.Size.Y / 2.0f);
                _anchorSprite.SmoothingMode = SmoothingMode.Smooth;
                _anchorAnim = new AnchorColorAnim();

                scrollHorizontal.Value = 0;
                scrollVertical.Value   = 0;

                _clipper = new Clipper(_content.Renderer, panelSprite)
                {
                    SelectorPattern = _content.BackgroundTexture,
                    DefaultCursor   = Cursors.Cross
                };

                _halfScreen = (Point)(new Vector2(panelSprite.ClientSize.Width / 2.0f, panelSprite.ClientSize.Height / 2.0f));

                CalculateSpritePosition();
            }

            ValidateControls();
        }
示例#5
0
        /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.SpriteVertexOffsetRenderer"/> class.</summary>
        /// <param name="sprite">The sprite view model.</param>
        /// <param name="graphics">The graphics interface for the application.</param>
        /// <param name="swapChain">The swap chain for the render area.</param>
        /// <param name="renderer">The 2D renderer for the application.</param>
        /// <param name="vertexEditor">The editor used to modify the sprite vertices.</param>
        /// <param name="initialZoom">The initial zoom scale value.</param>
        public SpriteVertexOffsetRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, ISpriteVertexEditService vertexEditor, float initialZoom)
            : base(sprite, graphics, swapChain, renderer, initialZoom)
        {
            InitialTextureAlpha           = 0;
            _vertexEditor                 = vertexEditor;
            _vertexEditor.RectToClient    = r => ToClient(r).Truncate();
            _vertexEditor.PointToClient   = p => ToClient(p).Truncate();
            _vertexEditor.PointFromClient = p => FromClient(p).Truncate();

            _workingSprite = new GorgonSprite
            {
                Texture           = sprite.Texture,
                TextureRegion     = sprite.TextureCoordinates,
                TextureArrayIndex = TextureArrayIndex,
                Size   = sprite.Size,
                Scale  = DX.Vector2.One,
                Anchor = DX.Vector2.Zero,
                Color  = GorgonColor.White,
                Depth  = 0.1f
            };

            UpdateWorkingSprite();

            _vertexEditor.VerticesChanged     += VertexEditor_VerticesChanged;
            _vertexEditor.KeyboardIconClicked += VertexEditor_KeyboardIconClicked;
            _vertexEditor.VertexSelected      += VertexEditor_VertexSelected;

            _camera = new Gorgon2DPerspectiveCamera(renderer, new DX.Size2F(swapChain.Width, swapChain.Height));
        }
示例#6
0
        /// <summary>
        /// Function to draw the lower layer.
        /// </summary>
        private static void DrawLayer1()
        {
            GorgonSprite shadowSprite = _bgSprite == _sprite2 ? _shadowSprites[1] : _shadowSprites[0];

            _layer1Target.Clear(GorgonColor.BlackTransparent);
            _graphics.SetRenderTarget(_layer1Target);

            _renderer.Begin(_rtvBlendState);

            // Background sprites should be smaller.
            _bgSprite.Scale    = new DX.Vector2(0.5f, 0.5f);
            shadowSprite.Scale = new DX.Vector2(0.5f, 0.5f);

            shadowSprite.Position = _bgSprite.Position +
                                    (new DX.Vector2(_bgSprite.Position.X - (_screen.Width / 2.0f), _bgSprite.Position.Y - (_screen.Height / 2.0f)) * _bgSprite.Scale * 0.075f);

            var bgRegion = new DX.RectangleF(0, 0, _screen.Width, _screen.Height);

            _renderer.DrawFilledRectangle(bgRegion,
                                          GorgonColor.White,
                                          _backgroundTexture,
                                          new DX.RectangleF(0,
                                                            0,
                                                            (float)_screen.Width / _backgroundTexture.Width,
                                                            (float)_screen.Height / _backgroundTexture.Height),
                                          textureSampler: GorgonSamplerState.PointFilteringWrapping);
            _renderer.DrawSprite(shadowSprite);
            _renderer.DrawSprite(_bgSprite);

            _renderer.End();
        }
示例#7
0
        /// <summary>Imports the data.</summary>
        /// <param name="temporaryDirectory">The temporary directory for writing any transitory data.</param>
        /// <param name="cancelToken">The cancel token.</param>
        /// <remarks>
        /// <para>
        /// The <paramref name="temporaryDirectory"/> should be used to write any working/temporary data used by the import.  Note that all data written into this directory will be deleted when the
        /// project is unloaded from memory.
        /// </para>
        /// </remarks>
        public FileInfo ImportData(DirectoryInfo temporaryDirectory, CancellationToken cancelToken)
        {
            var spriteCodec = new GorgonV3SpriteBinaryCodec(_renderer);

            _log.Print("Importing associated texture for sprite...", LoggingLevel.Simple);
            GorgonTexture2DView texture = GetTexture();

            try
            {
                _log.Print($"Importing file '{SourceFile.FullName}' (Codec: {_codec.Name})...", LoggingLevel.Verbose);
                GorgonSprite sprite = _codec.FromFile(SourceFile.FullName);

                if (sprite.Texture == null)
                {
                    sprite.Texture = texture;
                }

                var tempFile = new FileInfo(Path.Combine(temporaryDirectory.FullName, Path.GetFileNameWithoutExtension(SourceFile.Name)));

                _log.Print($"Converting '{SourceFile.FullName}' to Gorgon v3 Sprite file format.", LoggingLevel.Verbose);
                spriteCodec.Save(sprite, tempFile.FullName);

                return(tempFile);
            }
            finally
            {
                texture?.Dispose();
            }
        }
示例#8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ShadowBuilder"/> class.
 /// </summary>
 /// <param name="renderer">The renderer.</param>
 /// <param name="effect">The gaussian blur effect to use in order to soften the shadows.</param>
 /// <param name="sprite1">The first sprite to draw.</param>
 /// <param name="sprite2">The second sprite to draw.</param>
 public ShadowBuilder(Gorgon2D renderer, Gorgon2DGaussBlurEffect effect, GorgonSprite sprite1, GorgonSprite sprite2)
 {
     _renderer  = renderer;
     _gaussBlur = effect;
     _sprite1   = sprite1;
     _sprite2   = sprite2;
 }
示例#9
0
        /// <summary>
        /// Function to update the preview sprite.
        /// </summary>
        /// <param name="scale">The current scale factor.</param>
        private void UpdatePreviewSprite(float scale)
        {
            GorgonSprite currentSprite = DataContext.Sprites[DataContext.CurrentPreviewSprite];

            _previewSprite.Size              = new DX.Size2F(currentSprite.Size.Width * scale, currentSprite.Size.Height * scale);
            _previewSprite.TextureRegion     = currentSprite.TextureRegion;
            _previewSprite.TextureArrayIndex = currentSprite.TextureArrayIndex;
        }
示例#10
0
        /// <summary>
        /// Function to load the image to be used a thumbnail.
        /// </summary>
        /// <param name="thumbnailCodec">The codec for the thumbnail images.</param>
        /// <param name="thumbnailFile">The path to the thumbnail file.</param>
        /// <param name="content">The content being thumbnailed.</param>
        /// <param name="fileManager">The file manager used to handle content files.</param>
        /// <param name="cancelToken">The token used to cancel the operation.</param>
        /// <returns>The image, image content file and sprite, or just the thumbnail image if it was cached (sprite will be null).</returns>
        private (IGorgonImage image, IContentFile imageFile, GorgonSprite sprite) LoadThumbnailImage(IGorgonImageCodec thumbnailCodec, FileInfo thumbnailFile, IContentFile content, IContentFileManager fileManager, CancellationToken cancelToken)
        {
            IGorgonImage spriteImage;
            Stream       inStream  = null;
            Stream       imgStream = null;

            try
            {
                // If we've already got the file, then leave.
                if (thumbnailFile.Exists)
                {
                    inStream    = thumbnailFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                    spriteImage = thumbnailCodec.LoadFromStream(inStream);

#pragma warning disable IDE0046 // Convert to conditional expression
                    if (cancelToken.IsCancellationRequested)
                    {
                        return(null, null, null);
                    }
#pragma warning restore IDE0046 // Convert to conditional expression

                    return(spriteImage, null, null);
                }

                IContentFile imageFile = FindImage(content, fileManager);
                if (imageFile == null)
                {
                    return(_noImage.Clone(), null, null);
                }

                imgStream = imageFile.OpenRead();
                inStream  = content.OpenRead();

                if ((!_ddsCodec.IsReadable(imgStream)) ||
                    (!_defaultCodec.IsReadable(inStream)))
                {
                    return(_noImage.Clone(), null, null);
                }

                spriteImage = _ddsCodec.LoadFromStream(imgStream);
                GorgonSprite sprite = _defaultCodec.FromStream(inStream);

                return(spriteImage, imageFile, sprite);
            }
            catch (Exception ex)
            {
                CommonServices.Log.Print($"[ERROR] Cannot create thumbnail for '{content.Path}'", LoggingLevel.Intermediate);
                CommonServices.Log.LogException(ex);
                return(null, null, null);
            }
            finally
            {
                imgStream?.Dispose();
                inStream?.Dispose();
            }
        }
示例#11
0
        /// <summary>
        /// Function to create the sprites to draw.
        /// </summary>
        private static void CreateSprites()
        {
            // Create the regular sprite first.
            _normalSprite = new GorgonSprite
            {
                Anchor        = new DX.Vector2(0.5f, 0.5f),
                Size          = new DX.Size2F(_texture.Width, _texture.Height),
                Texture       = _texture,
                TextureRegion = new DX.RectangleF(0, 0, 1, 1)
            };

            _polySprite = PolygonHullParser.ParsePolygonHullString(_renderer, Resources.PolygonHull);
        }
示例#12
0
        /// <summary>
        /// Function to render the sprite preview.
        /// </summary>
        private void DrawPreview()
        {
            GorgonSprite sprite = DataContext.Sprites[DataContext.CurrentPreviewSprite];
            float        scale  = CalcZoomToSize(new DX.Size2F(sprite.Size.Width + 8, sprite.Size.Height + 8), new DX.Size2F(_swapChain.Width, _swapChain.Height));

            UpdatePreviewSprite(scale);

            _renderer.Begin(camera: _camera);
            _renderer.DrawFilledRectangle(new DX.RectangleF(-_swapChain.Width * 0.5f, -_swapChain.Height * 0.5f, _swapChain.Width, _swapChain.Height),
                                          GorgonColor.White,
                                          _bgTexture,
                                          new DX.RectangleF(0, 0, (float)_swapChain.Width / _bgTexture.Width, (float)_swapChain.Height / _bgTexture.Height));
            _renderer.DrawSprite(_previewSprite);
            _renderer.End();
        }
示例#13
0
        /// <summary>
        /// Handles the MouseUp event of the Window control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private static void Window_MouseUp(object sender, MouseEventArgs e)
        {
            _bgSprite.Position = new DX.Vector2(e.X, e.Y);
            _fgSprite.Position = new DX.Vector2(e.X, e.Y);

            if (_bgSprite == _sprite2)
            {
                _bgSprite = _sprite1;
                _fgSprite = _sprite2;
            }
            else
            {
                _bgSprite = _sprite2;
                _fgSprite = _sprite1;
            }
        }
示例#14
0
        /// <summary>
        /// Function to initialize the render data from the data context.
        /// </summary>
        /// <param name="dataContext">The current data context.</param>
        private void InitializeFromDataContext(ITextureAtlas dataContext)
        {
            if (dataContext?.Atlas == null)
            {
                _textureSprite = new GorgonSprite();
                return;
            }

            _textureSprite = new GorgonSprite
            {
                Texture        = dataContext.Atlas.Textures[0],
                TextureRegion  = new DX.RectangleF(0, 0, 1, 1),
                Size           = new DX.Size2F(dataContext.Atlas.Textures[0].Width, dataContext.Atlas.Textures[0].Height),
                TextureSampler = GorgonSamplerState.PointFiltering
            };
        }
示例#15
0
        /// <summary>
        /// Function to do perform processing for the application during idle time.
        /// </summary>
        /// <returns><b>true</b> to continue execution, <b>false</b> to stop.</returns>
        private static bool Idle()
        {
            GorgonSprite shadowSprite = _fgSprite == _sprite2 ? _shadowSprites[1] : _shadowSprites[0];

            // Draw our background that includes our background texture, and the sprite that's currently in the background (along with its shadow).
            // Blurring may or may not be applied depending on whether the user has applied it with the mouse wheel.
            DrawBlurredBackground();

            // Reset scales for our sprites. Foreground sprites will be larger than our background ones.
            shadowSprite.Scale = _fgSprite.Scale = DX.Vector2.One;

            // Ensure we're on the "screen" when we render.
            _graphics.SetRenderTarget(_screen.RenderTargetView);

            _renderer.Begin();

            // Draw our blurred (or not) background.
            _renderer.DrawFilledRectangle(new DX.RectangleF(0, 0, _screen.Width, _screen.Height),
                                          GorgonColor.White,
                                          _blurTexture,
                                          new DX.RectangleF(0, 0, 1, 1));

            // Draw an ellipse to indicate our light source.
            var lightPosition = new DX.RectangleF((_screen.Width / 2.0f) - 10, (_screen.Height / 2.0f) - 10, 20, 20);

            _renderer.DrawFilledEllipse(lightPosition, GorgonColor.White, 0.5f);

            // Draw the sprite and its corresponding shadow.
            // We'll adjust the shadow position to be altered by our distance from the light source, and the quadrant of the screen that we're in.
            shadowSprite.Position = _fgSprite.Position + (new DX.Vector2(_fgSprite.Position.X - (_screen.Width / 2.0f), _fgSprite.Position.Y - (_screen.Height / 2.0f)) * 0.125f);

            _renderer.DrawSprite(shadowSprite);
            _renderer.DrawSprite(_fgSprite);

            if (_showHelp)
            {
                _renderer.DrawString(HelpText, new DX.Vector2(2, 2), _helpFont, GorgonColor.White);
            }

            _renderer.End();

            GorgonExample.DrawStatsAndLogo(_renderer);

            _screen.Present(1);

            return(true);
        }
示例#16
0
        /// <summary>
        /// Function to initialize the render data from the data context.
        /// </summary>
        /// <param name="dataContext">The current data context.</param>
        private void InitializeFromDataContext(IExtract dataContext)
        {
            if (dataContext == null)
            {
                _previewSprite.Texture = null;
                _textureSprite         = new GorgonSprite();
                return;
            }

            _previewSprite.Texture = dataContext.Texture;
            _textureSprite         = new GorgonSprite
            {
                Texture        = dataContext.Texture,
                TextureRegion  = new DX.RectangleF(0, 0, 1, 1),
                Size           = new DX.Size2F(dataContext.Texture.Width, dataContext.Texture.Height),
                TextureSampler = GorgonSamplerState.PointFiltering
            };
        }
示例#17
0
        /// <summary>
        /// Function to save the sprite data to a file on a physical file system.
        /// </summary>
        /// <param name="sprite">The sprite to serialize into the file.</param>
        /// <param name="filePath">The path to the file to write.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="filePath" /> parameter is <b>null</b>.</exception>
        /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="filePath" /> parameter is empty.</exception>
        /// <exception cref="NotSupportedException">This method is not supported by this codec.</exception>
        public void Save(GorgonSprite sprite, string filePath)
        {
            if (!CanEncode)
            {
                throw new NotSupportedException();
            }

            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentEmptyException(nameof(filePath));
            }

            using (FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                Save(sprite, stream);
            }
        }
 /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.SpriteContentParameters"/> class.</summary>
 /// <param name="factory">The factory for building sprite content data.</param>
 /// <param name="spriteFile">The sprite file.</param>
 /// <param name="spriteTextureFile">The sprite texture file.</param>
 /// <param name="fileManager">The file manager used to access external content.</param>
 /// <param name="textureService">The texture service to use when reading sprite texture data.</param>
 /// <param name="sprite">The sprite being edited.</param>
 /// <param name="codec">The codec to use when reading/writing sprite data.</param>
 /// <param name="manualRectEdit">The manual rectangle editor view model.</param>
 /// <param name="manualVertexEdit">The manual vertex editor view model.</param>
 /// <param name="spritePickMaskEditor">The sprite picker mask color editor.</param>
 /// <param name="colorEditor">The color editor for the sprite.</param>
 /// <param name="anchorEditor">The anchor editor for the sprite.</param>
 /// <param name="wrapEditor">The texture wrapping state editor for the sprite.</param>
 /// <param name="settings">The plug in settings view model.</param>
 /// <param name="undoService">The undo service.</param>
 /// <param name="scratchArea">The file system used to write out temporary working data.</param>
 /// <param name="commonServices">Common application services.</param>
 public SpriteContentParameters(
     ISpriteContentFactory factory,
     IContentFile spriteFile,
     IContentFile spriteTextureFile,
     IContentFileManager fileManager,
     ISpriteTextureService textureService,
     GorgonSprite sprite,
     IGorgonSpriteCodec codec,
     IManualRectangleEditor manualRectEdit,
     IManualVertexEditor manualVertexEdit,
     ISpritePickMaskEditor spritePickMaskEditor,
     ISpriteColorEdit colorEditor,
     ISpriteAnchorEdit anchorEditor,
     ISpriteWrappingEditor wrapEditor,
     ISamplerBuildService samplerBuilder,
     IEditorPlugInSettings settings,
     IUndoService undoService,
     IGorgonFileSystemWriter <Stream> scratchArea,
     IViewModelInjection commonServices)
     : base(spriteFile, commonServices)
 {
     Factory               = factory ?? throw new ArgumentNullException(nameof(factory));
     Sprite                = sprite ?? throw new ArgumentNullException(nameof(sprite));
     UndoService           = undoService ?? throw new ArgumentNullException(nameof(undoService));
     ContentFileManager    = fileManager ?? throw new ArgumentNullException(nameof(fileManager));
     ScratchArea           = scratchArea ?? throw new ArgumentNullException(nameof(scratchArea));
     TextureService        = textureService ?? throw new ArgumentNullException(nameof(textureService));
     SpriteCodec           = codec ?? throw new ArgumentNullException(nameof(codec));
     ManualRectangleEditor = manualRectEdit ?? throw new ArgumentNullException(nameof(manualRectEdit));
     ManualVertexEditor    = manualVertexEdit ?? throw new ArgumentNullException(nameof(manualVertexEdit));
     SpritePickMaskEditor  = spritePickMaskEditor ?? throw new ArgumentNullException(nameof(spritePickMaskEditor));
     Settings              = settings ?? throw new ArgumentNullException(nameof(settings));
     ColorEditor           = colorEditor ?? throw new ArgumentNullException(nameof(colorEditor));
     AnchorEditor          = anchorEditor ?? throw new ArgumentNullException(nameof(anchorEditor));
     SpriteWrappingEditor  = wrapEditor ?? throw new ArgumentNullException(nameof(wrapEditor));
     SamplerBuilder        = samplerBuilder ?? throw new ArgumentNullException(nameof(samplerBuilder));
     SpriteTextureFile     = spriteTextureFile;
 }
示例#19
0
        /// <summary>Initializes a new instance of the <see cref="T:Gorgon.Editor.SpriteEditor.DefaultSpriteRenderer"/> class.</summary>
        /// <param name="sprite">The sprite view model.</param>
        /// <param name="graphics">The graphics interface for the application.</param>
        /// <param name="swapChain">The swap chain for the render area.</param>
        /// <param name="renderer">The 2D renderer for the application.</param>
        /// <param name="ants">The marching ants rectangle used to draw selection rectangles.</param>
        /// <param name="initialScale">The initial scaling value to apply to the render.</param>
        public DefaultSpriteRenderer(ISpriteContent sprite, GorgonGraphics graphics, GorgonSwapChain swapChain, Gorgon2D renderer, IMarchingAnts ants, float initialScale)
            : base(sprite, graphics, swapChain, renderer, initialScale)
        {
            _marchAnts = ants;

            _workingSprite = new GorgonSprite
            {
                Texture           = sprite.Texture,
                TextureRegion     = sprite.TextureCoordinates,
                TextureArrayIndex = TextureArrayIndex,
                Size   = sprite.Size,
                Scale  = DX.Vector2.One,
                Anchor = DX.Vector2.Zero
            };

            for (int i = 0; i < 4; ++i)
            {
                _workingSprite.CornerColors[i]  = sprite.VertexColors[i];
                _workingSprite.CornerOffsets[i] = sprite.VertexOffsets[i];
            }

            UpdateWorkingSprite();
        }
示例#20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ZoomWindow"/> class.
        /// </summary>
        /// <param name="renderer">The renderer to use for magnification.</param>
        /// <param name="texture">The texture to zoom.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="renderer"/> or the <paramref name="texture"/> parameter is NULL (Nothing in VB.Net).</exception>
        public ZoomWindow(Gorgon2D renderer, GorgonTexture2D texture)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            if (texture == null)
            {
                throw new ArgumentNullException("texture");
            }

            _windowSize = new Vector2(128, 128);
            Position    = Vector2.Zero;
            _zoom       = 2.0f;
            _renderer   = renderer;
            _texture    = texture;

            _sprite = _renderer.Renderables.CreateSprite("Zoomer",
                                                         new GorgonSpriteSettings
            {
                Texture         = _texture,
                Size            = _windowSize,
                InitialPosition = ZoomWindowLocation,
                TextureRegion   = new RectangleF(0, 0, 1, 1)
            });

            _sprite.TextureSampler.HorizontalWrapping = TextureAddressing.Border;
            _sprite.TextureSampler.VerticalWrapping   = TextureAddressing.Border;
            _sprite.TextureSampler.BorderColor        = GorgonColor.Transparent;
            _sprite.TextureSampler.TextureFilter      = TextureFilter.Point;

            _zoomWindowText = APIResources.GOREDIT_TEXT_ZOOM;
            _zoomFont       = renderer.Graphics.Fonts.DefaultFont;

            UpdateTextureCoordinates();
        }
示例#21
0
        /// <summary>
        /// Function to save the sprite data to a stream.
        /// </summary>
        /// <param name="sprite">The sprite to serialize into the stream.</param>
        /// <param name="stream">The stream that will contain the sprite.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="sprite"/>, or the <paramref name="stream"/> parameter is <b>null</b>.</exception>
        /// <exception cref="GorgonException">Thrown if the stream is read only.</exception>
        /// <exception cref="NotSupportedException">This method is not supported by this codec.</exception>
        public void Save(GorgonSprite sprite, Stream stream)
        {
            if (!CanEncode)
            {
                throw new NotSupportedException();
            }

            if (sprite == null)
            {
                throw new ArgumentNullException(nameof(sprite));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanWrite)
            {
                throw new GorgonException(GorgonResult.CannotWrite, Resources.GOR2DIO_ERR_STREAM_IS_READ_ONLY);
            }

            OnSaveToStream(sprite, stream);
        }
示例#22
0
        /// <summary>
        /// Function to render the sprite to a thumbnail image.
        /// </summary>
        /// <param name="sprite">The sprite to render.</param>
        /// <returns>The image containing the rendered sprite.</returns>
        private IGorgonImage RenderThumbnail(GorgonSprite sprite)
        {
            GorgonRenderTargetView prevRtv = null;

            try
            {
                sprite.Anchor = new DX.Vector2(0.5f);

                if (sprite.Size.Width > sprite.Size.Height)
                {
                    sprite.Scale = new DX.Vector2(256.0f / (sprite.Size.Width.Max(1)));
                }
                else
                {
                    sprite.Scale = new DX.Vector2(256.0f / (sprite.Size.Height.Max(1)));
                }

                sprite.Position = new DX.Vector2(128, 128);

                prevRtv = GraphicsContext.Graphics.RenderTargets[0];
                GraphicsContext.Graphics.SetRenderTarget(_rtv);
                GraphicsContext.Renderer2D.Begin();
                GraphicsContext.Renderer2D.DrawFilledRectangle(new DX.RectangleF(0, 0, 256, 256), GorgonColor.White, _bgPattern, new DX.RectangleF(0, 0, 1, 1));
                GraphicsContext.Renderer2D.DrawSprite(sprite);
                GraphicsContext.Renderer2D.End();

                return(_rtv.Texture.ToImage());
            }
            finally
            {
                if (prevRtv != null)
                {
                    GraphicsContext.Graphics.SetRenderTarget(prevRtv);
                }
            }
        }
示例#23
0
        /// <summary>
        /// Function to load a version 1.x Gorgon sprite.
        /// </summary>
        /// <param name="graphics">The graphics interface used to create states.</param>
        /// <param name="reader">Binary reader to use to read in the data.</param>
        /// <param name="overrideTexture">The texture to assign to the sprite instead of the texture associated with the name stored in the file.</param>
        /// <returns>The sprite from the stream data.</returns>
        private static GorgonSprite LoadSprite(GorgonGraphics graphics, GorgonBinaryReader reader, GorgonTexture2DView overrideTexture)
        {
            Version version;
            string  imageName = string.Empty;

            string headerVersion = reader.ReadString();

            if ((!headerVersion.StartsWith("GORSPR", StringComparison.OrdinalIgnoreCase)) ||
                (headerVersion.Length < 7) ||
                (headerVersion.Length > 9))
            {
                throw new GorgonException(GorgonResult.CannotRead, Resources.GOR2DIO_ERR_INVALID_HEADER);
            }

            var sprite = new GorgonSprite();

            // Get the version information.
            switch (headerVersion.ToUpperInvariant())
            {
            case "GORSPR1":
                version = new Version(1, 0);
                break;

            case "GORSPR1.1":
                version = new Version(1, 1);
                break;

            case "GORSPR1.2":
                version = new Version(1, 2);
                break;

            default:
                throw new GorgonException(GorgonResult.CannotRead, string.Format(Resources.GOR2DIO_ERR_VERSION_MISMATCH, headerVersion));
            }

            // We don't need the sprite name.
            reader.ReadString();

            // Find out if we have an image.
            if (reader.ReadBoolean())
            {
                bool isRenderTarget = reader.ReadBoolean();

                imageName = reader.ReadString();

                // We won't be supporting reading render targets from sprites in this version.
                if (isRenderTarget)
                {
                    // Skip the target data.
                    reader.ReadInt32();
                    reader.ReadInt32();
                    reader.ReadInt32();
                    reader.ReadBoolean();
                    reader.ReadBoolean();
                }
            }

            // We don't use "inherited" values anymore.  But we need them because
            // the file doesn't include inherited data.
            bool InheritAlphaMaskFunction     = reader.ReadBoolean();
            bool InheritAlphaMaskValue        = reader.ReadBoolean();
            bool InheritBlending              = reader.ReadBoolean();
            bool InheritHorizontalWrapping    = reader.ReadBoolean();
            bool InheritSmoothing             = reader.ReadBoolean();
            bool InheritStencilCompare        = reader.ReadBoolean();
            bool InheritStencilEnabled        = reader.ReadBoolean();
            bool InheritStencilFailOperation  = reader.ReadBoolean();
            bool InheritStencilMask           = reader.ReadBoolean();
            bool InheritStencilPassOperation  = reader.ReadBoolean();
            bool InheritStencilReference      = reader.ReadBoolean();
            bool InheritStencilZFailOperation = reader.ReadBoolean();
            bool InheritVerticalWrapping      = reader.ReadBoolean();
            bool InheritDepthBias             = true;
            bool InheritDepthTestFunction     = true;
            bool InheritDepthWriteEnabled     = true;

            // Get version 1.1 fields.
            if ((version.Major == 1) && (version.Minor >= 1))
            {
                InheritDepthBias         = reader.ReadBoolean();
                InheritDepthTestFunction = reader.ReadBoolean();
                InheritDepthWriteEnabled = reader.ReadBoolean();
            }

            // Get the size of the sprite.
            sprite.Size = new DX.Size2F(reader.ReadSingle(), reader.ReadSingle());

            // Older versions of the sprite object used pixel space for their texture coordinates.  We will have to
            // fix up these coordinates into texture space once we have a texture loaded.  At this point, there's no guarantee
            // that the texture was loaded safely, so we'll have to defer it until later.
            // Also, older versions used the size the determine the area on the texture to cover.  So use the size to
            // get the texture bounds.
            var textureOffset = new DX.Vector2(reader.ReadSingle(), reader.ReadSingle());

            // Read the anchor.
            // Gorgon v3 anchors are relative, so we need to convert them based on our sprite size.
            sprite.Anchor = new DX.Vector2(reader.ReadSingle() / sprite.Size.Width, reader.ReadSingle() / sprite.Size.Height);

            // Get vertex offsets.
            sprite.CornerOffsets.UpperLeft  = new DX.Vector3(reader.ReadSingle(), reader.ReadSingle(), 0);
            sprite.CornerOffsets.UpperRight = new DX.Vector3(reader.ReadSingle(), reader.ReadSingle(), 0);
            sprite.CornerOffsets.LowerRight = new DX.Vector3(reader.ReadSingle(), reader.ReadSingle(), 0);
            sprite.CornerOffsets.LowerLeft  = new DX.Vector3(reader.ReadSingle(), reader.ReadSingle(), 0);

            // Get vertex colors.
            sprite.CornerColors.UpperLeft  = new GorgonColor(reader.ReadInt32());
            sprite.CornerColors.UpperRight = new GorgonColor(reader.ReadInt32());
            sprite.CornerColors.LowerLeft  = new GorgonColor(reader.ReadInt32());
            sprite.CornerColors.LowerRight = new GorgonColor(reader.ReadInt32());

            // Skip shader information.  Version 1.0 had shader information attached to the sprite.
            if ((version.Major == 1) && (version.Minor < 1))
            {
                if (reader.ReadBoolean())
                {
                    reader.ReadString();
                    reader.ReadBoolean();
                    if (reader.ReadBoolean())
                    {
                        reader.ReadString();
                    }
                }
            }

            // We no longer have an alpha mask function.
            if (!InheritAlphaMaskFunction)
            {
                reader.ReadInt32();
            }

            if (!InheritAlphaMaskValue)
            {
                // Direct 3D 9 used a value from 0..255 for alpha masking, we use
                // a scalar value so convert to a scalar.
                sprite.AlphaTest = new GorgonRangeF(0.0f, reader.ReadInt32() / 255.0f);
            }

            // Set the blending mode.
            if (!InheritBlending)
            {
                // Skip the blending mode.  We don't use it per-sprite.
                reader.ReadInt32();
                reader.ReadInt32();
                reader.ReadInt32();
            }

            // Get alpha blending mode.
            if ((version.Major == 1) && (version.Minor >= 2))
            {
                // Skip the blending mode information.  We don't use it per-sprite.
                reader.ReadInt32();
                reader.ReadInt32();
            }

            TextureWrap  hWrap         = TextureWrap.Clamp;
            TextureWrap  vWrap         = TextureWrap.Clamp;
            SampleFilter filter        = SampleFilter.MinMagMipLinear;
            GorgonColor  samplerBorder = GorgonColor.White;

            // Get horizontal wrapping mode.
            if (!InheritHorizontalWrapping)
            {
                hWrap = ConvertImageAddressToTextureAddress(reader.ReadInt32());
            }

            // Get smoothing mode.
            if (!InheritSmoothing)
            {
                filter = ConvertSmoothingToFilter(reader.ReadInt32());
            }

            // Get stencil stuff.
            if (!InheritStencilCompare)
            {
                // We don't use depth/stencil info per sprite anymore.
                reader.ReadInt32();
            }
            if (!InheritStencilEnabled)
            {
                // We don't enable stencil in the same way anymore, so skip this value.
                reader.ReadBoolean();
            }
            if (!InheritStencilFailOperation)
            {
                // We don't use depth/stencil info per sprite anymore.
                reader.ReadInt32();
            }
            if (!InheritStencilMask)
            {
                // We don't use depth/stencil info per sprite anymore.
                reader.ReadInt32();
            }
            if (!InheritStencilPassOperation)
            {
                // We don't use depth/stencil info per sprite anymore.
                reader.ReadInt32();
            }
            if (!InheritStencilReference)
            {
                // We don't use depth/stencil info per sprite anymore.
                reader.ReadInt32();
            }
            if (!InheritStencilZFailOperation)
            {
                // We don't use depth/stencil info per sprite anymore.
                reader.ReadInt32();
            }

            // Get vertical wrapping mode.
            if (!InheritVerticalWrapping)
            {
                vWrap = ConvertImageAddressToTextureAddress(reader.ReadInt32());
            }

            // Get depth info.
            if ((version.Major == 1) && (version.Minor >= 1))
            {
                if (!InheritDepthBias)
                {
                    // Depth bias values are quite different on D3D9 than they are on D3D11, so skip this.
                    reader.ReadSingle();
                }
                if (!InheritDepthTestFunction)
                {
                    // We don't use depth/stencil info per sprite anymore.
                    reader.ReadInt32();
                }
                if (!InheritDepthWriteEnabled)
                {
                    // We don't use depth/stencil info per sprite anymore.
                    reader.ReadBoolean();
                }

                samplerBorder = new GorgonColor(reader.ReadInt32());

                // The border in the older version defaults to black.  To make it more performant, reverse this value to white.
                if (samplerBorder == GorgonColor.Black)
                {
                    samplerBorder = GorgonColor.White;
                }
            }

            // Get flipped flags.
            sprite.HorizontalFlip = reader.ReadBoolean();
            sprite.VerticalFlip   = reader.ReadBoolean();

            GorgonTexture2DView textureView;

            // Bind the texture (if we have one bound to this sprite) if it's already loaded, otherwise defer it.
            if ((!string.IsNullOrEmpty(imageName)) && (overrideTexture == null))
            {
                GorgonTexture2D texture = graphics.LocateResourcesByName <GorgonTexture2D>(imageName).FirstOrDefault();
                textureView = texture?.GetShaderResourceView();
            }
            else
            {
                textureView = overrideTexture;
            }

            // If we cannot load the image, then fall back to the standard coordinates.
            if (textureView == null)
            {
                sprite.TextureRegion = new DX.RectangleF(0, 0, 1, 1);
            }
            else
            {
                sprite.TextureRegion = new DX.RectangleF(textureOffset.X / textureView.Width,
                                                         textureOffset.Y / textureView.Height,
                                                         sprite.Size.Width / textureView.Width,
                                                         sprite.Size.Height / textureView.Height);
                sprite.TextureSampler = CreateSamplerState(graphics, filter, samplerBorder, hWrap, vWrap);
            }

            sprite.Texture = textureView;

            return(sprite);
        }
示例#24
0
        /// <summary>
        /// Function to initialize the example.
        /// </summary>
        /// <returns>The main window for the application.</returns>
        private static FormMain Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);
            GorgonExample.ShowStatistics        = false;

            FormMain window = GorgonExample.Initialize(new DX.Size2(Settings.Default.Resolution.Width, Settings.Default.Resolution.Height), "The Shadow Gn0s");

            try
            {
                // Create our primary graphics interface.
                IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

                if (adapters.Count == 0)
                {
                    throw new GorgonException(GorgonResult.CannotCreate, "This example requires a Direct3D 11.4 capable video card.\nThe application will now close.");
                }

                _graphics = new GorgonGraphics(adapters[0], log: GorgonApplication.Log);

                // Create our "screen".
                _screen = new GorgonSwapChain(_graphics, window, new GorgonSwapChainInfo("TheShadowGn0s Screen Swap chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                BuildRenderTargets(new DX.Size2(_screen.Width, _screen.Height));


                _backgroundTexture = GorgonTexture2DView.FromFile(_graphics,
                                                                  Path.Combine(GorgonExample.GetResourcePath(@"Textures\TheShadowGn0s\").FullName,
                                                                               "VBBack.jpg"),
                                                                  new GorgonCodecJpeg(),
                                                                  new GorgonTexture2DLoadOptions
                {
                    Name    = "Background Texture",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });

                // Create our 2D renderer.
                _renderer = new Gorgon2D(_graphics);

                _spriteTexture = GorgonTexture2DView.FromFile(_graphics,
                                                              Path.Combine(GorgonExample.GetResourcePath(@"Textures\TheShadowGn0s\").FullName,
                                                                           "0_HardVacuum.png"),
                                                              new GorgonCodecPng(),
                                                              new GorgonTexture2DLoadOptions
                {
                    Name    = "/Images/0_HardVacuum.png",
                    Binding = TextureBinding.ShaderResource,
                    Usage   = ResourceUsage.Immutable
                });

                var spriteCodec = new GorgonV2SpriteCodec(_renderer);
                _sprite1 = spriteCodec.FromFile(Path.Combine(GorgonExample.GetResourcePath(@"Sprites\TheShadowGn0s\").FullName, "Mother.gorSprite"));
                _sprite2 = spriteCodec.FromFile(Path.Combine(GorgonExample.GetResourcePath(@"Sprites\TheShadowGn0s\").FullName, "Mother2c.gorSprite"));

                _gaussBlur = new Gorgon2DGaussBlurEffect(_renderer, 9)
                {
                    BlurRenderTargetsSize = new DX.Size2(_screen.Width / 2, _screen.Height / 2)
                };

                var shadowBuilder = new ShadowBuilder(_renderer, _gaussBlur, _sprite1, _sprite2);
                (GorgonSprite[] shadowSprites, GorgonTexture2DView shadowTexture) = shadowBuilder.Build();
                _shadowSprites = shadowSprites;
                _shadowTexture = shadowTexture;

                var batchStateBuilder = new Gorgon2DBatchStateBuilder();
                var blendStateBuilder = new GorgonBlendStateBuilder();
                _rtvBlendState = batchStateBuilder
                                 .BlendState(blendStateBuilder
                                             .ResetTo(GorgonBlendState.Default)
                                             .DestinationBlend(alpha: Blend.InverseSourceAlpha))
                                 .Build();

                _sprite2.Position = new DX.Vector2((int)(_screen.Width / 2.0f), (int)(_screen.Height / 4.0f));
                _sprite1.Position = new DX.Vector2((int)(_screen.Width / 4.0f), (int)(_screen.Height / 5.0f));

                _bgSprite = _sprite2;
                _fgSprite = _sprite1;

                _screen.BeforeSwapChainResized += (sender, args) =>
                {
                    _blurTexture?.Dispose();
                    _blurTarget?.Dispose();
                    _layer1Texture?.Dispose();
                    _layer1Target?.Dispose();
                };

                window.MouseMove  += Window_MouseMove;
                window.MouseUp    += Window_MouseUp;
                window.MouseWheel += Window_MouseWheel;
                window.KeyUp      += Window_KeyUp;

                _screen.AfterSwapChainResized += (sender, args) => BuildRenderTargets(args.Size);

                GorgonExample.LoadResources(_graphics);

                _helpFont = GorgonExample.Fonts.GetFont(new GorgonFontInfo("Segoe UI", 12.0f, FontHeightMode.Points, "Segoe UI 12pt Bold, Outlined")
                {
                    FontStyle     = FontStyle.Bold,
                    OutlineColor2 = GorgonColor.Black,
                    OutlineColor1 = GorgonColor.Black,
                    OutlineSize   = 2,
                    TextureWidth  = 512,
                    TextureHeight = 256
                });

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
示例#25
0
 /// <summary>
 /// Function to save the sprite data to a stream.
 /// </summary>
 /// <param name="sprite">The sprite to serialize into the stream.</param>
 /// <param name="stream">The stream that will contain the sprite.</param>
 protected abstract void OnSaveToStream(GorgonSprite sprite, Stream stream);
示例#26
0
文件: Program.cs 项目: tmp7701/Gorgon
        /// <summary>
        /// Function to initialize the application.
        /// </summary>
        private static void Initialize()
        {
            _form = new MainForm();
            _form.Show();

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

            // Create the primary swap chain.
            _mainScreen = _graphics.Output.CreateSwapChain("MainScreen", new GorgonSwapChainSettings
            {
                Width      = Settings.Default.ScreenWidth,
                Height     = Settings.Default.ScreenHeight,
                Format     = BufferFormat.R8G8B8A8_UIntNormal,
                Window     = _form,
                IsWindowed = Settings.Default.Windowed
            });

            // Center the display.
            if (_mainScreen.Settings.IsWindowed)
            {
                _form.Location =
                    new Point(
                        _mainScreen.VideoOutput.OutputBounds.Width / 2 - _form.Width / 2 + _mainScreen.VideoOutput.OutputBounds.Left,
                        _mainScreen.VideoOutput.OutputBounds.Height / 2 - _form.Height / 2 + _mainScreen.VideoOutput.OutputBounds.Top);
            }

            // Load the ball texture.
            _ballTexture = _graphics.Textures.FromFile <GorgonTexture2D>("BallTexture", GetResourcePath(@"Textures\Balls\BallsTexture.dds"), new GorgonCodecDDS());

            // Create the 2D interface.
            _2D = _graphics.Output.Create2DRenderer(_mainScreen);
            _2D.IsLogoVisible = true;

            // Set our drawing code to use modulated blending.
            _2D.Drawing.BlendingMode = BlendingMode.Modulate;
            _2D.Drawing.Blending.DestinationAlphaBlend = BlendType.InverseSourceAlpha;

            // Create the wall sprite.
            _wall = _2D.Renderables.CreateSprite("Wall", new Vector2(63, 63), _ballTexture);
            _wall.BlendingMode = BlendingMode.None;

            // Create the ball sprite.
            _ball = _2D.Renderables.CreateSprite("Ball", new Vector2(64, 64), _ballTexture, new Vector2(0.5f, 0.5f));
            _ball.SmoothingMode = SmoothingMode.Smooth;
            _ball.Anchor        = new Vector2(32, 32);
            _ball.Blending.DestinationAlphaBlend = BlendType.InverseSourceAlpha;

            // Create the ball render target.
            _ballTarget = _graphics.Output.CreateRenderTarget("BallTarget", new GorgonRenderTarget2DSettings
            {
                DepthStencilFormat = BufferFormat.Unknown,
                Width         = Settings.Default.ScreenWidth,
                Height        = Settings.Default.ScreenHeight,
                Format        = BufferFormat.R8G8B8A8_UIntNormal,
                Multisampling = GorgonMultisampling.NoMultiSampling
            });
            _2D.Effects.GaussianBlur.BlurRenderTargetsSize = new Size(512, 512);
            _2D.Effects.GaussianBlur.BlurAmount            = 10.0f;

            // Ensure that our secondary camera gets updated.
            _mainScreen.AfterSwapChainResized += (sender, args) =>
            {
                // Fix any objects caught outside of the main target.
                for (int i = 0; i < _ballCount; i++)
                {
                    _ballList[i].Position.X = _ballList[i].Position.X.Max(0).Min(args.Width);
                    _ballList[i].Position.Y = _ballList[i].Position.Y.Max(0).Min(args.Height);
                }

                _ballTarget.Dispose();

                _ballTarget = _graphics.Output.CreateRenderTarget("BallTarget", new GorgonRenderTarget2DSettings
                {
                    DepthStencilFormat = BufferFormat.Unknown,
                    Width         = args.Width,
                    Height        = args.Height,
                    Format        = BufferFormat.R8G8B8A8_UIntNormal,
                    Multisampling = GorgonMultisampling.NoMultiSampling
                });

                Vector2 newTargetSize;
                newTargetSize.X = (512.0f * (args.Width / (float)Settings.Default.ScreenWidth)).Min(512);
                newTargetSize.Y = (512.0f * (args.Height / (float)Settings.Default.ScreenHeight)).Min(512);

                _2D.Effects.GaussianBlur.BlurRenderTargetsSize = (Size)newTargetSize;
                _2D.Effects.Displacement.BackgroundImage       = _ballTarget;
            };

            // Generate the ball list.
            GenerateBalls(Settings.Default.BallCount);

            // Assign event handlers.
            _form.KeyDown += _form_KeyDown;

            // Create statistics render target.
            _statsTarget = _graphics.Output.CreateRenderTarget("Statistics", new GorgonRenderTarget2DSettings
            {
                Width  = 160,
                Height = 66,
                Format = BufferFormat.R8G8B8A8_UIntNormal
            });

            // Draw our stats window frame.
            _2D.Target = _statsTarget;
            _2D.Clear(new GorgonColor(0, 0, 0, 0.5f));
            _2D.Drawing.DrawRectangle(new RectangleF(0, 0, _statsTarget.Settings.Width - 1, _statsTarget.Settings.Height - 1),
                                      new GorgonColor(0.86667f, 0.84314f, 0.7451f, 1.0f));
            _2D.Target = null;

            // Create our font.
            _ballFont = _graphics.Fonts.CreateFont("Arial 9pt Bold", new GorgonFontSettings
            {
                AntiAliasingMode = FontAntiAliasMode.AntiAlias,
                FontStyle        = FontStyle.Bold,
                FontFamilyName   = "Arial",
                FontHeightMode   = FontHeightMode.Points,
                Characters       = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890()_.-+:\u2191\u2193",
                Size             = 9.0f,
                OutlineColor1    = GorgonColor.Black,
                OutlineSize      = 1
            });

            // Statistics text buffer.
            _fpsText  = new StringBuilder(64);
            _helpText = new StringBuilder();
            _helpText.AppendFormat(Resources.HelpText,
                                   _graphics.VideoDevice.Name,
                                   _graphics.VideoDevice.SupportedFeatureLevel,
                                   _graphics.VideoDevice.DedicatedVideoMemory.FormatMemory());

            // Create a static text block.  This will perform MUCH better than drawing the text
            // every frame with DrawString.
            _helpTextSprite          = _2D.Renderables.CreateText("Help Text", _ballFont, _helpText.ToString(), Color.Yellow);
            _helpTextSprite.Position = new Vector2(3, 72);
            _helpTextSprite.Blending.DestinationAlphaBlend = BlendType.InverseSourceAlpha;
        }
示例#27
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), "Lights");

            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
                });
                _screen.BeforeSwapChainResized += Screen_BeforeSwapChainResized;
                _screen.AfterSwapChainResized  += Screen_AfterSwapChainResized;
                // Tell the graphics API that we want to render to the "screen" swap chain.
                _graphics.SetRenderTarget(_screen.RenderTargetView);

                // Load in our texture for our logo background.
                _backgroundLogoTexture = GorgonTexture2DView.FromFile(_graphics,
                                                                      Path.Combine(GorgonExample.GetResourcePath(@"Textures\Lights\").FullName, "lights.dds"),
                                                                      new GorgonCodecDds(),
                                                                      new GorgonTexture2DLoadOptions
                {
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource,
                    Name    = "Logo"
                });

                _torchTexture = GorgonTexture2DView.FromFile(_graphics,
                                                             Path.Combine(GorgonExample.GetResourcePath(@"Textures\Lights\").FullName, "Torch.png"),
                                                             new GorgonCodecPng(),
                                                             new GorgonTexture2DLoadOptions
                {
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource,
                    Name    = "Torch"
                });

                UpdateRenderTarget();

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

                _logoSprite = new GorgonSprite
                {
                    Texture       = _backgroundLogoTexture,
                    Bounds        = new DX.RectangleF(0, 0, _backgroundLogoTexture.Width, _backgroundLogoTexture.Height),
                    TextureRegion = new DX.RectangleF(0, 0, 1, 1),
                    Anchor        = new DX.Vector2(0.5f, 0.5f)
                };

                _torchSprite = new GorgonSprite
                {
                    Texture       = _torchTexture,
                    Bounds        = new DX.RectangleF(0, 0, 55, _torchTexture.Height),
                    TextureRegion = _torchTexture.Texture.ToTexel(new DX.Rectangle(0, 0, 55, _torchTexture.Height)),
                };

                // Create the effect that will light up our sprite(s).
                _lightEffect = new Gorgon2DDeferredLightingEffect(_renderer)
                {
                    FlipYNormal = true // Need this to be true because CrazyBump exported the normal map with Y inverted.
                };

                _lightEffect.Lights.Add(new Gorgon2DLight
                {
                    Color           = new GorgonColor(0.25f, 0.25f, 0.25f),
                    Attenuation     = 75,
                    LightType       = LightType.Point,
                    SpecularEnabled = true,
                    SpecularPower   = 6.0f,
                    Position        = new DX.Vector3((_screen.Width / 2.0f) - 150.0f, (_screen.Height / 2.0f) - 150.0f, -50)
                });
                _lightEffect.Lights.Add(new Gorgon2DLight
                {
                    Color           = GorgonColor.White,
                    Intensity       = 0.075f,
                    LightType       = LightType.Directional,
                    SpecularEnabled = false,
                    Position        = new DX.Vector3(0, 0, -200),
                    LightDirection  = new DX.Vector3(0, 0, 1)
                });

                GorgonExample.LoadResources(_graphics);

                window.MouseMove += Window_MouseMove;
                window.KeyDown   += Window_KeyDown;

                _torchFrameTime = new GorgonTimerQpc();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
示例#28
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), "Animation");

            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 Animation Example Swap Chain")
                {
                    Width  = Settings.Default.Resolution.Width,
                    Height = Settings.Default.Resolution.Height,
                    Format = BufferFormat.R8G8B8A8_UNorm
                });

                _target = GorgonRenderTarget2DView.CreateRenderTarget(_graphics, new GorgonTexture2DInfo(_screen.RenderTargetView, "Video Target")
                {
                    Binding = TextureBinding.ShaderResource
                });
                _targetView = _target.GetShaderResourceView();
                _target.Clear(GorgonColor.CornFlowerBlue);

                // Load our textures.
                var gif = new GorgonCodecGif(decodingOptions: new GorgonGifDecodingOptions
                {
                    ReadAllFrames = true
                });

                // Find out how long to display each frame for.
                // We'll also convert it to milliseconds since GIF stores the delays as 1/100th of a second.
                _frameDelays = gif.GetFrameDelays(Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "metal.gif"))
                               .Select(item => item / 100.0f).ToArray();

                _metal = GorgonTexture2DView.FromFile(_graphics,
                                                      Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "metal.gif"),
                                                      gif,
                                                      new GorgonTexture2DLoadOptions
                {
                    Name    = @"Metal \m/",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });
                _trooper = GorgonTexture2DView.FromFile(_graphics,
                                                        Path.Combine(GorgonExample.GetResourcePath(@"\Textures\Animation\").FullName, "trooper.png"),
                                                        new GorgonCodecPng(),
                                                        new GorgonTexture2DLoadOptions
                {
                    Name    = "Trooper",
                    Usage   = ResourceUsage.Immutable,
                    Binding = TextureBinding.ShaderResource
                });

                GorgonExample.LoadResources(_graphics);

                _renderer       = new Gorgon2D(_graphics);
                _animatedSprite = new GorgonSprite
                {
                    Position = new DX.Vector2(_screen.Width / 2, _screen.Height / 2),
                    Size     = new DX.Size2F(_metal.Width, _metal.Height),
                    Anchor   = new DX.Vector2(0.5f, 0.5f)
                };

                MakeAn80sMusicVideo();

                // We need to set up a blend state so that the alpha in the render target doesn't get overwritten.
                var builder      = new Gorgon2DBatchStateBuilder();
                var blendBuilder = new GorgonBlendStateBuilder();
                _targetBatchState = builder.BlendState(blendBuilder
                                                       .ResetTo(GorgonBlendState.Default)
                                                       .DestinationBlend(alpha: Blend.DestinationAlpha)
                                                       .Build())
                                    .Build();

                return(window);
            }
            finally
            {
                GorgonExample.EndInit();
            }
        }
示例#29
0
        /// <summary>
        /// Function to initialize the example.
        /// </summary>
        private void Initialize()
        {
            GorgonExample.ResourceBaseDirectory = new DirectoryInfo(Settings.Default.ResourceLocation);

            IReadOnlyList <IGorgonVideoAdapterInfo> adapters = GorgonGraphics.EnumerateAdapters(log: GorgonApplication.Log);

            if (adapters.Count == 0)
            {
                throw new GorgonException(GorgonResult.CannotCreate, "This example requires a Direct3D 11.4 capable video card.\nThe application will now close.");
            }

            _graphics = new GorgonGraphics(adapters[0]);

            _leftPanel = new GorgonSwapChain(_graphics,
                                             GroupControl1,
                                             new GorgonSwapChainInfo("Left Panel SwapChain")
            {
                Width  = GroupControl1.ClientSize.Width,
                Height = GroupControl1.ClientSize.Height,
                Format = BufferFormat.R8G8B8A8_UNorm
            });

            _rightPanel = new GorgonSwapChain(_graphics,
                                              GroupControl2,
                                              new GorgonSwapChainInfo(_leftPanel, "Right Panel SwapChain")
            {
                Width  = GroupControl2.ClientSize.Width,
                Height = GroupControl2.ClientSize.Height
            });

            _renderer = new Gorgon2D(_graphics);

            _fontFactory = new GorgonFontFactory(_graphics);
            _appFont     = _fontFactory.GetFont(new GorgonFontInfo(Font.FontFamily.Name, Font.Size * 1.33333f, FontHeightMode.Points, "Form Font")
            {
                Characters    = "SpdtoxDrag me!\u2190:1234567890.",
                TextureWidth  = 128,
                TextureHeight = 128,
                OutlineSize   = 2,
                FontStyle     = FontStyle.Bold,
                OutlineColor1 = GorgonColor.Black,
                OutlineColor2 = GorgonColor.Black
            });

            _torusTexture = GorgonTexture2DView.FromFile(_graphics,
                                                         Path.Combine(GorgonExample.GetResourcePath(@"Textures\GiveMeSomeControl\").FullName, "Torus.png"),
                                                         new GorgonCodecPng(),
                                                         new GorgonTexture2DLoadOptions
            {
                Binding = TextureBinding.ShaderResource,
                Name    = "Torus Animation Sheet",
                Usage   = ResourceUsage.Immutable
            });

            _torusLeft = new GorgonSprite
            {
                Anchor         = new DX.Vector2(0.5f, 0.5f), Size = new DX.Size2F(64, 64),
                TextureSampler = GorgonSamplerState.PointFiltering
            };
            _torusRight = new GorgonSprite
            {
                Anchor         = new DX.Vector2(0.5f, 0.5f), Size = new DX.Size2F(64, 64),
                TextureSampler = GorgonSamplerState.PointFiltering
            };

            BuildAnimation();

            GorgonExample.LoadResources(_graphics);
        }
示例#30
0
 /// <summary>
 /// Function to save the sprite data to a stream.
 /// </summary>
 /// <param name="sprite">The sprite to serialize into the stream.</param>
 /// <param name="stream">The stream that will contain the sprite.</param>
 protected override void OnSaveToStream(GorgonSprite sprite, Stream stream) => throw new NotSupportedException();