public static void MoveVector2WASD(ref Vector2 pos, ref Rectangle boundingRect) { var keyboard = Keyboard.GetState(); if (keyboard.IsKeyDown(Keys.A)) { pos.X -= 2; boundingRect.Offset(-1,0); } else if (keyboard.IsKeyDown(Keys.D)) { pos.X += 2; boundingRect.Offset(1, 0); } if (keyboard.IsKeyDown(Keys.W)) { pos.Y -= 2; boundingRect.Offset(0, -1); } else if (keyboard.IsKeyDown(Keys.S)) { boundingRect.Offset(0, 1); pos.Y += 2; } }
public void Draw(SpriteBatchProxy spriteBatch) { Rectangle dst = new Rectangle((int)m_location.X - MARGIN, (int)m_location.Y - MARGIN, 16, 16); m_srcRect.X = m_srcRect.Y = 0; for (int j = 0; j <= Math.Floor((double)((m_size.Y + MARGIN * 2) / m_srcRect.Height)); j++) { for (int i = 0; i <= Math.Floor((double)((m_size.X + MARGIN * 2) / m_srcRect.Width)); i++) { spriteBatch.Draw(Application.MagicContentManager.GetTexture("textbox"), dst, m_srcRect, Color.White); dst.Offset(16, 0); if (i == 0) { // first so offset for srcRect m_srcRect.Offset(16, 0); } else if (i == Math.Floor((double)((m_size.X + MARGIN * 2) / m_srcRect.Width)) - 1) { //last m_srcRect.Offset(16, 0); } } dst.Offset(-16 * (int)(Math.Floor((double)((m_size.X + MARGIN * 2) / m_srcRect.Width)) + 1), 16); m_srcRect.X = 0; if (j == 0) { // first so offset for srcRect m_srcRect.Offset(0, 16); } else if (j == Math.Floor((double)((m_size.Y + MARGIN * 2) / m_srcRect.Height)) - 1) { //last m_srcRect.Offset(0, 16); } } m_srcRect.X = m_anim * 16; m_srcRect.Y = 48; dst.Offset((int)(m_size.X + MARGIN * 2) - (16 + (int)m_skip_size.X + 8), -((int)m_skip_size.Y + 8)); spriteBatch.Draw(Application.MagicContentManager.GetTexture("textbox"), dst, m_srcRect, Color.White); dst.Offset(16, 0); spriteBatch.DrawString(Application.MagicContentManager.Font, m_skip, dst.Location.ToVector2(), Color.Black); spriteBatch.DrawString(Application.MagicContentManager.Font, m_text, m_location, Color.Black); }
private void _drawMiniMap() { Texture2D miniMapText = EOGame.Instance.GFXManager.TextureFromResource(GFXTypes.PostLoginUI, 45, true); Character c = World.Instance.MainPlayer.ActiveCharacter; _spriteBatch.Begin(); for (int row = Math.Max(c.Y - 30, 0); row <= Math.Min(c.Y + 30, Map.Height); ++row) { for (int col = Math.Max(c.X - 30, 0); col <= Math.Min(c.X + 30, Map.Width); ++col) { Rectangle miniMapRectSrc = new Rectangle(0, 0, miniMapText.Width / 9, miniMapText.Height); bool isEdge = false; Vector2 loc = _getMiniMapDrawCoordinates(col, row, c); if (c.X == col && c.Y == row) { //draw orange thing miniMapRectSrc.Offset((int)MiniMapGfx.Orange * miniMapRectSrc.Width, 0); } else { isEdge = _drawObjectAndActorIcons(col, row, ref miniMapRectSrc); } _drawGridBox(isEdge, miniMapText, loc, miniMapRectSrc); } } _spriteBatch.End(); }
public override void Draw(GameTime gameTime) { _reactionBar.Draw(gameTime); if (!_gameState.ReactionProgress.IsReactionInProgress) { _spriteBatch.Begin(); var seq = _touchService.Touches; for (int i = 0; i < seq.Count; i++) { var texture = seq[i].Button == ButtonType.Left ? _leftButtonTexture : _rightButtonTexture; var scale = (_reactionBar.BackTexture.Height - 2*LetterVerticalMargin)/texture.Height/2; var rect = new Rectangle(0, 0, (int) (texture.Width*scale), (int) (texture.Height*scale)); rect.Offset(_reactionBar.DestinationRectangle.X + (int) ((i + 0.5)*_oneTouchWidth - rect.Width/2f), _reactionBar.DestinationRectangle.Y + (int) (_reactionBar.DestinationRectangle.Height/2f - rect.Height/2f)); _spriteBatch.Draw(texture, rect, Color.White); } _spriteBatch.End(); } base.Draw(gameTime); }
internal override void Draw(Xna.Framework.Graphics.SpriteBatch ssb) { Rectangle screen = new Rectangle(0, 0, TDVBasicGame.Width, TDVBasicGame.Height); Rectangle dirtSource = new Rectangle(0, 0, TDVBasicGame.Width, TDVBasicGame.Height); dirtSource.Offset(dirtOffset); ssb.Draw(dirt, screen, dirtSource, Color.White); ssb.Draw(current_vignette, screen, vignette2.Bounds, Color.White); ssb.Draw(frame, screen, frame.Bounds, Color.White); frameNum++; if (frameNum % FRAME_DIVISOR == 0) { shakeOffset = rnd.Next(6) - 6; dirtOffset.X = rnd.Next(dirt.Width - TDVBasicGame.Width); dirtOffset.Y = rnd.Next(dirt.Height - TDVBasicGame.Height); if (frameNum % BULB_DIVISOR == 0) { if (rnd.Next(10) == 1) { current_vignette = vignette; } else { current_vignette = vignette2; } } } }
public void DrawSpriteGrid(IDisplayable displayable, SpriteGrid grid) { if (displayable == null || grid == null || displayable.DrawInfo.Visible == false) { return; } Texture2D xnaTec = GetTexture(grid.Texture.ID); XNAColor color = XNAColor.White; int drawIndex = 0; var topLeft = GetScreenPoint(displayable); foreach (var tile in grid.Cells) { XNARec src = GetTextureCell(grid.Texture, tile); XNARec dest = new XNARec((int)topLeft.X, (int)topLeft.Y, src.Width, src.Height); dest.Offset(drawIndex.ToXY(grid.Cells.Columns).Scale(src.Size)); spriteBatch.Draw(xnaTec, dest, src, color); drawIndex++; } }
public void Render(SpriteBatch spriteBatch, Environment env, GameTime time, Rectangle mapDest, float posLerp) { int tile; Rectangle destination; int x = mapDest.X, y = mapDest.Y; int tileWidth = mapDest.Width / Environment.mazeSize_; int tileHeight = mapDest.Height / Environment.mazeSize_; for (int i = 0; i < Environment.mazeSize_; ++i) for (int j = 0; j < Environment.mazeSize_; ++j) { tile = env.maze_[i][j]; destination = new Rectangle(x + j * tileWidth, y + i * tileHeight, tileWidth, tileHeight); if (tile == -1) spriteBatch.Draw(WallTex, destination, Color.White); else { spriteBatch.Draw(FloorTex, destination, Color.White); spriteBatch.Draw(DirtTex, destination, Color.Lerp(Color.Transparent, Color.White, tile / MAX_DIRT)); } } destination = new Rectangle(x + env.agentPosY_ * tileWidth, y + env.agentPosX_ * tileHeight, tileWidth, tileHeight); switch (env.preAction_) { case ActionType.actIDLE: spriteBatch.Draw(CleanerTex, destination, Color.Yellow); break; case ActionType.actSUCK: spriteBatch.Draw(CleanerTex, destination, Color.Green); break; case ActionType.actUP: spriteBatch.Draw(CleanerTex, destination, env.isJustBump ? Color.Red : Color.White); break; case ActionType.actRIGHT: destination.Offset(tileWidth, 0); spriteBatch.Draw(CleanerTex, destination, null, env.isJustBump ? Color.Red : Color.White, MathHelper.PiOver2, Vector2.Zero, SpriteEffects.None, 0f); break; case ActionType.actDOWN: destination.Offset(tileWidth, tileHeight); spriteBatch.Draw(CleanerTex, destination, null, env.isJustBump ? Color.Red : Color.White, MathHelper.Pi, Vector2.Zero, SpriteEffects.None, 0f); break; case ActionType.actLEFT: destination.Offset(0, tileHeight); spriteBatch.Draw(CleanerTex, destination, null, env.isJustBump ? Color.Red : Color.White, -MathHelper.PiOver2, Vector2.Zero, SpriteEffects.None, 0f); break; } }
public static void Initialize(Texture2D texture, Rectangle particaleFrame, Rectangle explosionFrame, int explosionFrameCount) { Texture = texture; ParticleFrame = particaleFrame; ExplosionFrames.Clear(); ExplosionFrames.Add(explosionFrame); for (int x = 1; x < explosionFrameCount; x++) { explosionFrame.Offset(explosionFrame.Width, 0); ExplosionFrames.Add(explosionFrame); } }
public Engine() { //**** Size of the game "view port" int width = 600; int height = 800; bounds = new Rectangle(0, 0, width, height); bounds.Offset((int)((PROPERTIES.screen.Width - width) / 2.0f), (int)((PROPERTIES.screen.Height - height) / 2.0f)); //Create the (unloaded) level objects levels = new Level[4]; levels[0] = new Level01(bounds); levels[1] = new Level02(bounds); levels[2] = new Level03(bounds); levels[3] = new Level04(bounds); }
public Textbox( int screen_width, int screen_height, Texture2D speechPorts, SullyGame g ) { game = g; boxes_of_text = new List<object>(); currently_rendering_text = new List<string>(); vertical_padding = 2; horizontal_padding = 7; long_step = 2; short_step = 1; full_reset(); //textbox.image = Content.Load<Texture2D>( "textbox" ); image = _.MakeBox( 317, 50, _.sg.boxcolors ); speechPortraits = speechPorts; bounds = new Rectangle( 0, 0, image.Width, image.Height ); int yloc = screen_height - bounds.Height - 4; bounds.Offset( ( screen_width - bounds.Width ) / 2, yloc ); speech_bounds = new Rectangle( 2, yloc - 33, 32, 32 ); inner_bounds = bounds; // copy value color_bounds = bounds; inner_bounds.Inflate( -horizontal_padding, -vertical_padding ); color_bounds.Inflate( -2, -2 ); bgColor = new Texture2D( _.sg.GraphicsDevice, 1, 1, false, SurfaceFormat.Color ); bgColor.SetData(new[] { new Color(140, 0, 140) }); McgLayer l = game.renderstack.GetLayer( "textbox" ); RenderDelegate a1 = ( int x, int y ) => { //game.spritebatch.Draw( inactiveBgColor, mainBox.color_bounds, Color.White * .5f ); //game.spritebatch.Draw( mainBox.image, mainBox.bounds, Color.White ); Draw(); }; l.AddNode( new McgNode( a1, l, 0, 0, 300, 300, 3000 ) ); }
// Draw the Animation Strip public void Draw(SpriteBatch spriteBatch) { // Only draw the animation when we are active if (Active) { float rot = rotFrame * 3.1416f * 2.0f / 360.0f; // spriteBatch.Draw(spriteStrip, destinationRect, sourceRect, color); Rectangle offRect = new Rectangle(destinationRect.Left, destinationRect.Top, destinationRect.Width, destinationRect.Height); offRect.Offset(sourceRect.Center.X - sourceRect.Left, sourceRect.Center.Y - sourceRect.Top); spriteBatch.Draw(spriteStrip, offRect, sourceRect, Color.White, rot, //new Vector2(0f, 0f), new Vector2(sourceRect.Center.X - sourceRect.Left, sourceRect.Center.Y - sourceRect.Top), SpriteEffects.None, 0); } }
public ARefillController(Vector2 position, string refillType) { this.IsActive = true; m_position = position; m_refillType = refillType; m_refillArea = new Rectangle(s_refillArea.X, s_refillArea.Y, s_refillArea.Width, s_refillArea.Height); m_refillArea.Offset((int)m_position.X, (int)m_position.Y); Rectangle bounds = new Rectangle(-40, -120, 80, 120); m_collider = new Collider(this, bounds, ColliderType.Scenery); m_animationController = new AnimationController( "Animation/Data/MissionObjects", "Animation/Textures/MissionObjects", AnimationName); }
/// <summary> /// Protected ctor - use the construct() method /// </summary> protected CharacterController( Vector2 startPosition, int speed, Rectangle bounds, ColliderType type, float animationScale, string animationDataPath, string animationTexturePath) { this.m_previousPosition = startPosition; this.m_position = startPosition; this.m_speedMax = speed; bounds.Offset((int)m_position.X, (int)m_position.Y); this.m_collider = new Collider(this, bounds, type); this.AnimationController = new AnimationController(animationDataPath, animationTexturePath); this.AnimationController.ActionTriggered += new ActionTriggeredEventHandler(this.handleAction); this.AnimationController.Scale = animationScale; this.GravityEffect = Gravity.Normal; this.Health = this.MaxHealth; this.m_previousAngle = (float)Math.PI / 2; }
public MessageBox(string text, SpriteFont spriteFont, Vector2 v2Center, BaseGame baseGame, EventHandler<PressEventArgs> OnOK) : base(v2Center, baseGame) { _text = text; _spriteFont = spriteFont; _buttonOK = new Button(new Rectangle(0, 0, 0, 0), "OK", _spriteFont, Color.Black, true); _buttonOK.Press += new EventHandler<PressEventArgs>(_buttonOK_Press); if (OnOK != null) _buttonOK.Press += OnOK; _v2TextSize = _spriteFont.MeasureString(_text); int height = textTopBuffer + (int)(_v2TextSize.Y) + betweenBuffer + _buttonOK.bounds.Height + buttonBottomBuffer; int width = leftBuffer + (int)(_v2TextSize.X) + rightBuffer; Rectangle bounds = new Rectangle((int)this.v2Center.X, (int)this.v2Center.Y, width, height); bounds.Offset(-(bounds.Width / 2), -(bounds.Height / 2)); this.bounds = bounds; Rectangle boundsOK = new Rectangle((this.bounds.Width / 2) - (_buttonOK.bounds.Width / 2), this.bounds.Height - buttonBottomBuffer - _buttonOK.bounds.Height, _buttonOK.bounds.Width, _buttonOK.bounds.Height); _buttonOK.bounds = boundsOK; this.addButton(_buttonOK); }
protected override void DrawHost(GameTime gameTime) { base.DrawHost(gameTime); graphics.GraphicsDevice.Clear(Color.Gray); spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied); Texture2D screen = KinectManager.GetScreen(graphics); if (screen != null) { spriteBatch.Draw(screen, new Rectangle(0, 0, resolution.Width, resolution.Height), new Color(255, 255, 255, 255)); } for (int i = 0; i < games.Length; i++) { drawGameRect(i, spriteBatch); } int border = 25; Rectangle rect = new Rectangle(border, 10, resolution.Width - border * 2, 90); spriteBatch.Draw(titleTexture, rect, new Color(75, 0, 150)); rect.Offset(0, 15); String message = "To play an app, hover over its center. To quit it, put your hands on your head."; TextUtils.DrawTextInRect(spriteBatch, directionsFont, message, rect, Color.White, true); if (PrimarySkeleton != null) { if (cursorVisible) { cursorOpacity = 0.1f + 0.9f * cursorOpacity; } else { cursorOpacity = 0.9f * cursorOpacity; } int width = 50; int height = 50 * cursorTexture.Height / cursorTexture.Width; Color color = Color.White; color.A = (byte)(255 * cursorOpacity); spriteBatch.Draw(cursorTexture, new Rectangle((int)cursorPosition.X, (int)cursorPosition.Y, width, height), null, color, cursorRotation, new Vector2(width / 2, height / 2), SpriteEffects.None, 0); } spriteBatch.End(); }
protected override void Draw() { Update(1f / 60f); if (CurrentScene != null) { DrawingManager.ViewPortSize = new Microsoft.Xna.Framework.Point(this.Width, this.Height); SquidCore.DrawSquidEngineScene(GraphicsDevice, 0.16f, SceneManager.ActiveScene); if (_highlightedItem != null) { Microsoft.Xna.Framework.Rectangle re = _highlightedItem.BoundingRect; if (_highlightedItem.IgnoreCameraPosition) { Vector2 offset = CurrentScene.ActiveCameras[0].Position; //offset *= -1; re.Offset((int)offset.X, (int)offset.Y); } DebugShapes.DrawRectangle(re, Color.Yellow); } foreach (SceneItem item in _selectedItems) { Microsoft.Xna.Framework.Rectangle re = item.BoundingRect; if (item.IgnoreCameraPosition) { Vector2 offset = CurrentScene.ActiveCameras[0].Position; //offset *= -1; re.Offset((int)offset.X, (int)offset.Y); } DebugShapes.DrawRectangle(re, Color.White); } if (PreviewedItem != null) { Vector2 oldPosition = PreviewedItem.Position; Vector2 oldPivot = PreviewedItem.Pivot; int oldLayer = PreviewedItem.Layer; PreviewedItem.Position = Vector2.Zero; PreviewedItem.Layer = 1; PreviewedItem.Pivot = new Vector2(PreviewedItem.BoundingRect.Width / 2f, PreviewedItem.BoundingRect.Height / 2f); PreviewedItem.Update(1f / 60f); PreviewedItem.Draw(1f / 60f); PreviewedItem.Position = oldPosition; PreviewedItem.Layer = oldLayer; PreviewedItem.Pivot = oldPivot; } if (Preferences.ShowCameraBounds == true) { Point size = SceneManager.GlobalDataHolder.NativeResolution; Point safeSize = Point.Zero; safeSize.X = (int)(size.X * 0.8f); safeSize.Y = (int)(size.Y * 0.8f); SquidEngine.Drawing.DebugShapes.DrawRectangle( new Microsoft.Xna.Framework.Rectangle(-size.X / 2, -size.Y / 2, size.X, size.Y), new Color(255, 0, 255, 200)); SquidEngine.Drawing.DebugShapes.DrawRectangle( new Microsoft.Xna.Framework.Rectangle(-safeSize.X / 2, -safeSize.Y / 2, safeSize.X, safeSize.Y), new Color(255, 255, 255, 100)); } if (Preferences.ShowGrid == true) { Point gridSize = Preferences.GridSizes[Preferences.SelectedGrid - 1]; Microsoft.Xna.Framework.Rectangle screenBounds = SceneManager.ActiveScene.ActiveCameras[0].BoundingRect; Point start = new Point((int)Math.Floor((double)screenBounds.X / (double)gridSize.X), (int)Math.Floor((double)screenBounds.Y / (double)gridSize.X)); Point end = new Point(1 + (int)Math.Floor((double)screenBounds.Right / (double)gridSize.X), 1 + (int)Math.Floor((double)screenBounds.Bottom / (double)gridSize.Y)); for (int x = start.X; x <= end.X; x++) { SquidEngine.Drawing.DebugShapes.DrawLine(new Vector2(x * gridSize.X, start.Y * gridSize.Y), new Vector2(x * gridSize.X, end.Y * gridSize.Y), (x == 0) ? Color.Black : Preferences.GridColor); } for (int y = start.Y; y <= end.Y; y++) { SquidEngine.Drawing.DebugShapes.DrawLine(new Vector2(start.X * gridSize.X, y * gridSize.Y), new Vector2(end.X * gridSize.X, y * gridSize.Y), (y == 0) ? Color.Black : Preferences.GridColor); } } SquidCore.RenderSquidEngine(); } }
public override Rectangle ToScreen(Rectangle rect) { rect.Y += TabControl.GetTabRect(this).Height; // drop child controls on pages down below Tabs if (Parent != null) { rect.Offset(Parent.Rectangle.Left, Parent.Rectangle.Top); rect = Parent.ToScreen(rect); } return rect; }
/// <summary> /// Updates the background screen. Unlike most screens, this should not /// transition off even if it has been covered by another screen: it is /// supposed to be covered, after all! This overload forces the /// coveredByOtherScreen parameter to false in order to stop the base /// Update method wanting to transition off. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { if ((lookAtOffset - lookAtTarget).Length() < 0.01f) { if(rand.Next(100)==1) lookAtTarget = new Vector3(((float)rand.NextDouble() * 0.5f) - 0.25f, ((float)rand.NextDouble() * 0.5f) - 0.25f, ((float)rand.NextDouble() * 0.5f) - 0.25f); } lookAtOffset = Vector3.Lerp(lookAtOffset, lookAtTarget, 0.02f); Camera.Position = new Vector3(3f, 0.2f, 16f); Camera.LookAt(new Vector3(0f, 0.5f, 25f) + lookAtOffset, 0f); drawEffect.View =Camera.viewMatrix; drawAlphaEffect.View = Camera.viewMatrix; Parallax.Update(gameTime, new Vector2(((1280 * 4) / MathHelper.TwoPi) * Camera.Yaw, 0f)); if (selectionMode == 0) { bannerTop1Pos = Vector2.Lerp(bannerTop1Pos, new Vector2(150f, 0f), 0.1f); bannerBottom1Pos = bannerTop1Pos + new Vector2(0, 210); bannerTop2Pos = Vector2.Lerp(bannerTop2Pos, new Vector2(400, -230), 0.1f); bannerBottom2Pos = bannerTop2Pos + new Vector2(0, 210); CarPos = Vector2.Lerp(CarPos, new Vector2(ScreenManager.Viewport.Width, ScreenManager.Viewport.Height-50)/2, 0.1f); carScale = MathHelper.Lerp(carScale, 1f, 0.1f); SpotPos = Vector2.Lerp(SpotPos, new Vector2(ScreenManager.Viewport.Width, ScreenManager.Viewport.Height+100)/2, 0.1f); PaintPos = Vector2.Lerp(PaintPos, new Vector2(ScreenManager.Viewport.Width/2, ScreenManager.Viewport.Height - 150) , 0.1f); paintCarAlpha = MathHelper.Lerp(paintCarAlpha, 1f, 0.1f); cupPosition = Vector2.Lerp(cupPosition, new Vector2(ScreenManager.Viewport.Width + 500, ScreenManager.Viewport.Height / 2), 0.1f); leftCupRect = new Rectangle((int)cupPosition.X - 350, (int)cupPosition.Y - 100, 50, 200); rightCupRect = new Rectangle((int)cupPosition.X + 300, (int)cupPosition.Y - 100, 50, 200); trophyPos = Vector2.Lerp(trophyPos, new Vector2(- 400, (ScreenManager.Viewport.Height / 2) + 50), 0.1f); } else { bannerTop1Pos = Vector2.Lerp(bannerTop1Pos, new Vector2(150f, -50f), 0.1f); bannerBottom1Pos = bannerTop1Pos + new Vector2(0, 210); bannerTop2Pos = Vector2.Lerp(bannerTop2Pos, new Vector2(400f, 0f), 0.1f); bannerBottom2Pos = bannerTop2Pos + new Vector2(0, 210); paintCarAlpha = MathHelper.Lerp(paintCarAlpha, 0f, 0.1f); carScale = MathHelper.Lerp(carScale, 0.5f, 0.1f); CarPos = Vector2.Lerp(CarPos, bannerBottom1Pos - new Vector2(0, ((bannerBottom1Pos.Y - (bannerTop1Pos.Y + texList["banner-top"].Height)) / 2) - 1f), 0.1f); SpotPos = Vector2.Lerp(SpotPos, new Vector2(ScreenManager.Viewport.Width / 2, ScreenManager.Viewport.Height + 500f), 0.1f); PaintPos = Vector2.Lerp(PaintPos, new Vector2(ScreenManager.Viewport.Width / 2, ScreenManager.Viewport.Height + 500f), 0.1f); cupPosition = Vector2.Lerp(cupPosition, new Vector2(500 + ((ScreenManager.Viewport.Width - 500)/2), ScreenManager.Viewport.Height / 2), 0.1f); trophyPos = Vector2.Lerp(trophyPos, new Vector2(((ScreenManager.Viewport.Width/ 2)-300), (ScreenManager.Viewport.Height / 2) + 50), 0.1f); leftCupRect = new Rectangle((int)cupPosition.X - 350, (int)cupPosition.Y - 100, 50, 200); rightCupRect = new Rectangle((int)cupPosition.X + 300, (int)cupPosition.Y - 100, 50, 200); for (int i = 0; i < 3; i++) { if (cupTracks[i].HasLoaded) { trackPos[i]++; if (trackPos[i] == cupTracks[i].Length) trackPos[i] = 0; } } } for (int i = 0; i < Cups.Count; i++) { Cups[i].Position = Vector2.Lerp(Cups[i].Position, cupPosition + new Vector2((i - selectedCup) * (200 * (1f - (Math.Abs(i - selectedCup) * 0.20f))), 0), 0.1f); //Cups[i].Position = Vector2.Lerp(Cups[i].Position, cupPosition + new Vector2((i - selectedCup) * (200 * (1f - (Math.Abs(i - selectedCup) * 0.25f))), 0), 0.1f); Cups[i].Scale = MathHelper.Lerp(Cups[i].Scale, 1f - (Math.Abs(i - selectedCup) * 0.25f), 0.1f); } redRect = new Rectangle((int)PaintPos.X - (texList["colors"].Width / 2), (int)PaintPos.Y - (texList["colors"].Height / 2), texList["colors"].Width, 40); greenRect = redRect; greenRect.Offset(0, 60); blueRect = greenRect; blueRect.Offset(0, 60); carSpinTime += gameTime.ElapsedGameTime.TotalMilliseconds; if (carSpinTime > 200) { carSpinTime = 0; carFrame--; if (carFrame == -1) carFrame = 7; } if (IsExiting && selectionMode==1) { if (TransitionPosition >= 0.95f) { if (!loadedGameplay) { AudioController.StopMusic(); LoadingScreen.Load(ScreenManager, false, null, new GameplayScreen(selectedCup, carColor)); loadedGameplay = true; } } } base.Update(gameTime, otherScreenHasFocus, false); }
public override int update(KeyboardState kb, MouseState ms) { speed = Game1.speed; timer += speed; anim_baller.update(); //ballerPos = new Vector2(hoopPos.X - 4 * (anim_baller.getBoundingBox().Width), hoopPos.Y + img_hoop.Height - anim_baller.getBoundingBox().Height); switch (state) { case State.START: MediaPlayer.Play(bgm); playedEndSound = false; anim_baller.stopLoop(); anim_baller.goToFrame(0); anim_baller.animateThis = false; gameStatus = -1; Random rand = new Random(); hoopPos = new Vector2(768, 384); anim_baller.updateRenderLocation(new Vector2(1, 1)); ballerPos = new Vector2(hoopPos.X - 4 * (anim_baller.getBoundingBox().Width), hoopPos.Y + img_hoop.Height - anim_baller.getBoundingBox().Height); powerBgPos = new Vector2(ballerPos.X, ballerPos.Y + img_baller.Height); powerWinPos = new Vector2(powerBgPos.X + rand.Next(225) + 225, ballerPos.Y + img_baller.Height); powerCurPos = new Vector2(ballerPos.X, ballerPos.Y + img_baller.Height); powerBg = new Rectangle(); powerBg.Width = 500; powerBg.Height = 40; powerBg.Offset((int)powerBgPos.X, (int)powerBgPos.Y); powerWin = new Rectangle(); powerWin.Width = 100; powerWin.Height = 40; powerWin.Offset((int)powerWinPos.X, (int)powerWinPos.Y); powerCur = new Rectangle(); powerCur.Width = 10; powerCur.Height = 40; powerCur.Offset((int)powerCurPos.X, (int)powerCurPos.Y); throwing = false; hasThrown = false; barDir = 0; //Ready to go! stateTimer = 0.0f; state = State.INTRO; break; case State.INTRO: stateTimer += speed; if (stateTimer >= gameIntroTimer) { stateTimer = 0.0f; state = State.PLAY; } break; case State.PLAY: stateTimer += speed; if (stateTimer >= gamePlayTimer) { stateTimer = 0.0f; state = State.LOSE; } if (kb.IsKeyDown(Keys.Space) && throwing == false && hasThrown == false) { anim_baller.goToFrame(1); throwing = true; barDir = 1 * (speed * 0.75f) * 250; powerCur.X += (int)Math.Ceiling(barDir); } if (kb.IsKeyDown(Keys.Space) && throwing == true && hasThrown == false) { anim_baller.goToFrame(1); if (powerCur.X >= (powerBg.X + powerBg.Width) && barDir > 0) { powerCur.X = powerBg.X + powerBg.Width; barDir = -1 * speed * 250; } else if (powerCur.X <= powerBg.X && barDir < 0) { barDir = 1 * speed * 250; } powerCur.X += (int)Math.Ceiling(barDir); } if (!kb.IsKeyDown(Keys.Space) && throwing == true && hasThrown == false) { hasThrown = true; if ((powerCur.X >= powerWin.X) && (powerCur.X <= (powerWin.X + powerWin.Width))) { anim_baller.animateThis = true; anim_baller.goToFrame(5); anim_baller.loopAnimation(5, 6); ballerPos = new Vector2(hoopPos.X - 75, hoopPos.Y - 35); stateTimer = 0.0f; state = State.WIN; } else { anim_baller.goToFrame(4); ballerPos = new Vector2(hoopPos.X - 75, hoopPos.Y - 35); stateTimer = 0.0f; state = State.LOSE; } } break; case State.WIN: stateTimer += speed; if (!playedEndSound) { snd_win.Play(); playedEndSound = true; } if (stateTimer >= gameEndTimer) { stateTimer = 0.0f; gameStatus = 1; state = State.EXIT; } break; case State.LOSE: if (!playedEndSound) { snd_lose.Play(); playedEndSound = true; } stateTimer += speed; if (stateTimer >= gameEndTimer) { stateTimer = 0.0f; gameStatus = 0; state = State.EXIT; } break; case State.EXIT: MediaPlayer.Stop(); int temp = gameStatus; gameStatus = -1; state = State.START; return temp; default: break; } return -1; }
/// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { // TODO: Add your update code here newgameRect = new Rectangle(150,20, 150,150); helpRect = new Rectangle(150,190, 150,150); creditsRect = new Rectangle(150, 360, 150, 150); quitRect = new Rectangle(150, 530, 150, 150); newgameRect1 = new Rectangle(450, 20, 450, 170); helpRect1 = new Rectangle(450, 190, 450, 170); creditsRect1 = new Rectangle(450, 360, 450, 170); quitRect1 = new Rectangle(450, 530, 450, 170); arrowRect = new Rectangle((int)arr_position.X, (int)arr_position.Y, 32, 32); MouseState mouseState = Mouse.GetState(); if (mouseState.X != prevMouseState.X || mouseState.Y != prevMouseState.Y) { arr_position = new Vector2(mouseState.X, mouseState.Y); prevMouseState = mouseState; } arrowRect = new Rectangle((int)arr_position.X, (int)arr_position.Y, 32, 32); if (arrowRect.Intersects(newgameRect) && mouseState.LeftButton == ButtonState.Pressed) { newgameRect.Inflate(10, 10); newgameRect1.Offset(50, 0); g2state = true; } else if (arrowRect.Intersects(newgameRect)) { newgameRect.Inflate(10, 10); newgameRect1.Offset(50, 0); } if (arrowRect.Intersects(helpRect) && mouseState.LeftButton == ButtonState.Pressed) { helpRect.Inflate(10, 10); helpRect1.Offset(50,0); helpstate = true; } else if (arrowRect.Intersects(helpRect)) { helpRect.Inflate(10, 10); helpRect1.Offset(50, 0); } if (arrowRect.Intersects(creditsRect) && mouseState.LeftButton == ButtonState.Pressed) { creditsRect.Inflate(10, 10); creditsRect1.Offset(50, 0); g4state = true; } else if (arrowRect.Intersects(creditsRect)) { creditsRect.Inflate(10, 10); creditsRect1.Offset(50, 0); } if (arrowRect.Intersects(quitRect) && mouseState.LeftButton == ButtonState.Pressed) { g3state = true; } else if (arrowRect.Intersects(quitRect)) { quitRect.Inflate(10, 10); quitRect1.Offset(50, 0); } base.Update(gameTime); }
private void updateGameRects(float friction) { int offY = 100; int offX = 40; int height = (resolution.Height - offY) / 2; int width = height; int border = 30; for (int i = 0; i < gameRects.Length; i++) { int offI = i - 2 * gameRectOffset; int oX = offI < 0 ? (offI - 1) / 2 : offI / 2, oY = Math.Abs(offI) % 2; Rectangle rect = new Rectangle(border, border + offY, width - border * 2, height - border * 2); rect.Offset(new Point(oX * width + offX, oY * height)); gameRects[i] = new Rectangle((int)Math.Round(lerp(gameRects[i].X, rect.X, friction)), (int)Math.Round(lerp(gameRects[i].Y, rect.Y, friction)), rect.Width, rect.Height); } }
//This will return what enemy is currently overlapping with the player's shot (or //(-1, -1) if there isn't one). private Tuple<int, int> ShotEnemy() { //First define a rectangle for the shot. Rectangle shotRect = new Rectangle((int)playerShotPosition.X, (int)playerShotPosition.Y, (int)shotSize.X, (int)shotSize.Y); //Next, check if it intersects with any of the X rectangles. Only do it if it's //beyond a certain point though. if (playerShotPosition.X + shotSize.X > enemyProperties.InitialX) { for (int i = 0; i < enemyProperties.XCount; i++) { if (shotRect.Intersects(enemyXRectangles[i])) { for (int j = 0; j < enemyProperties.YCount; j++) { Rectangle tempRect = new Rectangle(enemyYRectangles[j].X, enemyYRectangles[j].Y, enemyYRectangles[j].Width, enemyYRectangles[j].Height); tempRect.Offset(new Point(0, (int)enemyCurrentY)); if (shotRect.Intersects(tempRect)) { return new Tuple<int, int>(i, j); } } //If the loop exited, it means the bullet doesn't intersect //with any of the Y rectangles. return new Tuple<int, int>(-1, -1); } } } //If the loop exited, it means the bullet doesn't intersect with any //of the X rectangles. return new Tuple<int, int>(-1, -1); }
/// <summary> /// Offset a rectangle by a given vector using the ceiling of the absolute vector values. /// The original rectangle is not modified, since the rect is passed by value. /// </summary> /// <param name="rect">Rectangle to be modified.</param> /// <param name="offset">Offset vector, absolute value rounded up.</param> /// <returns>Offset rectangle.</returns> public Rectangle OffsetRectangle(Rectangle rect, Vector2 offset) { rect.Offset(offset.X == 0 ? 0 : (offset.X > 0 ? (int)offset.X + 1 : (int)offset.X - 1), offset.Y == 0 ? 0 : (offset.Y > 0 ? (int)offset.Y + 1 : (int)offset.Y - 1)); return rect; }
// Returns a rectangle based on the sprite's position and image height/width public Rectangle GetSpriteRectangle(int offsetX, int offsetY) { int height, width; if (animationFrames > 0) { height = image.Height; width = image.Width / animationFrames; } else { height = image.Height; width = image.Width; } Rectangle rec = new Rectangle((int)position.X - (int)origin.X, (int)position.Y - (int)origin.Y, width, height); rec.Offset(offsetX, offsetY); return rec; }
/// <summary> /// Изменяем положение прямоугольника на экране на -ScrollX только по 0Х /// </summary> /// <param name="rect"></param> /// <returns></returns> public static Rectangle GetScreenRect(Rectangle rect) { //Rectangle screenRect = rect; //screenRect.Offset(-ScrollX, 0); //return screenRect; rect.Offset(-ScrollX, 0); return rect; }
public void Draw(SpriteBatchProxy spriteBatch) { Rectangle dst = new Rectangle((int)_location.X - MARGIN, (int)_location.Y - MARGIN, 16, 16); _srcRect.X = _srcRect.Y = 0; for (int j = 0; j <= Math.Floor((double)((_size.Y + MARGIN * 2) / _srcRect.Height)); j++) { for (int i = 0; i <= Math.Floor((double)((_size.X + MARGIN * 2) / _srcRect.Width)); i++) { spriteBatch.Draw(Application.MagicContentManager.GetTexture("textbox"), dst, _srcRect, Color.White); dst.Offset(16, 0); if (i == 0) { // first so offset for srcRect _srcRect.Offset(16, 0); } else if (i == Math.Floor((double)((_size.X + MARGIN * 2) / _srcRect.Width)) - 1) { //last _srcRect.Offset(16, 0); } } dst.Offset(-16 * (int)(Math.Floor((double)((_size.X + MARGIN * 2) / _srcRect.Width)) + 1), 16); _srcRect.X = 0; if (j == 0) { // first so offset for srcRect _srcRect.Offset(0, 16); } else if (j == Math.Floor((double)((_size.Y + MARGIN * 2) / _srcRect.Height)) - 1) { //last _srcRect.Offset(0, 16); } } _srcRect.X = _anim * 16; _srcRect.Y = 48; dst.Offset((int)(_size.X + MARGIN * 2) - (16 + (int)_skip_size.X + 8), -((int)_skip_size.Y + 8)); spriteBatch.Draw(Application.MagicContentManager.GetTexture("textbox"), dst, _srcRect, Color.White); dst.Offset(16, 0); spriteBatch.DrawString(Application.MagicContentManager.Font, _skip, dst.Location.ToVector2(), Color.Black); // Draw controls var devices = Application.InputManager.GetLinkedDevices(LogicalPlayerIndex.One).FindAll(d => d.IsConnected); int x = COLSIZE; for (int i = 0; i < devices.Count; i++) { var device = devices[i]; Vector2 loc = _location; // Display name string name = LocalizedStrings.GetString("Move"); spriteBatch.DrawString(Application.MagicContentManager.Font, name, loc, Color.White); ButtonPrinter.DrawThumbstickLeft(spriteBatch, device, loc + new Vector2(i == 1 ? x - (COLSIZE / 3) : x, i == 1 ? 40 : 0), Color.White); name = LocalizedStrings.GetString("Jump"); loc.Y += 40 * devices.Count; spriteBatch.DrawString(Application.MagicContentManager.Font, name, loc, Color.White); ButtonPrinter.Draw(spriteBatch, MappingButtons.A, device, loc + new Vector2(x, 0), Color.White); name = LocalizedStrings.GetString("Walk"); loc.Y += 40; spriteBatch.DrawString(Application.MagicContentManager.Font, name, loc, Color.White); ButtonPrinter.Draw(spriteBatch, MappingButtons.X, device, loc + new Vector2(x, 0), Color.White); name = LocalizedStrings.GetString("Action"); loc.Y += 40; spriteBatch.DrawString(Application.MagicContentManager.Font, name, loc, Color.White); ButtonPrinter.Draw(spriteBatch, MappingButtons.Y, device, loc + new Vector2(x, 0), Color.White); x += COLSIZE / 2; } }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("hudfont"); LoadTex("arrow"); LoadTex("colors"); LoadTex("triangles"); LoadTex("square"); paintPos = new Vector2(GraphicsDevice.Viewport.Width - 215, GraphicsDevice.Viewport.Height-100); viewRT = new RenderTarget2D(GraphicsDevice, 800,600, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); viewRect = new Rectangle(0, GraphicsDevice.Viewport.Height - 600, 800, 600); worldMatrix = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Down); viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, -10), new Vector3(0, 0, 0), Vector3.Up); projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 800f/600f, 0.001f, 100f); sprite = new VoxelSprite(16, 16,16, GraphicsDevice); drawEffect = new BasicEffect(GraphicsDevice) { World = worldMatrix, View = viewMatrix, Projection = projectionMatrix, VertexColorEnabled = true, //LightingEnabled = true }; drawEffect.EnableDefaultLighting(); cursorEffect = new BasicEffect(GraphicsDevice) { World = worldMatrix, View = viewMatrix, Projection = projectionMatrix, VertexColorEnabled = true }; redRect = new Rectangle((int)paintPos.X - (texList["colors"].Width / 2), (int)paintPos.Y - (texList["colors"].Height / 2), texList["colors"].Width, 40); greenRect = redRect; greenRect.Offset(0, 60); blueRect = greenRect; blueRect.Offset(0, 60); swatches[0]= new Color(255, 255, 255); swatches[1]= new Color(255, 0, 0); swatches[2]= new Color(0, 255, 0); swatches[3]= new Color(0, 0, 255); swatches[4]= new Color(255, 255, 0); swatches[5]= new Color(255, 0, 255); swatches[6]= new Color(0, 255, 255); swatches[7]= new Color(81, 81, 81); swatches[8]= new Color(183, 183, 183); swatches[9]= new Color(0, 0, 0); Rectangle swRect = new Rectangle(GraphicsDevice.Viewport.Width - 420, 170, 410, 30); for (int i = 0; i < 10; i++) { swatchRects[i] = swRect; swRect.Offset(0, 40); } nextFrameRect = new Rectangle(GraphicsDevice.Viewport.Width - 75, 25, 50, 100); prevFrameRect = new Rectangle(25, 25, 50, 100); selectedColor = swatches[0]; }
public virtual Rectangle GetRectangle() { rect = new Rectangle(); rect.Offset((int)(basePosition.X + collisionMargins.X), (int)(basePosition.Y + collisionMargins.Y)); rect.Width = spriteSheet.SourceRectangle(0).Width - (int)(collisionMargins.X + collisionMargins.Z); rect.Height = spriteSheet.SourceRectangle(0).Height - (int)(collisionMargins.Y + collisionMargins.W); return rect; }
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // background var sourceRectangle = new Rectangle(0, 0, _viewportAdapter.VirtualWidth, _viewportAdapter.VirtualHeight); sourceRectangle.Offset(_camera.Position); _spriteBatch.Begin(samplerState: SamplerState.LinearWrap, transformMatrix: _camera.GetViewMatrix()); _spriteBatch.Draw(_backgroundTexture, _camera.Position, sourceRectangle, Color.White); _spriteBatch.End(); // entities _spriteBatch.Begin(samplerState: SamplerState.LinearClamp, blendState: BlendState.AlphaBlend, transformMatrix: _camera.GetViewMatrix()); _entityManager.Draw(_spriteBatch); _spriteBatch.End(); // hud _spriteBatch.Begin(); _spriteBatch.DrawString(_font, string.Format("Score: {0}", _score), Vector2.One, Color.White); _spriteBatch.End(); _guiManager.Draw(gameTime); base.Draw(gameTime); }
public override void Initialize() { Viewport viewport = MobileFortressClient.Game.GraphicsDevice.Viewport; Texture2D tex = Resources.Menus.Title.LoginButton; Rectangle rect = new Rectangle(0, 290, tex.Width, tex.Height); loginButton = new UIElement(this, tex, rect); loginButton.Clicked += LoginClick; loginButton.MouseOver += MouseOver; loginButton.MouseOff += MouseOff; loginButton.color = Color.Black; Manager.Elements.Add(loginButton); tex = Resources.Menus.Title.OptionsButton; rect = new Rectangle(0, 370, tex.Width, tex.Height); optionsButton = new UIElement(this, tex, rect); optionsButton.Clicked += OptionsClick; optionsButton.MouseOver += MouseOver; optionsButton.MouseOff += MouseOff; optionsButton.color = Color.Black; Manager.Elements.Add(optionsButton); tex = Resources.Menus.Title.ExitButton; rect = new Rectangle(0, 450, tex.Width, tex.Height); exitButton = new UIElement(this, tex, rect); exitButton.Clicked += ExitClick; exitButton.MouseOver += MouseOver; exitButton.MouseOff += MouseOff; exitButton.color = Color.Black; Manager.Elements.Add(exitButton); pointerTex = Resources.Menus.Title.Pointer; pointerDimensions = new Rectangle(0, 0, pointerTex.Width, pointerTex.Height); loginMenu = Resources.Menus.Title.LoginMenu; loginDimensions = new Rectangle(viewport.Width / 2 - loginMenu.Width / 2, viewport.Height, loginMenu.Width, loginMenu.Height); tex = Resources.Menus.Title.LoginConfirmButton; rect = new Rectangle(25, 9, tex.Width, tex.Height); rect.Offset(loginDimensions.Location); loginConfirmButton = new UIElement(this, tex, rect); loginConfirmButton.Clicked += ConfirmClick; Manager.Elements.Add(loginConfirmButton); tex = Resources.Menus.Title.TextBox; rect = new Rectangle(186, 6, tex.Width,tex.Height); rect.Offset(loginDimensions.Location); usernameBar = new UITextBox(this, tex, rect, false); rect = new Rectangle(186, 42, tex.Width, tex.Height); rect.Offset(loginDimensions.Location); passwordBar = new UITextBox(this, tex, rect, true); Manager.Elements.Add(usernameBar); Manager.Elements.Add(passwordBar); loginBackButton = new UIStandardButton(this, new Point(128, 128), "Back"); loginBackButton.dimensions.Offset(loginDimensions.Location); loginBackButton.hasButton = true; loginBackButton.customFont = Resources.Menus.BaroqueScript16; loginBackButton.Clicked += LoginCancel; Manager.Elements.Add(loginBackButton); }
public Rectangle offset(Rectangle rectangle) { rectangle.Offset(PointPosition); return rectangle; }
public void Draw() { string _hoverText = ""; MouseState _ms = Mouse.GetState(); foreach (SpaceObject _so in SpaceObjects //.FindAll(x => !x.HasTag("carried")) .FindAll(x => x.HasTag("!carried")) .FindAll(x => x.HasTag("!docked")) .OrderBy(x => x.Depth) ) { if(!_so.Visible) continue; #region maindrawing Vector2 _sp = Game.Camera.WorldToScreen(_so.Position); Rectangle _screenRect = new Rectangle( (int)(_sp.X), (int)(_sp.Y), Math.Max((int)(_so.Size.X * Game.Camera.GetZoom()),1), Math.Max((int)(_so.Size.Y * Game.Camera.GetZoom()),1) ); if (Game.Camera.Rectangle.Contains( new Point( (int)_so.Position.X, (int)_so.Position.Y) ) ) { DrawManager.AddCall( new BasicDrawCall( _so.Texture ?? Res.Textures["generic"], _screenRect, null, Color.White, (float)_so.Rotation, new Vector2( _so.Texture.Width / 2f, _so.Texture.Height / 2f ), 0f ) ); } #endregion #region selectionboxes _screenRect.Offset( new Point( (int)(-_so.Size.X * Game.Camera.GetZoom() / 2f), (int)(-_so.Size.Y * Game.Camera.GetZoom() / 2f)) ); if(true) { bool _selected = UIBindings.Get("Selected"). Contains(_so); bool _targeted = UIBindings.Get("Targeted"). Contains(_so); if(_selected) { if(_targeted) _screenRect.Offset(new Point(1, 1)); Utility.DrawOutlinedRectangle( _screenRect, new Color(0f, 1f, 0f, 0.5f) ); if(_targeted) _screenRect.Offset(new Point(-1, -1)); } if(_targeted) { if(_selected) _screenRect.Offset(new Point(-1, -1)); Utility.DrawOutlinedRectangle( _screenRect, new Color(1f, 0f, 0f, 0.5f) ); if(_selected) _screenRect.Offset(new Point(1, 1)); } } #endregion if (_screenRect.Contains(new Point(_ms.X, _ms.Y))) { _hoverText += "\n" + _so.Name; } } Utility.DropShadowText( "log font", _hoverText, new Vector2( _ms.X - Res.GetFont("log font") .MeasureString(_hoverText).X/2 + 10, _ms.Y - Res.GetFont("log font") .MeasureString(_hoverText).Y ), Color.Black, Color.White ); drawBoxSelection(); }
public bool SaveAsGif(AnimationItem aniItem, string fileName, ImageHandlerConfig config, bool options) { var rec = new AnimationRecoder(this.GraphicsDevice); rec.Items.Add(aniItem); int length = rec.GetMaxLength(); int delay = Math.Max(10, config.MinDelay); var timeline = rec.GetGifTimeLine(delay, 655350); // calc available canvas area rec.ResetAll(); Microsoft.Xna.Framework.Rectangle bounds = aniItem.Measure(); if (length > 0) { IEnumerable <int> delays = timeline?.Take(timeline.Length - 1) ?? Enumerable.Range(0, (int)Math.Ceiling(1.0 * length / delay) - 1); foreach (var frameDelay in delays) { rec.Update(TimeSpan.FromMilliseconds(frameDelay)); var rect = aniItem.Measure(); bounds = Microsoft.Xna.Framework.Rectangle.Union(bounds, rect); } } bounds.Offset(aniItem.Position); // customize clip/scale options AnimationClipOptions clipOptions = new AnimationClipOptions() { StartTime = 0, StopTime = length, Left = bounds.Left, Top = bounds.Top, Right = bounds.Right, Bottom = bounds.Bottom, OutputWidth = bounds.Width, OutputHeight = bounds.Height, }; if (options) { var frmOptions = new FrmGifClipOptions() { ClipOptions = clipOptions, ClipOptionsNew = clipOptions, }; if (frmOptions.ShowDialog() == DialogResult.OK) { var clipOptionsNew = frmOptions.ClipOptionsNew; clipOptions.StartTime = clipOptionsNew.StartTime ?? clipOptions.StartTime; clipOptions.StopTime = clipOptionsNew.StopTime ?? clipOptions.StopTime; clipOptions.Left = clipOptionsNew.Left ?? clipOptions.Left; clipOptions.Top = clipOptionsNew.Top ?? clipOptions.Top; clipOptions.Right = clipOptionsNew.Right ?? clipOptions.Right; clipOptions.Bottom = clipOptionsNew.Bottom ?? clipOptions.Bottom; clipOptions.OutputWidth = clipOptionsNew.OutputWidth ?? (clipOptions.Right - clipOptions.Left); clipOptions.OutputHeight = clipOptionsNew.OutputHeight ?? (clipOptions.Bottom - clipOptions.Top); } else { return(false); } } // validate params bounds = new Rectangle( clipOptions.Left.Value, clipOptions.Top.Value, clipOptions.Right.Value - clipOptions.Left.Value, clipOptions.Bottom.Value - clipOptions.Top.Value ); var targetSize = new Point(clipOptions.OutputWidth.Value, clipOptions.OutputHeight.Value); var startTime = clipOptions.StartTime.Value; var stopTime = clipOptions.StopTime.Value; if (bounds.Width <= 0 || bounds.Height <= 0 || targetSize.X <= 0 || targetSize.Y <= 0 || startTime < 0 || stopTime > length || stopTime - startTime < 0) { return(false); } length = stopTime - startTime; // create output dir string framesDirName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".frames"); if (config.SavePngFramesEnabled && !Directory.Exists(framesDirName)) { Directory.CreateDirectory(framesDirName); } // pre-render rec.ResetAll(); switch (config.BackgroundType.Value) { default: case ImageBackgroundType.Transparent: rec.BackgroundColor = Color.TransparentBlack; break; case ImageBackgroundType.Color: rec.BackgroundColor = System.Drawing.Color.FromArgb(255, config.BackgroundColor.Value).ToXnaColor(); break; case ImageBackgroundType.Mosaic: rec.BackgroundImage = MonogameUtils.CreateMosaic(GraphicsDevice, config.MosaicInfo.Color0.ToXnaColor(), config.MosaicInfo.Color1.ToXnaColor(), Math.Max(1, config.MosaicInfo.BlockSize)); break; } // select encoder GifEncoder enc = AnimateEncoderFactory.CreateEncoder(fileName, targetSize.X, targetSize.Y, config); var encParams = AnimateEncoderFactory.GetEncoderParams(config.GifEncoder.Value); // pipeline functions IEnumerable <Tuple <byte[], int> > MergeFrames(IEnumerable <Tuple <byte[], int> > frames) { byte[] prevFrame = null; int prevDelay = 0; foreach (var frame in frames) { byte[] currentFrame = frame.Item1; int currentDelay = frame.Item2; if (prevFrame == null) { prevFrame = currentFrame; prevDelay = currentDelay; } else if (memcmp(prevFrame, currentFrame, (IntPtr)prevFrame.Length) == 0) { prevDelay += currentDelay; } else { yield return(Tuple.Create(prevFrame, prevDelay)); prevFrame = currentFrame; prevDelay = currentDelay; } } if (prevFrame != null) { yield return(Tuple.Create(prevFrame, prevDelay)); } } IEnumerable <int> RenderDelay() { int t = 0; while (t < length) { int frameDelay = Math.Min(length - t, delay); t += frameDelay; yield return(frameDelay); } } IEnumerable <int> ClipTimeline(int[] _timeline) { int t = 0; for (int i = 0; i < timeline.Length; i++) { var frameDelay = timeline[i]; if (t < startTime) { if (t + frameDelay > startTime) { frameDelay = t + frameDelay - startTime; t = startTime; } else { t += frameDelay; continue; } } if (t + frameDelay < stopTime) { yield return(frameDelay); t += frameDelay; } else { frameDelay = stopTime - t; yield return(frameDelay); break; } } } int prevTime = 0; async Task <int> ApplyFrame(byte[] frameData, int frameDelay) { byte[] gifData = null; if (!encParams.SupportAlphaChannel && config.BackgroundType.Value == ImageBackgroundType.Transparent) { using (var rt2 = rec.GetGifTexture(config.BackgroundColor.Value.ToXnaColor(), config.MinMixedAlpha)) { if (gifData == null) { gifData = new byte[frameData.Length]; } rt2.GetData(gifData); } } else { gifData = frameData; } var tasks = new List <Task>(); // save each frame as png if (config.SavePngFramesEnabled) { tasks.Add(Task.Run(() => { string pngFileName = Path.Combine(framesDirName, $"{prevTime}_{prevTime + frameDelay}.png"); unsafe { fixed(byte *pFrameBuffer = frameData) { using (var bmp = new System.Drawing.Bitmap(targetSize.X, targetSize.Y, targetSize.X * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, new IntPtr(pFrameBuffer))) { bmp.Save(pngFileName, System.Drawing.Imaging.ImageFormat.Png); } } } })); } // append frame data to gif stream tasks.Add(Task.Run(() => { // TODO: only for gif here? frameDelay = Math.Max(10, (int)(Math.Round(frameDelay / 10.0) * 10)); unsafe { fixed(byte *pGifBuffer = gifData) { enc.AppendFrame(new IntPtr(pGifBuffer), frameDelay); } } })); await Task.WhenAll(tasks); prevTime += frameDelay; return(prevTime); } async Task RenderJob(IProgressDialogContext context, CancellationToken cancellationToken) { bool isCompareAndMergeFrames = timeline == null; // build pipeline IEnumerable <int> delayEnumerator = timeline == null?RenderDelay() : ClipTimeline(timeline); var step1 = delayEnumerator.TakeWhile(_ => !cancellationToken.IsCancellationRequested); var frameRenderEnumerator = step1.Select(frameDelay => { rec.Draw(); rec.Update(TimeSpan.FromMilliseconds(frameDelay)); return(frameDelay); }); var step2 = frameRenderEnumerator.TakeWhile(_ => !cancellationToken.IsCancellationRequested); var getFrameData = step2.Select(frameDelay => { using (var t2d = rec.GetPngTexture()) { byte[] frameData = new byte[t2d.Width * t2d.Height * 4]; t2d.GetData(frameData); return(Tuple.Create(frameData, frameDelay)); } }); var step3 = getFrameData.TakeWhile(_ => !cancellationToken.IsCancellationRequested); if (isCompareAndMergeFrames) { var mergedFrameData = MergeFrames(step3); step3 = mergedFrameData.TakeWhile(_ => !cancellationToken.IsCancellationRequested); } var step4 = step3.Select(item => ApplyFrame(item.Item1, item.Item2)); // run pipeline bool isPlaying = this.IsPlaying; try { this.IsPlaying = false; rec.Begin(bounds, targetSize); if (startTime > 0) { rec.Update(TimeSpan.FromMilliseconds(startTime)); } context.ProgressMin = 0; context.ProgressMax = length; foreach (var task in step4) { int currentTime = await task; context.Progress = currentTime; } } catch (Exception ex) { context.Message = $"Error: {ex.Message}"; throw; } finally { rec.End(); enc.Dispose(); this.IsPlaying = isPlaying; } } var dialogResult = ProgressDialog.Show(this.FindForm(), "Exporting...", "Save animation file...", true, false, RenderJob); return(dialogResult == DialogResult.OK); }