<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nick Gravelyn</title>
	<atom:link href="http://nickgravelyn.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nickgravelyn.com</link>
	<description></description>
	<lastBuildDate>Mon, 08 Feb 2010 06:33:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Generic UI for parameter editing</title>
		<link>http://nickgravelyn.com/2010/02/generic-ui-for-parameter-editing/</link>
		<comments>http://nickgravelyn.com/2010/02/generic-ui-for-parameter-editing/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 06:33:48 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1342</guid>
		<description><![CDATA[I&#8217;ve spent a good amount of the weekend thinking up designs that would allow me to quickly add new UI types into Shader Toy to support all sorts of parameter types. I think I&#8217;ve finally got something that works fairly well. What I&#8217;ve done is create a very simple interface that represents what a given [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve spent a good amount of the weekend thinking up designs that would allow me to quickly add new UI types into Shader Toy to support all sorts of parameter types. I think I&#8217;ve finally got something that works fairly well. What I&#8217;ve done is create a very simple interface that represents what a given UI must support:</p>
<pre class="brush: csharp;">public interface IParameterControl
{
	EffectParameter Parameter { get; set; }

	void CopyValue();
	void PasteValue();
}</pre>
<p>Like I said, very simple. Each UI control must allow me to get and set the EffectParameter it is editing as well as supporting copy/paste functionality. Next I created a mapping for matching a parameter type to a control type, taking into account annotations. Right now I don&#8217;t have much but this is the part that will fill up as time goes on:</p>
<pre class="brush: csharp;">private readonly Dictionary&lt;Type, Dictionary&lt;string, Type&gt;&gt; parameterEditorTypes =
	new Dictionary&lt;Type, Dictionary&lt;string, Type&gt;&gt;
	{
		{
			typeof(Vector4),
			new Dictionary&lt;string, Type&gt;
			{
				{ &quot;color&quot;, typeof(ColorChooser) }
			}
		}
	};</pre>
<p>Basically what that means is that we first look up what type the parameter is. In this case a float4/Vector4. Next we look up the &#8220;UIType&#8221; annotation on the parameter and use that to find what Type of control we need. In this case that&#8217;s a ColorChooser UI. Obviously we&#8217;d also want some defaults and lots more in here, but this is just where I&#8217;m starting.</p>
<p>Finally the meat of the operation. I have this method wired up for when I select a new item in my parameter list:</p>
<pre class="brush: csharp;">private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
	groupBox1.Controls.Clear();

	if (listBox1.SelectedIndex &lt; 0)
	{
		currentParameter = null;
		currentControl = null;
		groupBox1.Text = &quot;{No Parameter Selected}&quot;;
		return;
	}

	currentParameter = parameters[listBox1.SelectedIndex];
	groupBox1.Text = currentParameter.Name;

	bool isArray = currentParameter.Elements.Count &gt; 1;
	int arraySize = currentParameter.Elements.Count;

	Type currentParameterType;

	switch (currentParameter.ParameterType)
	{
		case EffectParameterType.Bool:
			currentParameterType = isArray ? typeof(bool[]) : typeof(bool);
			break;
		case EffectParameterType.Int32:
			currentParameterType = isArray ? typeof(int[]) : typeof(int);
			break;
		case EffectParameterType.Single:
		{
			if (currentParameter.RowCount == 1)
			{
				switch (currentParameter.ColumnCount)
				{
					case 1:
						currentParameterType = isArray ? typeof(float[]) : typeof(float);
						break;
					case 2:
						currentParameterType = isArray ? typeof(Vector2[]) : typeof(Vector2);
						break;
					case 3:
						currentParameterType = isArray ? typeof(Vector3[]) : typeof(Vector3);
						break;
					case 4:
						currentParameterType = isArray ? typeof(Vector4[]) : typeof(Vector4);
						break;
					default:
						currentParameterType = null;
						break;
				}
			}
			else
			{
				currentParameterType = isArray ? typeof(Matrix[]) : typeof(Matrix);
			}
			break;
		}
		case EffectParameterType.String:
		currentParameterType = typeof(string);
			break;
		case EffectParameterType.Texture:
		case EffectParameterType.Texture2D:
			currentParameterType = typeof(Texture2D);
			break;
		default:
			currentParameterType = null;
			break;
	}

	if (currentParameterType == null)
		return;

	string uiType = string.Empty;

	foreach (var annotation in currentParameter.Annotations)
	{
		if (annotation.Name == &quot;UIType&quot;)
		{
			uiType = annotation.GetValueString().ToLower();
			break;
		}
	}

	Type editorType = null;
	Dictionary&lt;string, Type&gt; editorMatch = null;
	if (parameterEditorTypes.TryGetValue(currentParameterType, out editorMatch) &amp;&amp;
		editorMatch.TryGetValue(uiType, out editorType))
	{
		currentControl = Activator.CreateInstance(editorType) as IParameterControl;
		currentControl.Parameter = currentParameter;
		Control c = currentControl as Control;
		c.Location = new Point(12, 24);
		groupBox1.Controls.Add(c);
	}
}</pre>
<p>That goes and figures out exactly what type of parameter we have, then we find the UIType annotation, and lastly we use those two pieces of information to figure out what type of control we want to use. We create an instance, set the parameter, position it, and add it to the group box. I&#8217;ll have to see if this holds up as I go, but for just colors right now it works quite well.</p>
<p>The idea behind all of this is to reduce the effort for implementing more UI for other parameter types. Before I had all sorts of hard coded types and different code paths based on type. With this new system, I just have to implement the new UI types and add them to my big dictionary mapping and this method will automatically work for the new UI. Should allow me to finally get down to making more UI for editing parameters.</p>
<p>And of course, what post on Shader Toy would be complete without yet another video. You&#8217;ll see the new color UI as well as me using copy/paste. Otherwise it&#8217;s nothing all that amazing. I just like making videos. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><center><!-- Smart Youtube --><span class="youtube"><object width="750" height="430"><param name="movie" value="http://www.youtube.com/v/SHRvpOY0ERU&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" /><param name="allowFullScreen" value="true" /><embed wmode="transparent" src="http://www.youtube.com/v/SHRvpOY0ERU&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowfullscreen="true" width="750" height="430" ></embed><param name="wmode" value="transparent" /></object></span></center></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/02/generic-ui-for-parameter-editing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Leveraging JavaScript&#8217;s eval method in C#</title>
		<link>http://nickgravelyn.com/2010/02/leveraging-javascripts-eval-method-in-c/</link>
		<comments>http://nickgravelyn.com/2010/02/leveraging-javascripts-eval-method-in-c/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 19:37:23 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1328</guid>
		<description><![CDATA[One thing I want to support in Shader Toy is the idea of formulaic parameters. For example, any float parameter might define itself in the UI as:
time * 2 + otherParameter^2
Where &#8216;time&#8217; is a value supplied by my editor for the total running time of the editor and &#8216;otherParameter&#8217; is some other parameter in the [...]]]></description>
			<content:encoded><![CDATA[<p>One thing I want to support in Shader Toy is the idea of formulaic parameters. For example, any float parameter might define itself in the UI as:</p>
<p>time * 2 + otherParameter^2</p>
<p>Where &#8216;time&#8217; is a value supplied by my editor for the total running time of the editor and &#8216;otherParameter&#8217; is some other parameter in the shader code. I want this to work. It&#8217;s fairly trivial to do value substitution, replacing those names with other numbers, but to evaluate that at runtime is something that, using just C#, is quite non-trivial. </p>
<p>I started off doing some internet searches to see what can be done. I found that Mono has an Evaluator class built in to leverage the C# compiler and evaluate arbitrary C# code at runtime without the mess of handling your own compiler instance and so forth. Really cool (and I wish Microsoft&#8217;s .NET supported that), but a bit overkill for my needs, plus I&#8217;d rather not switch runtimes.</p>
<p>Then I found a quick blurb on leveraging JavaScript from C# and using the &#8216;eval&#8217; method in that language. I gave this a try and am surprised at the simplicity of the solution when you realize what you&#8217;re able to do. I decided to test this out by making a command line calculator.</p>
<p><center><a href="http://nickgravelyn.com/wp-content/uploads/2010/02/calculator.png"><img src="http://nickgravelyn.com/wp-content/uploads/2010/02/calculator-300x195.png" alt="Calculator" title="Calculator" width="300" height="195" class="alignnone size-medium wp-image-1330" /></a></center></p>
<p>First thing you want to do is create an Evaluator.js file and fill it with this code:</p>
<pre class="brush: jscript;">package Evaluator
{
  class JSEvaluator
  {
    public static function Eval(expr : String) : String
    {
      return eval(expr, &quot;unsafe&quot;);
    }
  }
}</pre>
<p>That&#8217;s it. It&#8217;s the most simplistic wrapper one could imagine. Next, open up a Visual Studio command line or XNA Game Studio command line (both are found in the Start menu in their respective folders). Navigate to your js file and run this command:</p>
<pre class="brush: plain;">jsc /target:library Evaluator.js</pre>
<p>That will compile your JavaScript file into a .NET usable DLL file.</p>
<p>Now create a new Windows Console Application project in Visual Studio. First add a reference to Microsoft.JScript.dll which gives us the JavaScript runtime. Then add a reference to the Evaluator.dll file we produced earlier. Next, drop this code into your Program.cs file:</p>
<pre class="brush: csharp;">using System;
using Evaluator;

namespace Calculator
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine(&quot;Calculator&quot;);
			Console.WriteLine(&quot;Enter a mathematical formula for evaluation.&quot;);
			Console.WriteLine(&quot;Type 'exit' to quit.&quot;);
			Console.WriteLine();

			string line = string.Empty;

			do
			{
				Console.Write(&quot;&gt; &quot;);

				line = Console.ReadLine();

				if (line == &quot;exit&quot;)
					break;

				Console.WriteLine(JSEvaluator.Eval(line));

			} while (true);
		}
	}
}</pre>
<p>That&#8217;s it. We just call into our JSEvaluator class&#8217;s static Eval method and write out the results. Now give it a try and play around, it&#8217;s really quite fun. I&#8217;m not sure exactly how much it handles, and of course I do no exception handling so it&#8217;ll likely break if you give it weird stuff, but it&#8217;s fun as a little calculator.</p>
<p>Now I just need to implement it into my Shader Toy. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/02/leveraging-javascripts-eval-method-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Starting parameter editing for Shader Toy</title>
		<link>http://nickgravelyn.com/2010/02/starting-parameter-editing-for-shader-toy/</link>
		<comments>http://nickgravelyn.com/2010/02/starting-parameter-editing-for-shader-toy/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 03:31:00 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1324</guid>
		<description><![CDATA[I made a bit of progress on my parameter editing today. I have the app fully parsing down parameters and retrieving their values from the shader, and have the starts of the UI for editing in place. I&#8217;m using attributes (specifically a UIType string) to instruct what UI should appear. I also plan to use [...]]]></description>
			<content:encoded><![CDATA[<p>I made a bit of progress on my parameter editing today. I have the app fully parsing down parameters and retrieving their values from the shader, and have the starts of the UI for editing in place. I&#8217;m using attributes (specifically a UIType string) to instruct what UI should appear. I also plan to use UIType for other things, such as a UIType of &#8220;Position&#8221; placing something in the 3D view that can be manipulated directly in 3D space.</p>
<p>I need to figure out how to deal with the editor and the shader&#8217;s default values. Right now any change to the effect blows away changes to parameters. One solution is to simply store the mapping of parameters and their values such that after a new compilation I can set the correct values. Another idea is to somehow have the changes made in the UI update your effect code such that it writes the new values into the code. Not sure how doable that really is.</p>
<p>Thoughts? Leave &#8216;em in the comments.</p>
<p><center><!-- Smart Youtube --><span class="youtube"><object width="750" height="430"><param name="movie" value="http://www.youtube.com/v/lw1lBNVJp48&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" /><param name="allowFullScreen" value="true" /><embed wmode="transparent" src="http://www.youtube.com/v/lw1lBNVJp48&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowfullscreen="true" width="750" height="430" ></embed><param name="wmode" value="transparent" /></object></span></center></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/02/starting-parameter-editing-for-shader-toy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding basic features to Shader Toy</title>
		<link>http://nickgravelyn.com/2010/02/adding-basic-features-to-shader-toy/</link>
		<comments>http://nickgravelyn.com/2010/02/adding-basic-features-to-shader-toy/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 00:01:20 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1321</guid>
		<description><![CDATA[Decided to add a little bit of extra features onto Shader Toy before plunging into the next big step of editing parameters. Basically those features boil down to your standard new/open/save File menu, options for choosing one of a few basic primitives for the model (eventually I&#8217;ll support imported meshes, but not yet), a split-pane [...]]]></description>
			<content:encoded><![CDATA[<p>Decided to add a little bit of extra features onto Shader Toy before plunging into the next big step of editing parameters. Basically those features boil down to your standard new/open/save File menu, options for choosing one of a few basic primitives for the model (eventually I&#8217;ll support imported meshes, but not yet), a split-pane so you can choose how you want your code/view sized, camera controls, and an error display at the bottom so you can fix your broken code (inspired by my own issues figuring out what I did wrong in my shaders to cause them to not compile). As per usual, a video:</p>
<p><center><!-- Smart Youtube --><span class="youtube"><object width="750" height="430"><param name="movie" value="http://www.youtube.com/v/5h8qLrMdRnU&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" /><param name="allowFullScreen" value="true" /><embed wmode="transparent" src="http://www.youtube.com/v/5h8qLrMdRnU&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowfullscreen="true" width="750" height="430" ></embed><param name="wmode" value="transparent" /></object></span></center></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/02/adding-basic-features-to-shader-toy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shader Toy &#8211; Parameters and Annotations</title>
		<link>http://nickgravelyn.com/2010/02/shader-toy-parameters-and-annotations/</link>
		<comments>http://nickgravelyn.com/2010/02/shader-toy-parameters-and-annotations/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 17:19:54 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1294</guid>
		<description><![CDATA[Yesterday I started work on getting parameters and annotations from the shader in the hopes of eventually generating a UI with which one can modify them. Annotations will be used much like other shader apps giving hints to the UI such as min/max values, UI types, and other things.
So far it&#8217;s coming along, slowly but [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I started work on getting parameters and annotations from the shader in the hopes of eventually generating a UI with which one can modify them. Annotations will be used much like other shader apps giving hints to the UI such as min/max values, UI types, and other things.</p>
<p>So far it&#8217;s coming along, slowly but surely. Hopefully this weekend I can get the parameter editing up and running. Until then, watch this demo showing the list of parameters and annotations building as I type. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><center><!-- Smart Youtube --><span class="youtube"><object width="750" height="430"><param name="movie" value="http://www.youtube.com/v/o60iSDCik6U&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" /><param name="allowFullScreen" value="true" /><embed wmode="transparent" src="http://www.youtube.com/v/o60iSDCik6U&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowfullscreen="true" width="750" height="430" ></embed><param name="wmode" value="transparent" /></object></span></center></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/02/shader-toy-parameters-and-annotations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Pong in F# with XNA Game Studio</title>
		<link>http://nickgravelyn.com/2010/02/pong-in-fsharp-with-xna-game-studio/</link>
		<comments>http://nickgravelyn.com/2010/02/pong-in-fsharp-with-xna-game-studio/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 06:16:50 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1280</guid>
		<description><![CDATA[A few of my colleagues were discussing F# today and when/where/how it is/isn&#8217;t better than C#. I haven&#8217;t ever really used F# beyond a very, very brief look at the syntax, so tonight I decided to see what it was all about. As a little project, I decided to make Pong with XNA Game Studio [...]]]></description>
			<content:encoded><![CDATA[<p>A few of my colleagues were discussing F# today and when/where/how it is/isn&#8217;t better than C#. I haven&#8217;t ever really used F# beyond a very, <em>very</em> brief look at the syntax, so tonight I decided to see what it was all about. As a little project, I decided to make Pong with XNA Game Studio using F# with Visual Studio 2010. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><center><a href="http://nickgravelyn.com/wp-content/uploads/2010/02/fsharp-pong.png"><img src="http://nickgravelyn.com/wp-content/uploads/2010/02/fsharp-pong-300x236.png" alt="F# Pong" title="F# Pong" width="300" height="236" class="alignnone size-medium wp-image-1281" /></a></center></p>
<p>I will say that I&#8217;ve determined that F# probably has good uses, but my mind is still riding the object oriented train so it&#8217;s pretty hard to see how I could do more functional programming for game development. Even my F# is very much standard OO but with a new syntax. In that respect it&#8217;s hardly worth showing off, but in the interest of humor (I&#8217;ll go with that), I&#8217;ve decided to go ahead and talk about the project and the issues to overcome.</p>
<p>First I wanted to use VS 2010. This immediately means no (easy) way to build content. Therefore I needed to do any graphics in code. Not a terribly big deal until I wanted to display a score, but I opted to just show dots representing points (which, by the way, are not clamped in my game so I&#8217;m sure after a dozen or two there&#8217;ll be a mess up there).</p>
<p>Next I wanted to target .NET 4.0 (since that&#8217;s a good part of the reason to use VS 2010). But since the XNA Framework is compiled with the .NET 2.0 CLR in mind and .NET 4.0 has a whole new CLR, there&#8217;s a bit of an issue right out of the game if you add your XNA references and hit build. This is easily solved by adding an App.config file with the following in it:</p>
<pre class="brush: xml;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;configuration&gt;
	&lt;startup useLegacyV2RuntimeActivationPolicy=&quot;true&quot;&gt;
		&lt;supportedRuntime version=&quot;v4.0&quot;/&gt;
	&lt;/startup&gt;
&lt;/configuration&gt;</pre>
<p>I&#8217;m not a CLR person, but from what I&#8217;ve read, this allows me to use v2 runtime libraries with a v4 runtime (and no, there is no v3 runtime from what I&#8217;ve read; .NET 3.0 and 3.5 use the v2 runtime. But again, I&#8217;m not a big CLR person so correct me if I&#8217;m wrong <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<p>From there it was all just hacking away. Keeping in mind I learned F# just a few hours ago, here&#8217;s the entirety of my code, with no syntax highlighting since my code pasting stuff doesn&#8217;t support F#:</p>
<pre class="brush: plain; collapse: true; gutter: true; light: false; toolbar: true;">open System
open Microsoft.Xna.Framework
open Microsoft.Xna.Framework.Graphics
open Microsoft.Xna.Framework.Input

type Paddle(posX : int, posY : int) =
    let speed = 5
    let x = posX
    let mutable y = posY

    static member W = 10
    static member H = 80

    member this.X with get() = x
    member this.Y with get() = y and set v = y &lt;- v
    member this.Bounds
        with get() = new Rectangle(x - Paddle.W / 2, y - Paddle.H / 2, Paddle.W, Paddle.H)

    member this.Move (keyUp : Keys) (keyDown : Keys) =
        let ks = Keyboard.GetState()
        if ks.IsKeyDown(keyUp)
            then y &lt;- y - speed
        if ks.IsKeyDown(keyDown)
            then y &lt;- y + speed

type Ball() =
    let mutable x = 0
    let mutable y = 0

    let mutable vx = 0
    let mutable vy = 0

    static member W = 10
    static member H = 10

    member this.X with get() = x and set v = x &lt;- v
    member this.Y with get() = y and set v = y &lt;- v
    member this.Bounds
        with get() = new Rectangle(x - Ball.W / 2, y - Ball.H / 2, Ball.W, Ball.H)

    member this.BounceX() = vx &lt;- -vx
    member this.BounceY() = vy &lt;- -vy

    member this.Start (velX : int) (velY : int) =
        vx &lt;- velX
        vy &lt;- velY

    member this.Update() =
        x &lt;- x + vx
        y &lt;- y + vy

    member this.Collide (p : Paddle) = this.Bounds.Intersects(p.Bounds)

type Game1() as this =
    inherit Game()
    let graphics = new GraphicsDeviceManager(this)

    let mutable spriteBatch = null
    let mutable texture = null

    let left = new Paddle(Paddle.W * 2, 300)
    let right = new Paddle(800 - (Paddle.W * 2), 300)
    let ball = new Ball()

    let rand = new Random()

    let mutable leftScore = 0
    let mutable rightScore = 0

    let clampY x : int =
        if x &lt; Paddle.H / 2 then Paddle.H / 2
        else if x &gt; 600 - (Paddle.H / 2) then 600 - (Paddle.H / 2)
        else x

    let reset (b : Ball) =
        let mutable x = 0
        let mutable y = 0

        if rand.Next() % 2 = 0 then x &lt;- -3 else x &lt;- 3
        if rand.Next() % 2 = 0 then y &lt;- -3 else y &lt;- 3

        b.X &lt;- 400
        b.Y &lt;- 300
        b.Start x y

    let bounce (b : Ball) =
        if b.X &lt; Ball.W / 2 then
            rightScore &lt;- rightScore + 1
            reset b
        else if b.X &gt; 800 - Ball.W / 2 then
            leftScore &lt;- leftScore + 1
            reset b

        if b.Y &lt; Ball.H / 2 then
            b.Y &lt;- Ball.H / 2
            b.BounceY()
        else if b.Y &gt; 600 - Ball.H / 2 then
            b.Y &lt;- 600 - Ball.H / 2
            b.BounceY()

    override Game.LoadContent() =
        spriteBatch &lt;- new SpriteBatch(this.GraphicsDevice)
        texture &lt;- new Texture2D(this.GraphicsDevice, 1, 1);
        texture.SetData([| Color.White |])
        reset ball

    override Game.Update gameTime =
        left.Move Keys.Q Keys.A
        right.Move Keys.O Keys.L
        ball.Update()
        bounce ball
        left.Y &lt;- clampY left.Y
        right.Y &lt;- clampY right.Y

        if ball.Collide(left) || ball.Collide(right) then
            ball.BounceX()

    override Game.Draw gameTime =
        this.GraphicsDevice.Clear(Color.Black)
        spriteBatch.Begin()
        spriteBatch.Draw(texture, left.Bounds, Color.Lime)
        spriteBatch.Draw(texture, right.Bounds, Color.Lime)
        spriteBatch.Draw(texture, ball.Bounds, Color.Lime)

        for i in 1 .. leftScore do
            let r = new Rectangle(50 + i * 10, 5, 5, 5)
            spriteBatch.Draw(texture, r, Color.White);
        for i in 1 .. rightScore do
            let r = new Rectangle(750 - i * 10 - 5, 5, 5, 5)
            spriteBatch.Draw(texture, r, Color.White);

        spriteBatch.End()
        base.Draw(gameTime)

let g = new Game1()
try g.Run()
finally g.Dispose()</pre>
<p>So there you go. If you&#8217;ve ever wanted to make a game with XNA Game Studio using F#, it can be done. It&#8217;s interesting, to say the least, but I&#8217;m sticking with my C# for now. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/02/pong-in-fsharp-with-xna-game-studio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shader Toy</title>
		<link>http://nickgravelyn.com/2010/01/shader-toy/</link>
		<comments>http://nickgravelyn.com/2010/01/shader-toy/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 00:11:23 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1275</guid>
		<description><![CDATA[Today I decided to start doing more with VS2010 and .NET 4.0. But I also wanted to do something with the XNA Framework. Sadly you can&#8217;t really use VS2010 to make a game using XNA Game Studio since it isn&#8217;t supported in VS2010. So I figured I&#8217;d make some sort of WinForm editor tool. I [...]]]></description>
			<content:encoded><![CDATA[<p>Today I decided to start doing more with VS2010 and .NET 4.0. But I also wanted to do something with the XNA Framework. Sadly you can&#8217;t really use VS2010 to make a game using XNA Game Studio since it isn&#8217;t supported in VS2010. So I figured I&#8217;d make some sort of WinForm editor tool. I decided to make a shader editor since I want to start playing more with shaders.</p>
<p>A few hours later and I have something basically workable. I wrote my own XnaPanel for the graphics (slightly based on the WinForms samples, but largely my own stuff) and hooked up the rest. Basically as you type, it will try to compile your shader with every character stroke. If it compiles, it updates the view instantly so you can play around more freely without having to manually click any buttons to get an update.</p>
<p>Currently no support for textures or custom parameters, but these are all things I&#8217;m thinking about how to implement moving forward. I&#8217;m excited to have a project, even if it isn&#8217;t a game.</p>
<p>Here&#8217;s a video of my toy in action:</p>
<p><center><!-- Smart Youtube --><span class="youtube"><object width="750" height="430"><param name="movie" value="http://www.youtube.com/v/AkkH45tapKA&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" /><param name="allowFullScreen" value="true" /><embed wmode="transparent" src="http://www.youtube.com/v/AkkH45tapKA&amp;rel=0&amp;color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;autoplay=0&amp;showsearch=0&amp;ap=%2526fmt%3D18" type="application/x-shockwave-flash" allowfullscreen="true" width="750" height="430" ></embed><param name="wmode" value="transparent" /></object></span></center></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/01/shader-toy/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Spaceships galore</title>
		<link>http://nickgravelyn.com/2010/01/spaceships-galore/</link>
		<comments>http://nickgravelyn.com/2010/01/spaceships-galore/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 00:19:54 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1267</guid>
		<description><![CDATA[After seeing a post on the XNA forums about adapting an algorithm for generating random spaceships, I decided to give it a go myself. It was pretty fun and now I have to figure out whether I want to make a retro shooter using random spaceships. Here&#8217;s a video of my app generating a bunch [...]]]></description>
			<content:encoded><![CDATA[<p>After seeing <a href="http://forums.xna.com/forums/t/46403.aspx">a post on the XNA forums</a> about adapting an <a href="http://www.davebollinger.com/works/pixelspaceships/">algorithm for generating random spaceships</a>, I decided to give it a go myself. It was pretty fun and now I have to figure out whether I want to make a retro shooter using random spaceships. Here&#8217;s a video of my app generating a bunch of the space ships.</p>
<p><center><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/rAiMHfJ8KHU&#038;hl=en_US&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/rAiMHfJ8KHU&#038;hl=en_US&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></center></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/01/spaceships-galore/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using interpolators and timers</title>
		<link>http://nickgravelyn.com/2010/01/using-interpolators-and-timers/</link>
		<comments>http://nickgravelyn.com/2010/01/using-interpolators-and-timers/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 03:21:28 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1256</guid>
		<description><![CDATA[I got an email request asking for help using my interpolator and timer code I&#8217;ve been posting. Since I never really wrote up how to use them, I&#8217;m going to take a quick few minutes to walk you through the process of using these two classes. Make sure you go to the original post and [...]]]></description>
			<content:encoded><![CDATA[<p>I got an email request asking for help using my <a href="http://nickgravelyn.com/2009/12/more-timerinterpolator-tweaks/">interpolator and timer code</a> I&#8217;ve been posting. Since I never really wrote up how to use them, I&#8217;m going to take a quick few minutes to walk you through the process of using these two classes. Make sure you go to the <a href="http://nickgravelyn.com/2009/12/more-timerinterpolator-tweaks/">original post</a> and download the source files. Now let&#8217;s walk the steps of playing with these classes.</p>
<p>1) Create a new XNA GS project and add the files to your project. Should look like this:</p>
<p><img src="http://nickgravelyn.com/wp-content/uploads/2010/01/solution.png" width="312" height="322" /></p>
<p>2) Add a &#8216;using&#8217; statement for the &#8220;Utility&#8221; namespace:</p>
<pre class="brush: csharp;">using Utility;</pre>
<p>Alternatively you can just change the namespace in all the files from the TimerInterpolator.zip file to your game project&#8217;s namespace.</p>
<p>3) Add these fields to your game class:</p>
<pre class="brush: csharp;">Color background = Color.CornflowerBlue;
TimerCollection timers = new TimerCollection();
InterpolatorCollection interpolators = new InterpolatorCollection();</pre>
<p>We have a Color for the window background and collections for our timers and interpolators.</p>
<p>4) In your Update method call Update on both collections:</p>
<pre class="brush: csharp;">protected override void Update(GameTime gameTime)
{
	timers.Update(gameTime);
	interpolators.Update(gameTime);

	base.Update(gameTime);
}</pre>
<p>This makes sure all the timers and interpolators do their job when you create them.</p>
<p>5) Change the Draw method to clear with our field. This will let us test interpolators and timers without needing more graphics:</p>
<pre class="brush: csharp;">protected override void Draw(GameTime gameTime)
{
	GraphicsDevice.Clear(background);
	base.Draw(gameTime);
}</pre>
<p>6) Now we&#8217;re ready to start playing, so I&#8217;m done numbering the steps. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  </p>
<p>First let&#8217;s do a simple example. We&#8217;ll set a timer that fires after the game has been running for three seconds that simply changes our background to pink. In your LoadContent method add this code:</p>
<pre class="brush: csharp;">protected override void LoadContent()
{
	timers.Create(
		3f, // how long (in seconds) before the timer ticks
		false, // does the timer repeat?
		timer =&gt; background = Color.Pink); // the delegate to fire when the timer ticks
}</pre>
<p>If that last line (the &#8216;timer =>&#8217; part) doesn&#8217;t make sense, give <a href="http://nickgravelyn.com/2009/10/learning-lambda-expressions-for-xna-gs-developers/">this post</a> a read.</p>
<p>Give that a run and you&#8217;ll see that, sure enough, the window changes to pink after three seconds. What&#8217;s happening here? Well the TimerCollection class uses a method called Create to create timers. You set how much time passes between ticks, whether to repeat it (or just fire it once), and what to do when the timer ticks. It manages the rest inside. The method does return a Timer instance you can hang on to if you want, which is usually nice if you plan on canceling timers or stopping timers that are repeating.</p>
<p>Now let&#8217;s do something more interesting. We&#8217;ll still use the timer, but this time we&#8217;ll interpolate from CornflowerBlue to Pink after that three seconds. Let&#8217;s change our LoadContent method a little:</p>
<pre class="brush: csharp;">protected override void LoadContent()
{
	timers.Create(
		3f,
		false,
		timer =&gt;
		{
			interpolators.Create(
				0f,
				1f,
				i =&gt; background = Color.Lerp(Color.CornflowerBlue, Color.Pink, i.Value),
				null);
		});
}</pre>
<p>Now run the game and watch as the background fades from blue to pink after waiting three seconds. See how fun this is? </p>
<p>The Create method on InterpolatorCollection has a few overloads which are well commented, but I&#8217;ll put them here for easy reference:</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// Creates a new Interpolator.
/// &lt;/summary&gt;
/// &lt;param name=&quot;start&quot;&gt;The starting value.&lt;/param&gt;
/// &lt;param name=&quot;end&quot;&gt;The ending value.&lt;/param&gt;
/// &lt;param name=&quot;step&quot;&gt;
/// An optional callback to invoke when the Interpolator is updated.
/// &lt;/param&gt;
/// &lt;param name=&quot;completed&quot;&gt;
/// An optional callback to invoke when the Interpolator completes.
/// &lt;/param&gt;
/// &lt;returns&gt;The Interpolator instance.&lt;/returns&gt;
public Interpolator Create(
	float start,
	float end,
	Action&lt;Interpolator&gt; step,
	Action&lt;Interpolator&gt; completed)

/// &lt;summary&gt;
/// Creates a new Interpolator.
/// &lt;/summary&gt;
/// &lt;param name=&quot;start&quot;&gt;The starting value.&lt;/param&gt;
/// &lt;param name=&quot;end&quot;&gt;The ending value.&lt;/param&gt;
/// &lt;param name=&quot;length&quot;&gt;
/// The length of time, in seconds, to perform the interpolation.
/// &lt;/param&gt;
/// &lt;param name=&quot;step&quot;&gt;
/// An optional callback to invoke when the Interpolator is updated.
/// &lt;/param&gt;
/// &lt;param name=&quot;completed&quot;&gt;
/// An optional callback to invoke when the Interpolator completes.
/// &lt;/param&gt;
/// &lt;returns&gt;The Interpolator instance.&lt;/returns&gt;
public Interpolator Create(
	float start,
	float end,
	float length,
	Action&lt;Interpolator&gt; step,
	Action&lt;Interpolator&gt; completed)

/// &lt;summary&gt;
/// Creates a new Interpolator.
/// &lt;/summary&gt;
/// &lt;param name=&quot;start&quot;&gt;The starting value.&lt;/param&gt;
/// &lt;param name=&quot;end&quot;&gt;The ending value.&lt;/param&gt;
/// &lt;param name=&quot;length&quot;&gt;
/// The length of time, in seconds, to perform the interpolation.
/// &lt;/param&gt;
/// &lt;param name=&quot;scale&quot;&gt;
/// A delegate that handles converting the interpolator's progress to a value.
/// &lt;/param&gt;
/// &lt;param name=&quot;step&quot;&gt;
/// An optional callback to invoke when the Interpolator is updated.
/// &lt;/param&gt;
/// &lt;param name=&quot;completed&quot;&gt;
/// An optional callback to invoke when the Interpolator completes.
/// &lt;/param&gt;
/// &lt;returns&gt;The Interpolator instance.&lt;/returns&gt;
public Interpolator Create(
	float start,
	float end,
	float length,
	InterpolatorScaleDelegate scale,
	Action&lt;Interpolator&gt; step,
	Action&lt;Interpolator&gt; completed)</pre>
<p>We used the first one above which does a linear interpolation over one second. The second overload simply lets you change how long it takes so you could interpolate over five seconds or .5 seconds if you wanted. The last overload is interesting with the InterpolatorScaleDelegate. This delegate does a transformation in the Interpolator which can provide you with neat effects without needing subclasses or customizing the Interpolator class.</p>
<p>To understand the scale, let me explain how the Interpolator works. Under the hood, the Interpolator really has two values: &#8220;progress&#8221; and &#8220;value&#8221;. Progress is the core of the interpolator, going from 0 to 1 over the desired time. The value is then computed based on the scale delegate and the progress. By default it uses linear interpolation which doesn&#8217;t do any transformations on the progress. But you could easily substitute your own delegate that does interesting transforms on the progress to get your value. However, keep in mind what value you return. A value of &#8216;0&#8242; indicates the start point of your interpolation and a value of &#8216;1&#8242; indicates the end point. You can return 2 if you&#8217;d like, but know that it will be well past the end value.</p>
<p>The code I provided comes with a small set of delegates that you can try out. They&#8217;re all in the InterpolatorScales class, including the default linear interpolation used if no other delegate is provided.</p>
<pre class="brush: csharp;">/// &lt;summary&gt;
/// A static class that contains predefined scales for Interpolators.
/// &lt;/summary&gt;
public static class InterpolatorScales
{
	/// &lt;summary&gt;
	/// A linear interpolator scale.
	/// This is used by default by the Interpolator if no other scale is given.
	/// &lt;/summary&gt;
	public static readonly InterpolatorScaleDelegate Linear = LinearInterpolation;

	/// &lt;summary&gt;
	/// A quadratic interpolator scale.
	/// &lt;/summary&gt;
	public static readonly InterpolatorScaleDelegate Quadratic = QuadraticInterpolation;

	/// &lt;summary&gt;
	/// A cubic interpolator scale.
	/// &lt;/summary&gt;
	public static readonly InterpolatorScaleDelegate Cubic = CubicInterpolation;

	/// &lt;summary&gt;
	/// A quartic interpolator scale.
	/// &lt;/summary&gt;
	public static readonly InterpolatorScaleDelegate Quartic = QuarticInterpolation;

	private static float LinearInterpolation(float progress)
	{
		return progress;
	}

	private static float QuadraticInterpolation(float progress)
	{
		return progress * progress;
	}

	private static float CubicInterpolation(float progress)
	{
		return progress * progress * progress;
	}

	private static float QuarticInterpolation(float progress)
	{
		return progress * progress * progress * progress;
	}
}</pre>
<p>Some other delegates could use Sin, Cos, or other mathematical functions. Or you can go crazy with them; I once had a delegate that combined the quadratic interpolation with a sin wave and manual offset. The key is to find some function where a progress of &#8216;0&#8242; gives a value of &#8216;0&#8242; and a progress of &#8216;1&#8242; gives a value of &#8216;1&#8242;. Whatever happens in the middle is up to you. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So I hope that helps you get an idea for how to use these classes. The more you use them, the more you&#8217;ll see how nice it is to be able to fire off these objects to handle animations and pauses, rather than continually having random fields around for timing and animating things around. With that I&#8217;ll leave you with this fun LoadContent method you can toss into the test game to have some fun with your background color. <img src='http://nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: csharp;">Color[] backgroundColors = new[]
{
	Color.CornflowerBlue,
	Color.Pink,
	Color.Red,
	Color.Green,
};
int currentBackground = 0;

protected override void LoadContent()
{
	timers.Create(1f, true, timer =&gt; Interpolate());
}

private void Interpolate()
{
	interpolators.Create(
		0f,
		1f,
		.5f,
		InterpolatorStep,
		i =&gt; currentBackground = (currentBackground + 1) % backgroundColors.Length);
}

private void InterpolatorStep(Interpolator i)
{
	background = Color.Lerp(
		backgroundColors[currentBackground],
		backgroundColors[(currentBackground + 1) % backgroundColors.Length],
		i.Value);
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/01/using-interpolators-and-timers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>I made a Flash game!</title>
		<link>http://nickgravelyn.com/2010/01/i-made-a-flash-game/</link>
		<comments>http://nickgravelyn.com/2010/01/i-made-a-flash-game/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 08:26:04 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://nickgravelyn.com/?p=1235</guid>
		<description><![CDATA[A while back I spotted Flixel, a Flash/Flex library for game development, which sounded like a fun side project. I wanted to try and get into making little web games, but I didn&#8217;t really play with it much and it fell by the wayside. Today I saw a new Flex library called FlashPunk was released [...]]]></description>
			<content:encoded><![CDATA[<p>A while back I spotted <a href="http://flixel.org/">Flixel</a>, a Flash/Flex library for game development, which sounded like a fun side project. I wanted to try and get into making little web games, but I didn&#8217;t really play with it much and it fell by the wayside. Today I saw a new Flex library called <a href="http://flashpunk.net/">FlashPunk</a> was released and I decided to give it a go. It went really well and was quite fun to build with. The author had a very basic getting started tutorial of getting one sprite on the screen. I then used the rest of the content the tutorial gave and built this very basic shooter type game in a matter of hours:</p>
<p><span id="more-1235"></span></p>
<p><center><embed src="/flash/SimpleShooter.swf" width="224" height="360" allowscriptaccess="never" allowfullscreen="false"   flashvars="autostart=true"/><br />
(Click to give focus. Use Left/Right to move and Space to shoot.)</center></p>
<p>I&#8217;m impressed with how nice ActionScript 3 really is. I&#8217;ve never really used the language and am just winging it as I go. It has some things I don&#8217;t like, but that&#8217;s probably just because I think that C# is about the best language I&#8217;ve used.</p>
<p>I&#8217;m definitely excited to keep playing with this library and making more little Flash games. </p>
<p>EDIT: Decided to share the source in case anyone wanted to see how it was built or build upon it. The FlashPunk source is all in there and the project is a FlashBuilder one, though I&#8217;m sure you could import it into FlexBuilder or build with any other compiling tools you want. <a href="http://nickgravelyn.com/wp-content/uploads/2010/01/SimpleGame.zip">SimpleGame.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nickgravelyn.com/2010/01/i-made-a-flash-game/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
