Exemple #1
0
 public static void DisableScissor(this SpriteBatch spriteBatch)
 {
     spriteBatch.End();
     spriteBatch.GraphicsDevice.ScissorRectangle = _oldScissor;
     spriteBatch.Begin(_sortMode, _blendState, _samplerState, _depthStencilState, _rasterizerState, _effect,
         _matrix);
 }
        public static void DrawFilledCircle(this PrimitiveBatch primitiveBatch, Vector2 position, float radius, Color color)
        {
            primitiveBatch.Begin(PrimitiveType.TriangleList);
            int steps = 20;
            float step = MathHelper.TwoPi / steps;

            for (int i = 0; i < (steps + 1); i++)
            {
                float x = radius * (float)Math.Cos(i * step);
                float y = radius * (float)Math.Sin(i * step);

                if (i != 0)
                {
                    primitiveBatch.AddVertex(position + new Vector2(x, y), color);
                }

                if (i != steps)
                {
                    primitiveBatch.AddVertex(position, color);
                    primitiveBatch.AddVertex(position + new Vector2(x, y), color);

                }

            }

            primitiveBatch.End();
        }
Exemple #3
0
        /// <summary>
        ///     Starts the specified batch.
        /// </summary>
        /// <param name="batch">The batch.</param>
        /// <param name="useCamera">if set to <c>true</c> camera matrix will be applied.</param>
        /// <param name="sortMode">The sort mode.</param>
        /// <param name="blendState">State of the blend.</param>
        /// <param name="samplerState">State of the sampler.</param>
        /// <param name="depthStencilState">State of the depth stencil.</param>
        /// <param name="rasterizerState">State of the rasterizer.</param>
        /// <param name="effect">The effect.</param>
        /// <param name="transform">The transformation matrix.</param>
        public static void Start(this SpriteBatch batch,
            bool useCamera = false,
            SpriteSortMode sortMode = SpriteSortMode.Deferred,
            BlendState blendState = null,
            SamplerState samplerState = null,
            DepthStencilState depthStencilState = null,
            RasterizerState rasterizerState = null,
            Effect effect = null,
            Matrix? transform = null)
        {
            var matrix = Manager.IsWinForms ? Matrix.Identity : Manager.Settings.Resolution.Matrix;

            if (useCamera)
            {
                matrix = Manager.Camera.Matrix*matrix;
            }

            if (transform.HasValue)
            {
                matrix = transform.Value*matrix;
            }

            _sortMode = sortMode;
            _blendState = blendState;
            _samplerState = samplerState;
            _depthStencilState = depthStencilState;
            _rasterizerState = rasterizerState;
            _effect = effect;
            _matrix = matrix;

            batch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, matrix);
        }
        /// <summary>
        /// Asynchronously initiates the set of animations associated with the storyboard.
        /// </summary>
        /// <param name="storyboard">A storyboard which will be executed asynchronously.</param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public static Task BeginAsync(this Storyboard storyboard)
        {
            if (storyboard == null)
                throw new NullReferenceException();

            // it doesn't really matter which type is used here.
            var tcs = new TaskCompletionSource<bool>();
            EventHandler handler = null;
            handler = (sender, e) =>
            {
                storyboard.Completed -= handler;
                tcs.TrySetResult(true);
            };

            storyboard.Completed += handler;
            try
            {
                storyboard.Begin();
            }
            catch
            {
                storyboard.Completed -= handler;
                throw;
            }

            return tcs.Task;
        }
Exemple #5
0
 public static void EnableScissor(this SpriteBatch spriteBatch, Rectangle rect)
 {
     spriteBatch.End();
     _oldScissor = spriteBatch.GraphicsDevice.ScissorRectangle;
     spriteBatch.GraphicsDevice.ScissorRectangle = rect;
     spriteBatch.Begin(_sortMode, _blendState, _samplerState, _depthStencilState,
         new RasterizerState {ScissorTestEnable = true}, _effect, _matrix);
 }
 public static void Begin(this Storyboard storyboard, int duration)
 {
     var d = new Duration(TimeSpan.FromMilliseconds(duration));
     foreach (var child in storyboard.Children) {
         child.Duration = d;
     }
     storyboard.Begin();
 }
 /// <summary>
 /// Draws a poly line.
 /// Doesn't require SpriteBatch.Begin() or SpriteBatch.End()
 /// <param name="points">The points.</param>
 /// <param name="color">The color.</param>
 /// <param name="width">The width.</param>
 /// <param name="closed">Whether the shape should be closed.</param>
 public static void DrawPolyLine(this SpriteBatch spriteBatch, Vector2[] points, Color color, int width = 1, bool closed = false)
 {
     spriteBatch.Begin();
     for (int i = 0; i < points.Length - 1; i++)
         spriteBatch.DrawLine(points[i], points[i + 1], color, width);
     if (closed)
         spriteBatch.DrawLine(points[points.Length - 1], points[0], color, width);
     spriteBatch.End();
 }
        public static void DrawLine(this PrimitiveBatch primBatch, Line line, Color color)
        {
            primBatch.Begin(PrimitiveType.LineList);

            primBatch.AddVertex((Vector2)line.Start, color);
            primBatch.AddVertex((Vector2)line.End, color);

            primBatch.End();
        }
        public static Task<Storyboard> PlayAsync(this Storyboard storyboard)
        {
            var tcs = new TaskCompletionSource<Storyboard>();

            storyboard.Completed += (sender, o) => tcs.SetResult(storyboard);
            storyboard.Begin();

            return tcs.Task;
        }
		public static void DrawImmediate( this SpriteBatch sb,
			Texture2D texture,
			Rectangle destinationRectangle,
			Color color ) {
			sb.Begin();

			sb.Draw( texture, destinationRectangle, color );

			sb.End();

		}
        public static void Begin(this Storyboard storyboard, Action callback)
        {
            EventHandler<object> handler = null;
            handler = (s, e) => {
                if (callback != null) callback();
                storyboard.Completed -= handler;
            };
            storyboard.Completed += handler;

            storyboard.Begin();
        }
		public static void DrawStringImmediate( this SpriteBatch sb, SpriteFont font,
			string text, Vector2 pos, Color color ) {
			sb.Begin( SpriteBlendMode.AlphaBlend,
					 SpriteSortMode.Immediate,
					 SaveStateMode.SaveState );

			sb.DrawString( font,
				text,
				pos,
				color );

			sb.End();

		}
        public static Task RunAsync(this Storyboard @this)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            EventHandler handler = null;
            handler = delegate
            {
                @this.Completed -= handler;
                tcs.TrySetResult(null);
            };
            @this.Completed += handler;
            @this.Begin();

            return tcs.Task;
        }
        public static void Begin(this Storyboard storyboard, int duration, Action callback)
        {
            EventHandler<object> handler = null;
            handler = (s, e) => {
                if (callback != null) callback();
                storyboard.Completed -= handler;
            };
            storyboard.Completed += handler;

            var d = new Duration(TimeSpan.FromMilliseconds(duration));
            foreach (var child in storyboard.Children) {
                child.Duration = d;
            }
            storyboard.Begin();
        }
        /// <summary>
        /// Helper draws a translucent black fullscreen sprite, used for fading
        /// screens in and out, and for darkening the background behind popups.
        /// </summary>
        public static void FadeBackBufferToBlack(this SpriteBatch spriteBatch, float alpha)
        {
            GraphicsDevice device = spriteBatch.GraphicsDevice;
              Viewport viewport = device.Viewport;

              Texture2D blankTexture = new Texture2D(device, 1, 1);
              blankTexture.SetData<Color>(new Color[] { Color.White });

              spriteBatch.Begin();

              spriteBatch.Draw(blankTexture,
                       new Rectangle(0, 0, viewport.Width, viewport.Height),
                       Color.Black * alpha);

              spriteBatch.End();
        }
Exemple #16
0
		public static Task BeginAsync(this Storyboard storyboard) {
			var tcs = new TaskCompletionSource<bool>();
			if (storyboard == null) {
				tcs.SetException(new ArgumentNullException());
			}
			else {
				EventHandler onComplete = null;
				onComplete = delegate(object s, EventArgs e) {
					storyboard.Completed -= onComplete;
					tcs.SetResult(true);
				};
				storyboard.Completed += onComplete;
				storyboard.Begin();
			}
			return tcs.Task;
		}
 //private readonly static ILog Log = LogManager.GetLogger(typeof(UnitOfWorkHelpers).FullName);
 public static void DoInTransaction(this IUnitOfWork uow, Action action)
 {
     uow.Begin();
     try
     {
         action.Invoke();
         uow.Commit();
     }
     catch (Exception ex)
     {
         //Log.Error(string.Format("Exception thrown in transaction. Action method: {0}, action Target: {1}.",
         //    action.Method, action.Target), ex);
         uow.RollBack();
         throw;
     }
 }
Exemple #18
0
 public static void PrerenderLayer(this SpriteBatch spriteBatch, TiledMap map, Layer layer)
 {
     bool layerIsDrawn = layer.IsDrawn;
     layer.IsDrawn = true;
     GraphicsDevice graphics = spriteBatch.GraphicsDevice;
     RenderTargetBinding[] initialRenderTargets = graphics.GetRenderTargets();
     RenderTarget2D renderTarget = new RenderTarget2D(graphics, map.TotalWidth, map.TotalHeight);
     graphics.SetRenderTarget(renderTarget);
     layer.Texture = renderTarget;
     graphics.Clear(Color.Transparent);
     spriteBatch.Begin();
     spriteBatch.Draw(map, layer, Vector2.Zero);
     spriteBatch.End();
     graphics.SetRenderTargets(initialRenderTargets);
     layer.IsDrawn = layerIsDrawn;
     layer.IsPrerendered = true;
 }
 public static Task BeginAsync(this Storyboard storyboard)
 {
     System.Threading.Tasks.TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
     if (storyboard == null)
         tcs.SetException(new ArgumentNullException());
     else
     {
         EventHandler<object> onComplete = null;
         onComplete = (s, e) => {
             storyboard.Completed -= onComplete;
             tcs.SetResult(true);
         };
         storyboard.Completed += onComplete;
         storyboard.Begin();
     }
     return tcs.Task;
 }
 public static void Render(
     this SpriteBatch spriteBatch,
     Effect effect,
     Texture2D texture,
     ref Vector2 position,
     ref Color color)
 {
     spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
     {
         foreach (EffectPass pass in effect.CurrentTechnique.Passes)
         {
             pass.Apply();
             spriteBatch.Draw(texture, position, color);
         }
     }
     spriteBatch.End();
 }
        public static Task BeginAsync(this Storyboard storyboard)
        {
            storyboard.ThrowIfNull("storyboard");

            var tcs = new TaskCompletionSource<bool>();

            EventHandler onComplete = null;
            onComplete  = (s, e) =>
            {
                // sure ref set to null.
                storyboard.Completed -= onComplete;
                tcs.SetResult(true);
            };
            storyboard.Completed += onComplete;

            storyboard.Begin();

            return tcs.Task;
        }
        public static Task BeginAsync(this Storyboard storyboard)
        {
            var taskSource = new TaskCompletionSource<object>();

            EventHandler<object> completed = null;

            completed += (s, e) =>
            {
                storyboard.Completed -= completed;

                taskSource.SetResult(null);
            };

            storyboard.Completed += completed;

            storyboard.Begin();

            return taskSource.Task;
        }
        public static void DrawLine(this SpriteBatch spriteBatch, Texture2D pixelTexture, float x0, float y0, float x1, float y1)
        {
            spriteBatch.Begin();
            bool steep = (Math.Abs(y1 - y0) > Math.Abs(x1 - x0));
            if (steep)
            {
                Swap(ref x0, ref y0);
                Swap(ref x1, ref y1);
            }
            if (x0 > x1)
            {
                Swap(ref x0, ref x1);
                Swap(ref y0, ref y1);
            }
            float deltax = x1 - x0;
            float deltay = Math.Abs(y1 - y0);
            float error = 0;
            float deltaerror = deltay / deltax;
            int ystep;
            float y = y0;
            ystep = (y0 < y1) ? 1 : -1;
            for (float x = x0; x < x1; x++)
            {
                Vector2 position;
                if (steep)
                    position = new Vector2(y, x);
                else

                    position = new Vector2(x, y);
                spriteBatch.Draw(pixelTexture, position, Color.White);
                error += deltaerror;
                if (error >= 0.5f)
                {
                    y = y + ystep;
                    error -= 1.0f;
                }
            }
            spriteBatch.End();
        }
        /// <summary>
        /// Performs the given action as a transaction with the given name</summary>
        /// <param name="context">Transaction context or null</param>
        /// <param name="transaction">Transaction action</param>
        /// <param name="transactionName">Transaction name</param>
        /// <returns>True if the transaction succeeded and false if it was cancelled (i.e.,
        /// InvalidTransactionException was thrown)</returns>
        /// <remarks>In the implementation of 'transaction', throw InvalidTransactionException
        /// to cancel the transaction and log a warning message to the user (unless the
        /// InvalidTransactionException's ReportError is false).</remarks>
        public static bool DoTransaction(this ITransactionContext context, 
            Action transaction, string transactionName)
        {
            // If we are already in a transaction just perform the action
            // Let all exceptions "bubble up" and be handled by the outer transaction
            if (context != null && context.InTransaction)
            {
                transaction();
                return true;
            }
            
            try
            {
                if (context != null)
                    context.Begin(transactionName);

                //Transactions can be canceled in the call to Begin. When this occurs,
                //we want to skip doing the transaction and the end calls.
                if (context != null && !context.InTransaction)
                    return false;

                transaction();

                if (context != null)
                    context.End();
            }
            catch (InvalidTransactionException ex)
            {
                if (context != null && context.InTransaction)
                    context.Cancel();

                if (ex.ReportError)
                    Outputs.WriteLine(OutputMessageType.Error, ex.Message);
                return false;
            }
            return true;
        }
Exemple #25
0
        private static Task BeginAsync(this Storyboard story)
        {
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            if (story == null)
            {
                tcs.SetException(new ArgumentNullException());
            }
            else
            {
                EventHandler<object> onComplete = null;
                onComplete = (s, e) =>
                {
                    story.Completed -= onComplete;

                    // Subtract the counter of completed Storyboards:
                    _storyCompleteCounter--;
//DEBUG             Logging.Inst.LogMessage("Storyboard completed. Number of open Storyboards left: " + _storyCompleteCounter + ".\n");

                    tcs.SetResult(true);
                };
                story.Completed += onComplete;
                story.Begin();
            }
            return tcs.Task;
        }
 public static void BeginCamera(this SpriteBatch mBatch, Camera2D camera)
 {
     mBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, SamplerState.AnisotropicClamp, DepthStencilState.Default, RasterizerState.CullNone, null, camera.GetViewTransformationMatrix());
 }
 public static void BeginCamera(this SpriteBatch mBatch, Camera2D camera, BlendState bstate)
 {
     mBatch.Begin(SpriteSortMode.Deferred, bstate, SamplerState.AnisotropicWrap, DepthStencilState.Default, RasterizerState.CullNone, null, camera.GetViewTransformationMatrix());
 }
 public static void Begin(this SpriteBatch spriteBatch, SpriteSortMode spriteSortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, Effect effect, Camera camera, Rectangle scissor)
 {
     spriteBatch.GraphicsDevice.ScissorRectangle = scissor;
     spriteBatch.Begin(spriteSortMode, blendState, samplerState, depthStencilState, _cullRasterizerState, effect, camera.View);
 }
Exemple #29
0
        /// <summary>
        /// Consume an arbitrary number of whitespace characters
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private static JsonParserContext ConsumeWhiteSpace(
            this JsonParserContext ctx
            )
        {
            JSonReader src = ctx.Begin();

            for (int p = src.Position, len = src.Text.Length; p < len; p++)
            {
                if (WhiteSpace.IndexOf(src.Text[p]) < 0)
                {
                    src.Position = p;
                    break;
                }
            }

            return ctx;
        }
Exemple #30
0
        /// <summary>
        /// Consume a JSON string token
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="throws"></param>
        /// <returns></returns>
        private static JsonParserContext ConsumeString(
            this JsonParserContext ctx,
            bool throws
            )
        {
            if (ctx.ConsumeWhiteSpace().ConsumeAnyChar("\"", throws).IsSucceeded)
            {
                JSonReader src = ctx.Begin();

                for (int p = src.Position, len = src.Text.Length; p < len; p++)
                {
                    if ((src.Text[p]) == '"')
                    {
                        ctx.SetResult(
                            new JValue { BoxedValue = src.Text.Substring(src.Position, p - src.Position) }
                            );

                        src.Position = p + 1;
                        break;
                    }
                }
            }

            return ctx;
        }