<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>invalid operation - Silverlight</title>
    <link>http://blog.invalidoperation.com/</link>
    <description>how do i wrote codes</description>
    <language>en-us</language>
    <copyright>ray</copyright>
    <lastBuildDate>Sun, 14 Mar 2010 21:30:00 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.2.8279.16125</generator>
    <managingEditor>ray.oneill@gmail.com</managingEditor>
    <webMaster>ray.oneill@gmail.com</webMaster>
    <item>
      <trackback:ping>http://blog.invalidoperation.com/Trackback.aspx?guid=1acef3c4-1afa-49d6-9a16-5ff162726c9d</trackback:ping>
      <pingback:server>http://blog.invalidoperation.com/pingback.aspx</pingback:server>
      <pingback:target>http://blog.invalidoperation.com/PermaLink,guid,1acef3c4-1afa-49d6-9a16-5ff162726c9d.aspx</pingback:target>
      <dc:creator>Ray</dc:creator>
      <wfw:comment>http://blog.invalidoperation.com/CommentView,guid,1acef3c4-1afa-49d6-9a16-5ff162726c9d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.invalidoperation.com/SyndicationService.asmx/GetEntryCommentsRss?guid=1acef3c4-1afa-49d6-9a16-5ff162726c9d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I’ve had Bill Reiss’ <a href="http://blogs.silverarcade.com/silverlight-games-101">Silverlight
Games 101</a> blog in my Google reader for a while now, and recently he’s started
a new series started on developing the Asteroids-like “Space Rocks” game under Silverlight
3. Between <a href="http://blogs.silverarcade.com/silverlight-games-101/09/silverlight-space-rocks-game-step-3-sprites-part-2/">part
3</a> and <a href="http://blogs.silverarcade.com/silverlight-games-101/14/silverlight-space-rocks-game-step-4-inheriting-from-sprite/">part
4</a> was a post promoting <a href="http://blogs.silverarcade.com/silverlight-games-101/12/silverlight-setting-dependency-properties-and-the-effect-on-performance/">caching
dependency property values for performance</a>. I’m not a WPF or Silverlight guru
so I can’t really argue with the statement; but it does make sense in the same way
that caching static data in a line of business application does. 
</p>
        <p>
In <a href="http://blogs.silverarcade.com/silverlight-games-101/14/silverlight-space-rocks-game-step-4-inheriting-from-sprite/">part
4</a> we see this in action, in properties on the <em>Sprite</em> class:
</p>
        <pre class="c#" name="code">        public double X
        {
            get
            {
                return x;
            }
            set
            {
                if (x != value)
                {
                    x = value;
                    this.SetValue(Canvas.LeftProperty, x - dw);
                }
            }
        }

        public double Y
        {
            get
            {
                return y;
            }
            set
            {
                if (y != value)
                {
                    y = value;
                   this.SetValue(Canvas.TopProperty, y - dh);
                }
            }
        }</pre>
        <p>
I don’t like the duplication of the caching inside of the class itself, especially
when dependency properties are likely to be used quite heavily in a game, which is
going to be doing things like adjusting position of visual game elements every rendered
frame. Surely, this is unnecessary duplication and we can do better? Behold, the DependencyPropertyCache:
</p>
        <pre class="c#" name="code">using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SpaceRocks
{
    public class DependencyPropertyCache&lt;T&gt;
    {
        private DependencyProperty _dependencyProperty;
        private DependencyObject _parent;

        public DependencyPropertyCache(DependencyObject parent, DependencyProperty property)
        {
            if (parent == null)
                throw new ArgumentNullException("parent");
            if (property == null)
                throw new ArgumentNullException("property");

            _parent = parent;
            _dependencyProperty = property;
        }

        public T Value { get; private set; }

        public void SetValue(T value)
        {
            if (!Value.Equals(value))
            {
                _parent.SetValue(_dependencyProperty, value);
                this.Value = value;
            }
        }
    }
}</pre>
        <p>
Pretty simple, really. Now we can have cached values exposed by the <em>Value </em>property
and update the value using <em>SetValue </em>which does a comparison between old and
new, and only updates the actual dependency property if the new value is different.
Bill was using the inequality operator and this class is using the <em>Equals </em>method
on System.Object, however it wouldn’t be very difficult to modify the cache to constrain
T to implementing IComparable&lt;T&gt;, as System.Double does, and/or a constructor
overload which might take a custom IComparable&lt;T&gt;. So far in the series, there
are only System.Double properties, so I’ve not done that yet.
</p>
        <p>
So now the modified code for the <em>Sprite </em>class from <a href="http://blogs.silverarcade.com/silverlight-games-101/14/silverlight-space-rocks-game-step-4-inheriting-from-sprite/">part
4</a> looks like this:  
</p>
        <pre class="c#" name="code">using System.Windows.Controls;
using Microsoft.Xna.Framework;
using System.Windows;
using System.Windows.Media;

namespace SpaceRocks
{
    public class Sprite : Control
    {
        double dw = 0;
        double dh = 0; 
        static Vector2 gameSize = new Vector2(640, 480);
        private DependencyPropertyCache&lt;double&gt; _x;
        private DependencyPropertyCache&lt;double&gt; _y;
 
        public Sprite()
        {
            this.DefaultStyleKey = typeof(Sprite);
            this.SizeChanged += new SizeChangedEventHandler(Sprite_SizeChanged);
            _x = new DependencyPropertyCache&lt;double&gt;(this, Canvas.LeftProperty);
            _y = new DependencyPropertyCache&lt;double&gt;(this, Canvas.TopProperty);
        }

        void Sprite_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Vector2 pos = Position;           
            
            _x.SetValue(double.NaN);
            _y.SetValue(double.NaN);

            Position = pos;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            FrameworkElement element = VisualTreeHelper.GetChild(this, 0) as FrameworkElement;
            dw = element.Width / 2;
            dh = element.Height / 2;
            Width = element.Width;
            Height = element.Height;
        }

        public double X
        {
            get
            {
                return _x.Value;
            }
            set
            {
                _x.SetValue(value - dw);                
            }
        }

        public double Y
        {
            get
            {
                return _y.Value;
            }
            set
            {
                _y.SetValue(value - dh);                
            }
        }

        public Vector2 Position
        {
            get
            {
                return new Vector2( (float)_x.Value, (float)_y.Value);
            }
            set
            {
                _x.SetValue(value.X);
                _y.SetValue(value.Y);
            }
        }

        public Vector2 Velocity { get; set; }

        public void Update(double elapsedSeconds)
        {
            Position += Velocity * (float)elapsedSeconds;
            if (Position.X &gt; gameSize.X) Position -= new Vector2(gameSize.X, 0);
            if (Position.X &lt; 0) Position += new Vector2(gameSize.X, 0);
            if (Position.Y &gt; gameSize.Y) Position -= new Vector2(0, gameSize.Y);
            if (Position.Y &lt; 0) Position += new Vector2(0, gameSize.Y);
        }
    }
}</pre>
        <p>
Sweet.
</p>
        <img width="0" height="0" src="http://blog.invalidoperation.com/aggbug.ashx?id=1acef3c4-1afa-49d6-9a16-5ff162726c9d" />
      </body>
      <title>Caching Silverlight Dependency Properties</title>
      <guid isPermaLink="false">http://blog.invalidoperation.com/PermaLink,guid,1acef3c4-1afa-49d6-9a16-5ff162726c9d.aspx</guid>
      <link>http://blog.invalidoperation.com/2010/03/14/CachingSilverlightDependencyProperties.aspx</link>
      <pubDate>Sun, 14 Mar 2010 21:30:00 GMT</pubDate>
      <description>&lt;p&gt;
I’ve had Bill Reiss’ &lt;a href="http://blogs.silverarcade.com/silverlight-games-101"&gt;Silverlight
Games 101&lt;/a&gt; blog in my Google reader for a while now, and recently he’s started
a new series started on developing the Asteroids-like “Space Rocks” game under Silverlight
3. Between &lt;a href="http://blogs.silverarcade.com/silverlight-games-101/09/silverlight-space-rocks-game-step-3-sprites-part-2/"&gt;part
3&lt;/a&gt; and &lt;a href="http://blogs.silverarcade.com/silverlight-games-101/14/silverlight-space-rocks-game-step-4-inheriting-from-sprite/"&gt;part
4&lt;/a&gt; was a post promoting &lt;a href="http://blogs.silverarcade.com/silverlight-games-101/12/silverlight-setting-dependency-properties-and-the-effect-on-performance/"&gt;caching
dependency property values for performance&lt;/a&gt;. I’m not a WPF or Silverlight guru
so I can’t really argue with the statement; but it does make sense in the same way
that caching static data in a line of business application does. 
&lt;/p&gt;
&lt;p&gt;
In &lt;a href="http://blogs.silverarcade.com/silverlight-games-101/14/silverlight-space-rocks-game-step-4-inheriting-from-sprite/"&gt;part
4&lt;/a&gt; we see this in action, in properties on the &lt;em&gt;Sprite&lt;/em&gt; class:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;        public double X
        {
            get
            {
                return x;
            }
            set
            {
                if (x != value)
                {
                    x = value;
                    this.SetValue(Canvas.LeftProperty, x - dw);
                }
            }
        }

        public double Y
        {
            get
            {
                return y;
            }
            set
            {
                if (y != value)
                {
                    y = value;
                   this.SetValue(Canvas.TopProperty, y - dh);
                }
            }
        }&lt;/pre&gt;
&lt;p&gt;
I don’t like the duplication of the caching inside of the class itself, especially
when dependency properties are likely to be used quite heavily in a game, which is
going to be doing things like adjusting position of visual game elements every rendered
frame. Surely, this is unnecessary duplication and we can do better? Behold, the DependencyPropertyCache:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SpaceRocks
{
    public class DependencyPropertyCache&amp;lt;T&amp;gt;
    {
        private DependencyProperty _dependencyProperty;
        private DependencyObject _parent;

        public DependencyPropertyCache(DependencyObject parent, DependencyProperty property)
        {
            if (parent == null)
                throw new ArgumentNullException(&amp;quot;parent&amp;quot;);
            if (property == null)
                throw new ArgumentNullException(&amp;quot;property&amp;quot;);

            _parent = parent;
            _dependencyProperty = property;
        }

        public T Value { get; private set; }

        public void SetValue(T value)
        {
            if (!Value.Equals(value))
            {
                _parent.SetValue(_dependencyProperty, value);
                this.Value = value;
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;
Pretty simple, really. Now we can have cached values exposed by the &lt;em&gt;Value &lt;/em&gt;property
and update the value using &lt;em&gt;SetValue &lt;/em&gt;which does a comparison between old and
new, and only updates the actual dependency property if the new value is different.
Bill was using the inequality operator and this class is using the &lt;em&gt;Equals &lt;/em&gt;method
on System.Object, however it wouldn’t be very difficult to modify the cache to constrain
T to implementing IComparable&amp;lt;T&amp;gt;, as System.Double does, and/or a constructor
overload which might take a custom IComparable&amp;lt;T&amp;gt;. So far in the series, there
are only System.Double properties, so I’ve not done that yet.
&lt;/p&gt;
&lt;p&gt;
So now the modified code for the &lt;em&gt;Sprite &lt;/em&gt;class from &lt;a href="http://blogs.silverarcade.com/silverlight-games-101/14/silverlight-space-rocks-game-step-4-inheriting-from-sprite/"&gt;part
4&lt;/a&gt; looks like this:&amp;#160; 
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;using System.Windows.Controls;
using Microsoft.Xna.Framework;
using System.Windows;
using System.Windows.Media;

namespace SpaceRocks
{
    public class Sprite : Control
    {
        double dw = 0;
        double dh = 0; 
        static Vector2 gameSize = new Vector2(640, 480);
        private DependencyPropertyCache&amp;lt;double&amp;gt; _x;
        private DependencyPropertyCache&amp;lt;double&amp;gt; _y;
 
        public Sprite()
        {
            this.DefaultStyleKey = typeof(Sprite);
            this.SizeChanged += new SizeChangedEventHandler(Sprite_SizeChanged);
            _x = new DependencyPropertyCache&amp;lt;double&amp;gt;(this, Canvas.LeftProperty);
            _y = new DependencyPropertyCache&amp;lt;double&amp;gt;(this, Canvas.TopProperty);
        }

        void Sprite_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Vector2 pos = Position;           
            
            _x.SetValue(double.NaN);
            _y.SetValue(double.NaN);

            Position = pos;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            FrameworkElement element = VisualTreeHelper.GetChild(this, 0) as FrameworkElement;
            dw = element.Width / 2;
            dh = element.Height / 2;
            Width = element.Width;
            Height = element.Height;
        }

        public double X
        {
            get
            {
                return _x.Value;
            }
            set
            {
                _x.SetValue(value - dw);                
            }
        }

        public double Y
        {
            get
            {
                return _y.Value;
            }
            set
            {
                _y.SetValue(value - dh);                
            }
        }

        public Vector2 Position
        {
            get
            {
                return new Vector2( (float)_x.Value, (float)_y.Value);
            }
            set
            {
                _x.SetValue(value.X);
                _y.SetValue(value.Y);
            }
        }

        public Vector2 Velocity { get; set; }

        public void Update(double elapsedSeconds)
        {
            Position += Velocity * (float)elapsedSeconds;
            if (Position.X &amp;gt; gameSize.X) Position -= new Vector2(gameSize.X, 0);
            if (Position.X &amp;lt; 0) Position += new Vector2(gameSize.X, 0);
            if (Position.Y &amp;gt; gameSize.Y) Position -= new Vector2(0, gameSize.Y);
            if (Position.Y &amp;lt; 0) Position += new Vector2(0, gameSize.Y);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;
Sweet.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.invalidoperation.com/aggbug.ashx?id=1acef3c4-1afa-49d6-9a16-5ff162726c9d" /&gt;</description>
      <comments>http://blog.invalidoperation.com/CommentView,guid,1acef3c4-1afa-49d6-9a16-5ff162726c9d.aspx</comments>
      <category>Silverlight</category>
    </item>
  </channel>
</rss>