Translating C# Brushes to Silverlight Brushes

If you’ve read my blog post Translating C# Color to Silverlight Color, you’re aware that there are fewer color constants in Silverlight than there are in C#. The post above demonstrates how to work around that – but the same problem exists for Brushes.

There are a great number of brushes that we can use in C# (static properties in the Brushes class), but in Silverlight there are like… none. I can’t even find the Brushes class in Silverlight. But never worry, I’ll use Reflection to create a BrushConstants class that we can use in both C# and Silverlight (if you use my ColorConstants class from my previous blogpost).

I used this code to generate the class;

        static void Main(string[] args)
        {
            List<PropertyInfo> propertyInfos =
                typeof(Color)
                    .GetProperties(BindingFlags.Static | BindingFlags.Public)
                    .Where(prop => prop.PropertyType == typeof(Color))
                    .ToList();

            List<string> properties =
                propertyInfos
                    .Select(
                    prop => string.Format(
                                "public static Brush {0} {{get{{return new SolidColorBrush(ColorConstants.{0});}}}}",
                                prop.Name))
                    .ToList();

            File.WriteAllLines(@"c:\slask\properties.txt", properties.ToArray());
        }

The finished class is presented below. Note that in this case, you can use the same class in both Silverlight and C#, the reason is that the ColorConstants class is available in both – even though they differ they can be used the same;

using System.Windows.Media;

public static class BrushConstants
{
    public static Brush Transparent { get { return new SolidColorBrush(ColorConstants.Transparent); } }
    public static Brush AliceBlue { get { return new SolidColorBrush(ColorConstants.AliceBlue); } }
    public static Brush AntiqueWhite { get { return new SolidColorBrush(ColorConstants.AntiqueWhite); } }
    public static Brush Aqua { get { return new SolidColorBrush(ColorConstants.Aqua); } }
    public static Brush Aquamarine { get { return new SolidColorBrush(ColorConstants.Aquamarine); } }
    public static Brush Azure { get { return new SolidColorBrush(ColorConstants.Azure); } }
    public static Brush Beige { get { return new SolidColorBrush(ColorConstants.Beige); } }
    public static Brush Bisque { get { return new SolidColorBrush(ColorConstants.Bisque); } }
    public static Brush Black { get { return new SolidColorBrush(ColorConstants.Black); } }
    public static Brush BlanchedAlmond { get { return new SolidColorBrush(ColorConstants.BlanchedAlmond); } }
    public static Brush Blue { get { return new SolidColorBrush(ColorConstants.Blue); } }
    public static Brush BlueViolet { get { return new SolidColorBrush(ColorConstants.BlueViolet); } }
    public static Brush Brown { get { return new SolidColorBrush(ColorConstants.Brown); } }
    public static Brush BurlyWood { get { return new SolidColorBrush(ColorConstants.BurlyWood); } }
    public static Brush CadetBlue { get { return new SolidColorBrush(ColorConstants.CadetBlue); } }
    public static Brush Chartreuse { get { return new SolidColorBrush(ColorConstants.Chartreuse); } }
    public static Brush Chocolate { get { return new SolidColorBrush(ColorConstants.Chocolate); } }
    public static Brush Coral { get { return new SolidColorBrush(ColorConstants.Coral); } }
    public static Brush CornflowerBlue { get { return new SolidColorBrush(ColorConstants.CornflowerBlue); } }
    public static Brush Cornsilk { get { return new SolidColorBrush(ColorConstants.Cornsilk); } }
    public static Brush Crimson { get { return new SolidColorBrush(ColorConstants.Crimson); } }
    public static Brush Cyan { get { return new SolidColorBrush(ColorConstants.Cyan); } }
    public static Brush DarkBlue { get { return new SolidColorBrush(ColorConstants.DarkBlue); } }
    public static Brush DarkCyan { get { return new SolidColorBrush(ColorConstants.DarkCyan); } }
    public static Brush DarkGoldenrod { get { return new SolidColorBrush(ColorConstants.DarkGoldenrod); } }
    public static Brush DarkGray { get { return new SolidColorBrush(ColorConstants.DarkGray); } }
    public static Brush DarkGreen { get { return new SolidColorBrush(ColorConstants.DarkGreen); } }
    public static Brush DarkKhaki { get { return new SolidColorBrush(ColorConstants.DarkKhaki); } }
    public static Brush DarkMagenta { get { return new SolidColorBrush(ColorConstants.DarkMagenta); } }
    public static Brush DarkOliveGreen { get { return new SolidColorBrush(ColorConstants.DarkOliveGreen); } }
    public static Brush DarkOrange { get { return new SolidColorBrush(ColorConstants.DarkOrange); } }
    public static Brush DarkOrchid { get { return new SolidColorBrush(ColorConstants.DarkOrchid); } }
    public static Brush DarkRed { get { return new SolidColorBrush(ColorConstants.DarkRed); } }
    public static Brush DarkSalmon { get { return new SolidColorBrush(ColorConstants.DarkSalmon); } }
    public static Brush DarkSeaGreen { get { return new SolidColorBrush(ColorConstants.DarkSeaGreen); } }
    public static Brush DarkSlateBlue { get { return new SolidColorBrush(ColorConstants.DarkSlateBlue); } }
    public static Brush DarkSlateGray { get { return new SolidColorBrush(ColorConstants.DarkSlateGray); } }
    public static Brush DarkTurquoise { get { return new SolidColorBrush(ColorConstants.DarkTurquoise); } }
    public static Brush DarkViolet { get { return new SolidColorBrush(ColorConstants.DarkViolet); } }
    public static Brush DeepPink { get { return new SolidColorBrush(ColorConstants.DeepPink); } }
    public static Brush DeepSkyBlue { get { return new SolidColorBrush(ColorConstants.DeepSkyBlue); } }
    public static Brush DimGray { get { return new SolidColorBrush(ColorConstants.DimGray); } }
    public static Brush DodgerBlue { get { return new SolidColorBrush(ColorConstants.DodgerBlue); } }
    public static Brush Firebrick { get { return new SolidColorBrush(ColorConstants.Firebrick); } }
    public static Brush FloralWhite { get { return new SolidColorBrush(ColorConstants.FloralWhite); } }
    public static Brush ForestGreen { get { return new SolidColorBrush(ColorConstants.ForestGreen); } }
    public static Brush Fuchsia { get { return new SolidColorBrush(ColorConstants.Fuchsia); } }
    public static Brush Gainsboro { get { return new SolidColorBrush(ColorConstants.Gainsboro); } }
    public static Brush GhostWhite { get { return new SolidColorBrush(ColorConstants.GhostWhite); } }
    public static Brush Gold { get { return new SolidColorBrush(ColorConstants.Gold); } }
    public static Brush Goldenrod { get { return new SolidColorBrush(ColorConstants.Goldenrod); } }
    public static Brush Gray { get { return new SolidColorBrush(ColorConstants.Gray); } }
    public static Brush Green { get { return new SolidColorBrush(ColorConstants.Green); } }
    public static Brush GreenYellow { get { return new SolidColorBrush(ColorConstants.GreenYellow); } }
    public static Brush Honeydew { get { return new SolidColorBrush(ColorConstants.Honeydew); } }
    public static Brush HotPink { get { return new SolidColorBrush(ColorConstants.HotPink); } }
    public static Brush IndianRed { get { return new SolidColorBrush(ColorConstants.IndianRed); } }
    public static Brush Indigo { get { return new SolidColorBrush(ColorConstants.Indigo); } }
    public static Brush Ivory { get { return new SolidColorBrush(ColorConstants.Ivory); } }
    public static Brush Khaki { get { return new SolidColorBrush(ColorConstants.Khaki); } }
    public static Brush Lavender { get { return new SolidColorBrush(ColorConstants.Lavender); } }
    public static Brush LavenderBlush { get { return new SolidColorBrush(ColorConstants.LavenderBlush); } }
    public static Brush LawnGreen { get { return new SolidColorBrush(ColorConstants.LawnGreen); } }
    public static Brush LemonChiffon { get { return new SolidColorBrush(ColorConstants.LemonChiffon); } }
    public static Brush LightBlue { get { return new SolidColorBrush(ColorConstants.LightBlue); } }
    public static Brush LightCoral { get { return new SolidColorBrush(ColorConstants.LightCoral); } }
    public static Brush LightCyan { get { return new SolidColorBrush(ColorConstants.LightCyan); } }
    public static Brush LightGoldenrodYellow { get { return new SolidColorBrush(ColorConstants.LightGoldenrodYellow); } }
    public static Brush LightGreen { get { return new SolidColorBrush(ColorConstants.LightGreen); } }
    public static Brush LightGray { get { return new SolidColorBrush(ColorConstants.LightGray); } }
    public static Brush LightPink { get { return new SolidColorBrush(ColorConstants.LightPink); } }
    public static Brush LightSalmon { get { return new SolidColorBrush(ColorConstants.LightSalmon); } }
    public static Brush LightSeaGreen { get { return new SolidColorBrush(ColorConstants.LightSeaGreen); } }
    public static Brush LightSkyBlue { get { return new SolidColorBrush(ColorConstants.LightSkyBlue); } }
    public static Brush LightSlateGray { get { return new SolidColorBrush(ColorConstants.LightSlateGray); } }
    public static Brush LightSteelBlue { get { return new SolidColorBrush(ColorConstants.LightSteelBlue); } }
    public static Brush LightYellow { get { return new SolidColorBrush(ColorConstants.LightYellow); } }
    public static Brush Lime { get { return new SolidColorBrush(ColorConstants.Lime); } }
    public static Brush LimeGreen { get { return new SolidColorBrush(ColorConstants.LimeGreen); } }
    public static Brush Linen { get { return new SolidColorBrush(ColorConstants.Linen); } }
    public static Brush Magenta { get { return new SolidColorBrush(ColorConstants.Magenta); } }
    public static Brush Maroon { get { return new SolidColorBrush(ColorConstants.Maroon); } }
    public static Brush MediumAquamarine { get { return new SolidColorBrush(ColorConstants.MediumAquamarine); } }
    public static Brush MediumBlue { get { return new SolidColorBrush(ColorConstants.MediumBlue); } }
    public static Brush MediumOrchid { get { return new SolidColorBrush(ColorConstants.MediumOrchid); } }
    public static Brush MediumPurple { get { return new SolidColorBrush(ColorConstants.MediumPurple); } }
    public static Brush MediumSeaGreen { get { return new SolidColorBrush(ColorConstants.MediumSeaGreen); } }
    public static Brush MediumSlateBlue { get { return new SolidColorBrush(ColorConstants.MediumSlateBlue); } }
    public static Brush MediumSpringGreen { get { return new SolidColorBrush(ColorConstants.MediumSpringGreen); } }
    public static Brush MediumTurquoise { get { return new SolidColorBrush(ColorConstants.MediumTurquoise); } }
    public static Brush MediumVioletRed { get { return new SolidColorBrush(ColorConstants.MediumVioletRed); } }
    public static Brush MidnightBlue { get { return new SolidColorBrush(ColorConstants.MidnightBlue); } }
    public static Brush MintCream { get { return new SolidColorBrush(ColorConstants.MintCream); } }
    public static Brush MistyRose { get { return new SolidColorBrush(ColorConstants.MistyRose); } }
    public static Brush Moccasin { get { return new SolidColorBrush(ColorConstants.Moccasin); } }
    public static Brush NavajoWhite { get { return new SolidColorBrush(ColorConstants.NavajoWhite); } }
    public static Brush Navy { get { return new SolidColorBrush(ColorConstants.Navy); } }
    public static Brush OldLace { get { return new SolidColorBrush(ColorConstants.OldLace); } }
    public static Brush Olive { get { return new SolidColorBrush(ColorConstants.Olive); } }
    public static Brush OliveDrab { get { return new SolidColorBrush(ColorConstants.OliveDrab); } }
    public static Brush Orange { get { return new SolidColorBrush(ColorConstants.Orange); } }
    public static Brush OrangeRed { get { return new SolidColorBrush(ColorConstants.OrangeRed); } }
    public static Brush Orchid { get { return new SolidColorBrush(ColorConstants.Orchid); } }
    public static Brush PaleGoldenrod { get { return new SolidColorBrush(ColorConstants.PaleGoldenrod); } }
    public static Brush PaleGreen { get { return new SolidColorBrush(ColorConstants.PaleGreen); } }
    public static Brush PaleTurquoise { get { return new SolidColorBrush(ColorConstants.PaleTurquoise); } }
    public static Brush PaleVioletRed { get { return new SolidColorBrush(ColorConstants.PaleVioletRed); } }
    public static Brush PapayaWhip { get { return new SolidColorBrush(ColorConstants.PapayaWhip); } }
    public static Brush PeachPuff { get { return new SolidColorBrush(ColorConstants.PeachPuff); } }
    public static Brush Peru { get { return new SolidColorBrush(ColorConstants.Peru); } }
    public static Brush Pink { get { return new SolidColorBrush(ColorConstants.Pink); } }
    public static Brush Plum { get { return new SolidColorBrush(ColorConstants.Plum); } }
    public static Brush PowderBlue { get { return new SolidColorBrush(ColorConstants.PowderBlue); } }
    public static Brush Purple { get { return new SolidColorBrush(ColorConstants.Purple); } }
    public static Brush Red { get { return new SolidColorBrush(ColorConstants.Red); } }
    public static Brush RosyBrown { get { return new SolidColorBrush(ColorConstants.RosyBrown); } }
    public static Brush RoyalBlue { get { return new SolidColorBrush(ColorConstants.RoyalBlue); } }
    public static Brush SaddleBrown { get { return new SolidColorBrush(ColorConstants.SaddleBrown); } }
    public static Brush Salmon { get { return new SolidColorBrush(ColorConstants.Salmon); } }
    public static Brush SandyBrown { get { return new SolidColorBrush(ColorConstants.SandyBrown); } }
    public static Brush SeaGreen { get { return new SolidColorBrush(ColorConstants.SeaGreen); } }
    public static Brush SeaShell { get { return new SolidColorBrush(ColorConstants.SeaShell); } }
    public static Brush Sienna { get { return new SolidColorBrush(ColorConstants.Sienna); } }
    public static Brush Silver { get { return new SolidColorBrush(ColorConstants.Silver); } }
    public static Brush SkyBlue { get { return new SolidColorBrush(ColorConstants.SkyBlue); } }
    public static Brush SlateBlue { get { return new SolidColorBrush(ColorConstants.SlateBlue); } }
    public static Brush SlateGray { get { return new SolidColorBrush(ColorConstants.SlateGray); } }
    public static Brush Snow { get { return new SolidColorBrush(ColorConstants.Snow); } }
    public static Brush SpringGreen { get { return new SolidColorBrush(ColorConstants.SpringGreen); } }
    public static Brush SteelBlue { get { return new SolidColorBrush(ColorConstants.SteelBlue); } }
    public static Brush Tan { get { return new SolidColorBrush(ColorConstants.Tan); } }
    public static Brush Teal { get { return new SolidColorBrush(ColorConstants.Teal); } }
    public static Brush Thistle { get { return new SolidColorBrush(ColorConstants.Thistle); } }
    public static Brush Tomato { get { return new SolidColorBrush(ColorConstants.Tomato); } }
    public static Brush Turquoise { get { return new SolidColorBrush(ColorConstants.Turquoise); } }
    public static Brush Violet { get { return new SolidColorBrush(ColorConstants.Violet); } }
    public static Brush Wheat { get { return new SolidColorBrush(ColorConstants.Wheat); } }
    public static Brush White { get { return new SolidColorBrush(ColorConstants.White); } }
    public static Brush WhiteSmoke { get { return new SolidColorBrush(ColorConstants.WhiteSmoke); } }
    public static Brush Yellow { get { return new SolidColorBrush(ColorConstants.Yellow); } }
    public static Brush YellowGreen { get { return new SolidColorBrush(ColorConstants.YellowGreen); } }
}

Translating C# Color to Silverlight Color

I’ve used a lot of named C# colors in my FreeGoo project and currently I’m trying to migrate my C# code to Silverlight – which doesn’t have the same colors.

In C#, the color class is located in System.Drawing and in Silverlight it’s located in System.Windows.Media.

System.Drawing.Color

The C# color, System.Drawing.Color, contains lots and lots of nice constant colors that can be used in code. See this document for the available c# color constants.

System.Windows.Media.Color

The Silverlight color, System.Windows.Media.Color, only contains a handful of color constants!

Handling both in C# and Silverlight

So, how do we handle this when we have code that must execute – both in C# and in Silverlight? Well, if C#/Silverlight allowed static extension methods, we could possibly use that, but since they don’t, we must create a wrapper class. Actually, we create two color wrapper classes, one to use in Silverlight and one to use in C#. Both will be called ColorWrapper.

Using Reflection – and Lambda – to identify color constants

I’ll use reflection to create the color constants; since the C# Color class contains the color constants, I’ll use that to create a list of color constants.

This code reveals that there are 141 color constants;

        static void Main(string[] args)
        {
            List<PropertyInfo> propertyInfos =
                typeof(Color)
                    .GetProperties(BindingFlags.Static | BindingFlags.Public)
                    .Where(prop => prop.PropertyType == typeof(Color))
                    .ToList();

            Console.WriteLine("Color constants: {0}", propertyInfos.Count);
            propertyInfos.ForEach(prop => Console.WriteLine("Prop: " + prop.Name));

            Console.ReadKey();
        }
Loading a C# color as a Silverlight Color

If you wish to load a C# color as a Silverlight color, you must identify Red, Green, Blue and Alpha Values and use these in the color constructor. Tweaking the code above to also retrieve the color (with the ARGB values), allows us to output the code we’ll use for Silverlight. And since we need to use the same code in C#, we need a color translator that’ll work with C# as well.

Generate ColorConstants for C#

In C#, it’ll simply return the same color as is returned by the color object itself, looks silly, but makes cross target compiling possible. Note the double curly braces, they’re required since we’re using a format string;

        static void Main(string[] args)
        {
            List<PropertyInfo> propertyInfos =
                typeof(Color)
                    .GetProperties(BindingFlags.Static | BindingFlags.Public)
                    .Where(prop => prop.PropertyType == typeof(Color))
                    .ToList();

            Console.WriteLine("Color constants: {0}", propertyInfos.Count);
            propertyInfos.ForEach(
                prop => Console.WriteLine(
                    "public static Color {0} {{get{{return Color.{0};}}}}", 
                    prop.Name));

            Console.ReadKey();
        }
Generate ColorConstants for Silverlight

Generating the Silverlight ColorConstants is slightly more complicated, but not all that much. There is a method that takes ARGB to generate the color, and in the code above we’re a breath away from knowing the ARGB values. This code does the trick;

        static void Main(string[] args)
        {
            List<PropertyInfo> propertyInfos =
                typeof(Color)
                    .GetProperties(BindingFlags.Static | BindingFlags.Public)
                    .Where(prop => prop.PropertyType == typeof(Color))
                    .ToList();

            Console.WriteLine("Color constants: {0}", propertyInfos.Count);
            propertyInfos.ForEach(
                prop =>
                {
                    Color color = (Color)prop.GetValue(null, null);
                    Console.WriteLine(
                        "public static Color {0} {{get{{return Color.FromArgb({1}, {2}, {3}, {4});}}}}",
                        prop.Name,
                        color.A,
                        color.R,
                        color.G,
                        color.B);
                });

            Console.ReadKey();
        }

For completeness, the actual classes;

C# ColorConstants

Only ever use this if you have a project that you must use in both C# and Silverlight;

using System.Drawing;

public static class ColorConstants
{
    public static Color Transparent { get { return Color.Transparent; } }
    public static Color AliceBlue { get { return Color.AliceBlue; } }
    public static Color AntiqueWhite { get { return Color.AntiqueWhite; } }
    public static Color Aqua { get { return Color.Aqua; } }
    public static Color Aquamarine { get { return Color.Aquamarine; } }
    public static Color Azure { get { return Color.Azure; } }
    public static Color Beige { get { return Color.Beige; } }
    public static Color Bisque { get { return Color.Bisque; } }
    public static Color Black { get { return Color.Black; } }
    public static Color BlanchedAlmond { get { return Color.BlanchedAlmond; } }
    public static Color Blue { get { return Color.Blue; } }
    public static Color BlueViolet { get { return Color.BlueViolet; } }
    public static Color Brown { get { return Color.Brown; } }
    public static Color BurlyWood { get { return Color.BurlyWood; } }
    public static Color CadetBlue { get { return Color.CadetBlue; } }
    public static Color Chartreuse { get { return Color.Chartreuse; } }
    public static Color Chocolate { get { return Color.Chocolate; } }
    public static Color Coral { get { return Color.Coral; } }
    public static Color CornflowerBlue { get { return Color.CornflowerBlue; } }
    public static Color Cornsilk { get { return Color.Cornsilk; } }
    public static Color Crimson { get { return Color.Crimson; } }
    public static Color Cyan { get { return Color.Cyan; } }
    public static Color DarkBlue { get { return Color.DarkBlue; } }
    public static Color DarkCyan { get { return Color.DarkCyan; } }
    public static Color DarkGoldenrod { get { return Color.DarkGoldenrod; } }
    public static Color DarkGray { get { return Color.DarkGray; } }
    public static Color DarkGreen { get { return Color.DarkGreen; } }
    public static Color DarkKhaki { get { return Color.DarkKhaki; } }
    public static Color DarkMagenta { get { return Color.DarkMagenta; } }
    public static Color DarkOliveGreen { get { return Color.DarkOliveGreen; } }
    public static Color DarkOrange { get { return Color.DarkOrange; } }
    public static Color DarkOrchid { get { return Color.DarkOrchid; } }
    public static Color DarkRed { get { return Color.DarkRed; } }
    public static Color DarkSalmon { get { return Color.DarkSalmon; } }
    public static Color DarkSeaGreen { get { return Color.DarkSeaGreen; } }
    public static Color DarkSlateBlue { get { return Color.DarkSlateBlue; } }
    public static Color DarkSlateGray { get { return Color.DarkSlateGray; } }
    public static Color DarkTurquoise { get { return Color.DarkTurquoise; } }
    public static Color DarkViolet { get { return Color.DarkViolet; } }
    public static Color DeepPink { get { return Color.DeepPink; } }
    public static Color DeepSkyBlue { get { return Color.DeepSkyBlue; } }
    public static Color DimGray { get { return Color.DimGray; } }
    public static Color DodgerBlue { get { return Color.DodgerBlue; } }
    public static Color Firebrick { get { return Color.Firebrick; } }
    public static Color FloralWhite { get { return Color.FloralWhite; } }
    public static Color ForestGreen { get { return Color.ForestGreen; } }
    public static Color Fuchsia { get { return Color.Fuchsia; } }
    public static Color Gainsboro { get { return Color.Gainsboro; } }
    public static Color GhostWhite { get { return Color.GhostWhite; } }
    public static Color Gold { get { return Color.Gold; } }
    public static Color Goldenrod { get { return Color.Goldenrod; } }
    public static Color Gray { get { return Color.Gray; } }
    public static Color Green { get { return Color.Green; } }
    public static Color GreenYellow { get { return Color.GreenYellow; } }
    public static Color Honeydew { get { return Color.Honeydew; } }
    public static Color HotPink { get { return Color.HotPink; } }
    public static Color IndianRed { get { return Color.IndianRed; } }
    public static Color Indigo { get { return Color.Indigo; } }
    public static Color Ivory { get { return Color.Ivory; } }
    public static Color Khaki { get { return Color.Khaki; } }
    public static Color Lavender { get { return Color.Lavender; } }
    public static Color LavenderBlush { get { return Color.LavenderBlush; } }
    public static Color LawnGreen { get { return Color.LawnGreen; } }
    public static Color LemonChiffon { get { return Color.LemonChiffon; } }
    public static Color LightBlue { get { return Color.LightBlue; } }
    public static Color LightCoral { get { return Color.LightCoral; } }
    public static Color LightCyan { get { return Color.LightCyan; } }
    public static Color LightGoldenrodYellow { get { return Color.LightGoldenrodYellow; } }
    public static Color LightGreen { get { return Color.LightGreen; } }
    public static Color LightGray { get { return Color.LightGray; } }
    public static Color LightPink { get { return Color.LightPink; } }
    public static Color LightSalmon { get { return Color.LightSalmon; } }
    public static Color LightSeaGreen { get { return Color.LightSeaGreen; } }
    public static Color LightSkyBlue { get { return Color.LightSkyBlue; } }
    public static Color LightSlateGray { get { return Color.LightSlateGray; } }
    public static Color LightSteelBlue { get { return Color.LightSteelBlue; } }
    public static Color LightYellow { get { return Color.LightYellow; } }
    public static Color Lime { get { return Color.Lime; } }
    public static Color LimeGreen { get { return Color.LimeGreen; } }
    public static Color Linen { get { return Color.Linen; } }
    public static Color Magenta { get { return Color.Magenta; } }
    public static Color Maroon { get { return Color.Maroon; } }
    public static Color MediumAquamarine { get { return Color.MediumAquamarine; } }
    public static Color MediumBlue { get { return Color.MediumBlue; } }
    public static Color MediumOrchid { get { return Color.MediumOrchid; } }
    public static Color MediumPurple { get { return Color.MediumPurple; } }
    public static Color MediumSeaGreen { get { return Color.MediumSeaGreen; } }
    public static Color MediumSlateBlue { get { return Color.MediumSlateBlue; } }
    public static Color MediumSpringGreen { get { return Color.MediumSpringGreen; } }
    public static Color MediumTurquoise { get { return Color.MediumTurquoise; } }
    public static Color MediumVioletRed { get { return Color.MediumVioletRed; } }
    public static Color MidnightBlue { get { return Color.MidnightBlue; } }
    public static Color MintCream { get { return Color.MintCream; } }
    public static Color MistyRose { get { return Color.MistyRose; } }
    public static Color Moccasin { get { return Color.Moccasin; } }
    public static Color NavajoWhite { get { return Color.NavajoWhite; } }
    public static Color Navy { get { return Color.Navy; } }
    public static Color OldLace { get { return Color.OldLace; } }
    public static Color Olive { get { return Color.Olive; } }
    public static Color OliveDrab { get { return Color.OliveDrab; } }
    public static Color Orange { get { return Color.Orange; } }
    public static Color OrangeRed { get { return Color.OrangeRed; } }
    public static Color Orchid { get { return Color.Orchid; } }
    public static Color PaleGoldenrod { get { return Color.PaleGoldenrod; } }
    public static Color PaleGreen { get { return Color.PaleGreen; } }
    public static Color PaleTurquoise { get { return Color.PaleTurquoise; } }
    public static Color PaleVioletRed { get { return Color.PaleVioletRed; } }
    public static Color PapayaWhip { get { return Color.PapayaWhip; } }
    public static Color PeachPuff { get { return Color.PeachPuff; } }
    public static Color Peru { get { return Color.Peru; } }
    public static Color Pink { get { return Color.Pink; } }
    public static Color Plum { get { return Color.Plum; } }
    public static Color PowderBlue { get { return Color.PowderBlue; } }
    public static Color Purple { get { return Color.Purple; } }
    public static Color Red { get { return Color.Red; } }
    public static Color RosyBrown { get { return Color.RosyBrown; } }
    public static Color RoyalBlue { get { return Color.RoyalBlue; } }
    public static Color SaddleBrown { get { return Color.SaddleBrown; } }
    public static Color Salmon { get { return Color.Salmon; } }
    public static Color SandyBrown { get { return Color.SandyBrown; } }
    public static Color SeaGreen { get { return Color.SeaGreen; } }
    public static Color SeaShell { get { return Color.SeaShell; } }
    public static Color Sienna { get { return Color.Sienna; } }
    public static Color Silver { get { return Color.Silver; } }
    public static Color SkyBlue { get { return Color.SkyBlue; } }
    public static Color SlateBlue { get { return Color.SlateBlue; } }
    public static Color SlateGray { get { return Color.SlateGray; } }
    public static Color Snow { get { return Color.Snow; } }
    public static Color SpringGreen { get { return Color.SpringGreen; } }
    public static Color SteelBlue { get { return Color.SteelBlue; } }
    public static Color Tan { get { return Color.Tan; } }
    public static Color Teal { get { return Color.Teal; } }
    public static Color Thistle { get { return Color.Thistle; } }
    public static Color Tomato { get { return Color.Tomato; } }
    public static Color Turquoise { get { return Color.Turquoise; } }
    public static Color Violet { get { return Color.Violet; } }
    public static Color Wheat { get { return Color.Wheat; } }
    public static Color White { get { return Color.White; } }
    public static Color WhiteSmoke { get { return Color.WhiteSmoke; } }
    public static Color Yellow { get { return Color.Yellow; } }
    public static Color YellowGreen { get { return Color.YellowGreen; } }
}
Silverlight ColorConstants
using System.Windows.Media;

public class ColorConstants
{
    public static Color Transparent { get { return Color.FromArgb(0, 255, 255, 255); } }
    public static Color AliceBlue { get { return Color.FromArgb(255, 240, 248, 255); } }
    public static Color AntiqueWhite { get { return Color.FromArgb(255, 250, 235, 215); } }
    public static Color Aqua { get { return Color.FromArgb(255, 0, 255, 255); } }
    public static Color Aquamarine { get { return Color.FromArgb(255, 127, 255, 212); } }
    public static Color Azure { get { return Color.FromArgb(255, 240, 255, 255); } }
    public static Color Beige { get { return Color.FromArgb(255, 245, 245, 220); } }
    public static Color Bisque { get { return Color.FromArgb(255, 255, 228, 196); } }
    public static Color Black { get { return Color.FromArgb(255, 0, 0, 0); } }
    public static Color BlanchedAlmond { get { return Color.FromArgb(255, 255, 235, 205); } }
    public static Color Blue { get { return Color.FromArgb(255, 0, 0, 255); } }
    public static Color BlueViolet { get { return Color.FromArgb(255, 138, 43, 226); } }
    public static Color Brown { get { return Color.FromArgb(255, 165, 42, 42); } }
    public static Color BurlyWood { get { return Color.FromArgb(255, 222, 184, 135); } }
    public static Color CadetBlue { get { return Color.FromArgb(255, 95, 158, 160); } }
    public static Color Chartreuse { get { return Color.FromArgb(255, 127, 255, 0); } }
    public static Color Chocolate { get { return Color.FromArgb(255, 210, 105, 30); } }
    public static Color Coral { get { return Color.FromArgb(255, 255, 127, 80); } }
    public static Color CornflowerBlue { get { return Color.FromArgb(255, 100, 149, 237); } }
    public static Color Cornsilk { get { return Color.FromArgb(255, 255, 248, 220); } }
    public static Color Crimson { get { return Color.FromArgb(255, 220, 20, 60); } }
    public static Color Cyan { get { return Color.FromArgb(255, 0, 255, 255); } }
    public static Color DarkBlue { get { return Color.FromArgb(255, 0, 0, 139); } }
    public static Color DarkCyan { get { return Color.FromArgb(255, 0, 139, 139); } }
    public static Color DarkGoldenrod { get { return Color.FromArgb(255, 184, 134, 11); } }
    public static Color DarkGray { get { return Color.FromArgb(255, 169, 169, 169); } }
    public static Color DarkGreen { get { return Color.FromArgb(255, 0, 100, 0); } }
    public static Color DarkKhaki { get { return Color.FromArgb(255, 189, 183, 107); } }
    public static Color DarkMagenta { get { return Color.FromArgb(255, 139, 0, 139); } }
    public static Color DarkOliveGreen { get { return Color.FromArgb(255, 85, 107, 47); } }
    public static Color DarkOrange { get { return Color.FromArgb(255, 255, 140, 0); } }
    public static Color DarkOrchid { get { return Color.FromArgb(255, 153, 50, 204); } }
    public static Color DarkRed { get { return Color.FromArgb(255, 139, 0, 0); } }
    public static Color DarkSalmon { get { return Color.FromArgb(255, 233, 150, 122); } }
    public static Color DarkSeaGreen { get { return Color.FromArgb(255, 143, 188, 139); } }
    public static Color DarkSlateBlue { get { return Color.FromArgb(255, 72, 61, 139); } }
    public static Color DarkSlateGray { get { return Color.FromArgb(255, 47, 79, 79); } }
    public static Color DarkTurquoise { get { return Color.FromArgb(255, 0, 206, 209); } }
    public static Color DarkViolet { get { return Color.FromArgb(255, 148, 0, 211); } }
    public static Color DeepPink { get { return Color.FromArgb(255, 255, 20, 147); } }
    public static Color DeepSkyBlue { get { return Color.FromArgb(255, 0, 191, 255); } }
    public static Color DimGray { get { return Color.FromArgb(255, 105, 105, 105); } }
    public static Color DodgerBlue { get { return Color.FromArgb(255, 30, 144, 255); } }
    public static Color Firebrick { get { return Color.FromArgb(255, 178, 34, 34); } }
    public static Color FloralWhite { get { return Color.FromArgb(255, 255, 250, 240); } }
    public static Color ForestGreen { get { return Color.FromArgb(255, 34, 139, 34); } }
    public static Color Fuchsia { get { return Color.FromArgb(255, 255, 0, 255); } }
    public static Color Gainsboro { get { return Color.FromArgb(255, 220, 220, 220); } }
    public static Color GhostWhite { get { return Color.FromArgb(255, 248, 248, 255); } }
    public static Color Gold { get { return Color.FromArgb(255, 255, 215, 0); } }
    public static Color Goldenrod { get { return Color.FromArgb(255, 218, 165, 32); } }
    public static Color Gray { get { return Color.FromArgb(255, 128, 128, 128); } }
    public static Color Green { get { return Color.FromArgb(255, 0, 128, 0); } }
    public static Color GreenYellow { get { return Color.FromArgb(255, 173, 255, 47); } }
    public static Color Honeydew { get { return Color.FromArgb(255, 240, 255, 240); } }
    public static Color HotPink { get { return Color.FromArgb(255, 255, 105, 180); } }
    public static Color IndianRed { get { return Color.FromArgb(255, 205, 92, 92); } }
    public static Color Indigo { get { return Color.FromArgb(255, 75, 0, 130); } }
    public static Color Ivory { get { return Color.FromArgb(255, 255, 255, 240); } }
    public static Color Khaki { get { return Color.FromArgb(255, 240, 230, 140); } }
    public static Color Lavender { get { return Color.FromArgb(255, 230, 230, 250); } }
    public static Color LavenderBlush { get { return Color.FromArgb(255, 255, 240, 245); } }
    public static Color LawnGreen { get { return Color.FromArgb(255, 124, 252, 0); } }
    public static Color LemonChiffon { get { return Color.FromArgb(255, 255, 250, 205); } }
    public static Color LightBlue { get { return Color.FromArgb(255, 173, 216, 230); } }
    public static Color LightCoral { get { return Color.FromArgb(255, 240, 128, 128); } }
    public static Color LightCyan { get { return Color.FromArgb(255, 224, 255, 255); } }
    public static Color LightGoldenrodYellow { get { return Color.FromArgb(255, 250, 250, 210); } }
    public static Color LightGreen { get { return Color.FromArgb(255, 144, 238, 144); } }
    public static Color LightGray { get { return Color.FromArgb(255, 211, 211, 211); } }
    public static Color LightPink { get { return Color.FromArgb(255, 255, 182, 193); } }
    public static Color LightSalmon { get { return Color.FromArgb(255, 255, 160, 122); } }
    public static Color LightSeaGreen { get { return Color.FromArgb(255, 32, 178, 170); } }
    public static Color LightSkyBlue { get { return Color.FromArgb(255, 135, 206, 250); } }
    public static Color LightSlateGray { get { return Color.FromArgb(255, 119, 136, 153); } }
    public static Color LightSteelBlue { get { return Color.FromArgb(255, 176, 196, 222); } }
    public static Color LightYellow { get { return Color.FromArgb(255, 255, 255, 224); } }
    public static Color Lime { get { return Color.FromArgb(255, 0, 255, 0); } }
    public static Color LimeGreen { get { return Color.FromArgb(255, 50, 205, 50); } }
    public static Color Linen { get { return Color.FromArgb(255, 250, 240, 230); } }
    public static Color Magenta { get { return Color.FromArgb(255, 255, 0, 255); } }
    public static Color Maroon { get { return Color.FromArgb(255, 128, 0, 0); } }
    public static Color MediumAquamarine { get { return Color.FromArgb(255, 102, 205, 170); } }
    public static Color MediumBlue { get { return Color.FromArgb(255, 0, 0, 205); } }
    public static Color MediumOrchid { get { return Color.FromArgb(255, 186, 85, 211); } }
    public static Color MediumPurple { get { return Color.FromArgb(255, 147, 112, 219); } }
    public static Color MediumSeaGreen { get { return Color.FromArgb(255, 60, 179, 113); } }
    public static Color MediumSlateBlue { get { return Color.FromArgb(255, 123, 104, 238); } }
    public static Color MediumSpringGreen { get { return Color.FromArgb(255, 0, 250, 154); } }
    public static Color MediumTurquoise { get { return Color.FromArgb(255, 72, 209, 204); } }
    public static Color MediumVioletRed { get { return Color.FromArgb(255, 199, 21, 133); } }
    public static Color MidnightBlue { get { return Color.FromArgb(255, 25, 25, 112); } }
    public static Color MintCream { get { return Color.FromArgb(255, 245, 255, 250); } }
    public static Color MistyRose { get { return Color.FromArgb(255, 255, 228, 225); } }
    public static Color Moccasin { get { return Color.FromArgb(255, 255, 228, 181); } }
    public static Color NavajoWhite { get { return Color.FromArgb(255, 255, 222, 173); } }
    public static Color Navy { get { return Color.FromArgb(255, 0, 0, 128); } }
    public static Color OldLace { get { return Color.FromArgb(255, 253, 245, 230); } }
    public static Color Olive { get { return Color.FromArgb(255, 128, 128, 0); } }
    public static Color OliveDrab { get { return Color.FromArgb(255, 107, 142, 35); } }
    public static Color Orange { get { return Color.FromArgb(255, 255, 165, 0); } }
    public static Color OrangeRed { get { return Color.FromArgb(255, 255, 69, 0); } }
    public static Color Orchid { get { return Color.FromArgb(255, 218, 112, 214); } }
    public static Color PaleGoldenrod { get { return Color.FromArgb(255, 238, 232, 170); } }
    public static Color PaleGreen { get { return Color.FromArgb(255, 152, 251, 152); } }
    public static Color PaleTurquoise { get { return Color.FromArgb(255, 175, 238, 238); } }
    public static Color PaleVioletRed { get { return Color.FromArgb(255, 219, 112, 147); } }
    public static Color PapayaWhip { get { return Color.FromArgb(255, 255, 239, 213); } }
    public static Color PeachPuff { get { return Color.FromArgb(255, 255, 218, 185); } }
    public static Color Peru { get { return Color.FromArgb(255, 205, 133, 63); } }
    public static Color Pink { get { return Color.FromArgb(255, 255, 192, 203); } }
    public static Color Plum { get { return Color.FromArgb(255, 221, 160, 221); } }
    public static Color PowderBlue { get { return Color.FromArgb(255, 176, 224, 230); } }
    public static Color Purple { get { return Color.FromArgb(255, 128, 0, 128); } }
    public static Color Red { get { return Color.FromArgb(255, 255, 0, 0); } }
    public static Color RosyBrown { get { return Color.FromArgb(255, 188, 143, 143); } }
    public static Color RoyalBlue { get { return Color.FromArgb(255, 65, 105, 225); } }
    public static Color SaddleBrown { get { return Color.FromArgb(255, 139, 69, 19); } }
    public static Color Salmon { get { return Color.FromArgb(255, 250, 128, 114); } }
    public static Color SandyBrown { get { return Color.FromArgb(255, 244, 164, 96); } }
    public static Color SeaGreen { get { return Color.FromArgb(255, 46, 139, 87); } }
    public static Color SeaShell { get { return Color.FromArgb(255, 255, 245, 238); } }
    public static Color Sienna { get { return Color.FromArgb(255, 160, 82, 45); } }
    public static Color Silver { get { return Color.FromArgb(255, 192, 192, 192); } }
    public static Color SkyBlue { get { return Color.FromArgb(255, 135, 206, 235); } }
    public static Color SlateBlue { get { return Color.FromArgb(255, 106, 90, 205); } }
    public static Color SlateGray { get { return Color.FromArgb(255, 112, 128, 144); } }
    public static Color Snow { get { return Color.FromArgb(255, 255, 250, 250); } }
    public static Color SpringGreen { get { return Color.FromArgb(255, 0, 255, 127); } }
    public static Color SteelBlue { get { return Color.FromArgb(255, 70, 130, 180); } }
    public static Color Tan { get { return Color.FromArgb(255, 210, 180, 140); } }
    public static Color Teal { get { return Color.FromArgb(255, 0, 128, 128); } }
    public static Color Thistle { get { return Color.FromArgb(255, 216, 191, 216); } }
    public static Color Tomato { get { return Color.FromArgb(255, 255, 99, 71); } }
    public static Color Turquoise { get { return Color.FromArgb(255, 64, 224, 208); } }
    public static Color Violet { get { return Color.FromArgb(255, 238, 130, 238); } }
    public static Color Wheat { get { return Color.FromArgb(255, 245, 222, 179); } }
    public static Color White { get { return Color.FromArgb(255, 255, 255, 255); } }
    public static Color WhiteSmoke { get { return Color.FromArgb(255, 245, 245, 245); } }
    public static Color Yellow { get { return Color.FromArgb(255, 255, 255, 0); } }
    public static Color YellowGreen { get { return Color.FromArgb(255, 154, 205, 50); } }
}

Synchronizing a C# project with a Silverlight project

My tool sucks!

I just wasted a days worth of work. When I started coding Silverlight, I wanted to be able to synchronize my C# projects with my Silverlight projects – I wanted to make sure the same code was present in both projects.

There were no tools to do this, not any that I could find anyway, but there were ways of doing it by hand.

Fast forward to about two days ago, and I needed to synchronize Silverlight projects with C# projects again – and since I had already searched around, I assumed there were no tools to do this. Well, I was wrong. There are – now. Turns out, Microsoft have released a tool that does this. And it does it much better than my tool did.

So if you wish to Synchronize a C# project with a Silverlight project, don’t use my tool, use Microsofts ProjectLinker tool!

I’m leaving my tool up, suck as it may!

I’m leaving my tool up (as in, the CodePlex site will remain active), as an example to anyone who wants to programmatically change Visual Studio projects, parse the Visual Studio XML file (csproj) and such.

Mostly, I’m leaving it up as a testament to my folly, don’t ever trust dated research, do your homework or suffer the consequences!

C# XML Namespace “Fun”

I’ve been working with Visual Studio project files (csproj files) recently – they’re XML files. Now, if you open a csproj file in an editor, you’ll find items that look like this;

  <ItemGroup>
    <Compile Include="Behaviors\Behavior.cs" />
    <Compile Include="Behaviors\Rotator.cs" />
    <Compile Include="Behaviors\BodyRenderableBehavior.cs" />
    <Compile Include="Behaviors\ResistsCollission.cs" />
    <Compile Include="Goal.cs" />
    <Compile Include="GraphicsArgument.cs" />
    <Compile Include="Interfaces\ILevel.cs" />
    <Compile Include="Renderables\BodyHook.cs" />
    <Compile Include="Renderables\BodyHookOwners\BodyHookOwner.cs" />
.
.
.
  </ItemGroup>

These are the actual files that will get included compiled in the assembly. Now, using XElement and it’s descendants to locate these, you’d be forgiven for trying this out (but it won’t work);

        private static void Test(string projectFileName)
        {
            XElement root =
                XDocument.Load(projectFileName).Root;

            const string CompileTag = "Compile";

            List<XElement>
                compiles =
                    root
                        .Descendants(CompileTag)
                        .ToList();

            Console.WriteLine("Found these compiles:");
            compiles.ForEach(
                compile =>
                    Console.WriteLine(
                        "Compile: {0}",
                        compile.Attribute("Include").Value));
            Console.ReadKey();
        }

 

The printed list will be empty. The reason that it’s empty is that the <Compile /> nodes are located in a namespace, and the query above searches in the empty namespace.

You gotta prefix it with the namespace!

You’ll find the namespace in the xlmns attribute in the project root node header;

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" 
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>

The namespace is this url;

http://schemas.microsoft.com/developer/msbuild/2003

So the simples way to change this code to work is to add this namespace to the search criteria. But how to format it? Debugging around a bit gave me the answer, place the namespace within curly-braces in the element name; “{namespace}TagName”. This code works;

        private static void Test(string projectFileName)
        {
            XElement root =
                XDocument.Load(projectFileName).Root;

            const string compileTag = "Compile";
            const string nameSpace = "{http://schemas.microsoft.com/developer/msbuild/2003}";

            List<XElement>
                compiles =
                    root
                        .Descendants(nameSpace + compileTag)
                        .ToList();

            Console.WriteLine("Found these compiles:");
            compiles.ForEach(
                compile =>
                    Console.WriteLine(
                        "Compile: {0}",
                        compile.Attribute("Include").Value));
            Console.ReadKey();
        }

 

You may wish to use the type-safe XNamespace and XName classes instead – note that if you use XNamespace, you can’t have the curly braces in the string;

        private static void Test(string projectFileName)
        {
            XElement root =
                XDocument.Load(projectFileName).Root;

            XNamespace nameSpace = "http://schemas.microsoft.com/developer/msbuild/2003";
            XName compileTag = nameSpace + "Compile";

            List<XElement>
                compiles =
                    root
                        .Descendants(compileTag)
                        .ToList();

            Console.WriteLine("Found these compiles:");
            compiles.ForEach(
                compile =>
                    Console.WriteLine(
                        "Compile: {0}",
                        compile.Attribute("Include").Value));
            Console.ReadKey();
        }

World Of Goo – or a simple aproximation thereof – in Silverlight!?

There’s this wonderful physics based puzzler game called World of Goo, if you have the time, I encourage you to try it out. Buy it, it’s well worth it! I enjoy it by myself and I’ve played it with my six years old son – on the Wii we can play it together.

Anyway, a while back I decided I wanted to try make my own “clone” of World of Goo. At least copy the mechanics and the physics of the game.

Physics in Silverlight / C# / .NET

First of, I needed a physics engine. Previously I’ve worked heavily with Open Dynamics Engine (ODE) – a fully fledged 3D physics engine that I created a Delphi DLL wrapper for waaay back.

But for 2D physics in C#, I was pleasantly surprised to find Farseer Physics – a simple to use and well thought out 2D physics engine based on Box2D.

Rendering in Silverlight / Win32 / WPF

Previously, I’ve only worked with OpenGL, I’ve been a contributor to a OpenGL engine in the distant past. But for 3D graphics in Win32 / Silverlight, I decided to go with WPF – a decision I haven’t regretted.

Putting them Together

After a few days (literally) days of work, I was able to create a simple POC (proof of concept) that imitates World of Goo mechanics and physics using WPF for a renderer.

FreeGoo

Have you ever seen the Simpsons episode where someone offers Homer goo and he replies “ooooh, free gooo!!!”? Well, if you ever have, you’re sure to realize that the only sensible name for a would be clone of World of Goo would be…. FreeGoo! So I created a project on CodePlex where you can download the source of FreeGoo.

If you’re interested in game development then you should download it and give it a try! Here’s a screenshot;

FreeGooScreenshot

And Now for Something Completely Different – Silverlight

Since I’m a Silverlight fan and I’ve built FreeGoo using C# and WPF and FarSeer (both are available in Silverlight), one of my goals are to convert FreeGoo to Silverlight.

I’ll use this blog to outline my progress.

First Step

My first step is to handle the problem that C# projects/assemblies can’t be used in Silverlight and vice versa. That will be possible in Silverlight 4, but currently, it isn’t. What to do? Well, a tool of course – a tool that takes a C# project and emits a Silverlight project…

Stay tuned…

[Edit: Turns out the answer is Project Linker]

Perlin Noise in C#

I had some Delphi code banging around that I’ve used many times, it was originally written by Tom Nuydens (tom@delphi3d.net). I decided to translate it to C#, you’ll find it below and some code where I’m using it.

using System;

namespace ImageTools.Core
{

    /* Perlin noise class.  ( by Tom Nuydens (tom@delphi3d.net) )
 * Converted to C# by Mattias Fagerlund, Mattias.Fagerlund@cortego.se

  ******************************************************************************

  I used the following references for my implementation:
    http://students.vassar.edu/mazucker/code/perlin-noise-math-faq.html
    Darwin Peachey's chapter in "Texturing & Modeling: A Procedural Approach"
  Another good resource is
    http://freespace.virgin.net/hugo.elias/models/m_perlin.htm

  ******************************************************************************

  This class generates 3D Perlin noise. The demo that comes with this is 2D, but
  uses the 3rd dimension to create animated noise. The noise does not tile,
  although it could be made to do so with a few small modifications to the
  algorithm.

  Perlin noise can be used as a starting point for all kinds of things,
  including terrain generation, cloud rendering, procedural textures, and more.
  Most of these techniques involve rendering multiple "octaves" of noise. This
  means you generate multiple noise values for every pixel (each with different
  X, Y and/or Z coordinates), and then sum them. There's an example of this in
  the accompanying demo.
*/

    public class PerlinNoise
    {
        private const int GradientSizeTable = 256;
        private readonly Random _random;
        private readonly double[] _gradients = new double[GradientSizeTable * 3];
        /* Borrowed from Darwyn Peachey (see references above).
           The gradient table is indexed with an XYZ triplet, which is first turned
           into a single random index using a lookup in this table. The table simply
           contains all numbers in [0..255] in random order. */
        private readonly byte[] _perm = new byte[] {
              225,155,210,108,175,199,221,144,203,116, 70,213, 69,158, 33,252,
                5, 82,173,133,222,139,174, 27,  9, 71, 90,246, 75,130, 91,191,
              169,138,  2,151,194,235, 81,  7, 25,113,228,159,205,253,134,142,
              248, 65,224,217, 22,121,229, 63, 89,103, 96,104,156, 17,201,129,
               36,  8,165,110,237,117,231, 56,132,211,152, 20,181,111,239,218,
              170,163, 51,172,157, 47, 80,212,176,250, 87, 49, 99,242,136,189,
              162,115, 44, 43,124, 94,150, 16,141,247, 32, 10,198,223,255, 72,
               53,131, 84, 57,220,197, 58, 50,208, 11,241, 28,  3,192, 62,202,
               18,215,153, 24, 76, 41, 15,179, 39, 46, 55,  6,128,167, 23,188,
              106, 34,187,140,164, 73,112,182,244,195,227, 13, 35, 77,196,185,
               26,200,226,119, 31,123,168,125,249, 68,183,230,177,135,160,180,
               12,  1,243,148,102,166, 38,238,251, 37,240,126, 64, 74,161, 40,
              184,149,171,178,101, 66, 29, 59,146, 61,254,107, 42, 86,154,  4,
              236,232,120, 21,233,209, 45, 98,193,114, 78, 19,206, 14,118,127,
               48, 79,147, 85, 30,207,219, 54, 88,234,190,122, 95, 67,143,109,
              137,214,145, 93, 92,100,245,  0,216,186, 60, 83,105, 97,204, 52};

        public PerlinNoise(int seed)
        {
            _random = new Random(seed);
            InitGradients();
        }

        public double Noise(double x, double y, double z)
        {
            /* The main noise function. Looks up the pseudorandom gradients at the nearest
               lattice points, dots them with the input vector, and interpolates the
               results to produce a single output value in [0, 1] range. */

            int ix = (int)Math.Floor(x);
            double fx0 = x - ix;
            double fx1 = fx0 - 1;
            double wx = Smooth(fx0);

            int iy = (int)Math.Floor(y);
            double fy0 = y - iy;
            double fy1 = fy0 - 1;
            double wy = Smooth(fy0);

            int iz = (int)Math.Floor(z);
            double fz0 = z - iz;
            double fz1 = fz0 - 1;
            double wz = Smooth(fz0);

            double vx0 = Lattice(ix, iy, iz, fx0, fy0, fz0);
            double vx1 = Lattice(ix + 1, iy, iz, fx1, fy0, fz0);
            double vy0 = Lerp(wx, vx0, vx1);

            vx0 = Lattice(ix, iy + 1, iz, fx0, fy1, fz0);
            vx1 = Lattice(ix + 1, iy + 1, iz, fx1, fy1, fz0);
            double vy1 = Lerp(wx, vx0, vx1);

            double vz0 = Lerp(wy, vy0, vy1);

            vx0 = Lattice(ix, iy, iz + 1, fx0, fy0, fz1);
            vx1 = Lattice(ix + 1, iy, iz + 1, fx1, fy0, fz1);
            vy0 = Lerp(wx, vx0, vx1);

            vx0 = Lattice(ix, iy + 1, iz + 1, fx0, fy1, fz1);
            vx1 = Lattice(ix + 1, iy + 1, iz + 1, fx1, fy1, fz1);
            vy1 = Lerp(wx, vx0, vx1);

            double vz1 = Lerp(wy, vy0, vy1);
            return Lerp(wz, vz0, vz1);
        }

        private void InitGradients()
        {
            for (int i = 0; i < GradientSizeTable; i++)
            {
                double z = 1f - 2f * _random.NextDouble();
                double r = Math.Sqrt(1f - z * z);
                double theta = 2 * Math.PI * _random.NextDouble();
                _gradients[i * 3] = r * Math.Cos(theta);
                _gradients[i * 3 + 1] = r * Math.Sin(theta);
                _gradients[i * 3 + 2] = z;
            }
        }

        private int Permutate(int x)
        {
            const int mask = GradientSizeTable - 1;
            return _perm[x & mask];
        }

        private int Index(int ix, int iy, int iz)
        {
            // Turn an XYZ triplet into a single gradient table index.
            return Permutate(ix + Permutate(iy + Permutate(iz)));
        }

        private double Lattice(int ix, int iy, int iz, double fx, double fy, double fz)
        {
            // Look up a random gradient at [ix,iy,iz] and dot it with the [fx,fy,fz] vector.
            int index = Index(ix, iy, iz);
            int g = index*3;
            return _gradients[g] * fx + _gradients[g + 1] * fy + _gradients[g + 2] * fz;
        }

        private double Lerp(double t, double value0, double value1)
        {
            // Simple linear interpolation.
            return value0 + t * (value1 - value0);
        }

        private double Smooth(double x)
        {
            /* Smoothing curve. This is used to calculate interpolants so that the noise
              doesn't look blocky when the frequency is low. */
            return x * x * (3 - 2 * x);
        }
    }
}

And here’s an example of how to use it with three octaves of noise. See my previous post about using lambda to manipulate images, that code is required to make this work;

        private void noiseButton_Click(object sender, EventArgs e)
        {
            PerlinNoise perlinNoise = new PerlinNoise(99);
            Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
            double widthDivisor = 1 / (double)pictureBox.Width;
            double heightDivisor = 1 / (double)pictureBox.Height;
            bitmap.SetEachPixelColour(
                (point, color) =>
                {
                    // Note that the result from the noise function is in the range -1 to 1, but I want it in the range of 0 to 1
                    // that's the reason of the strange code
                    double v =
                        // First octave
                        (perlinNoise.Noise(2 * point.X * widthDivisor, 2 * point.Y * heightDivisor, -0.5) + 1) / 2 * 0.7 +
                        // Second octave
                        (perlinNoise.Noise(4 * point.X * widthDivisor, 4 * point.Y * heightDivisor, 0) + 1) / 2 * 0.2 +
                        // Third octave
                        (perlinNoise.Noise(8 * point.X * widthDivisor, 8 * point.Y * heightDivisor, +0.5) + 1) / 2 * 0.1;

                    v = Math.Min(1, Math.Max(0, v));
                    byte b = (byte)(v * 255);
                    return Color.FromArgb(b, b, b);
                });
            pictureBox.Image = bitmap;
        }

Using lambda to manipulate images

Working with every pixel in an image – the lambda way!

When working with images, I frequently need to apply the same function to every pixel in the image. Since I do that a lot, I decided to create some nice lambda image processing extensions!

In C# Win32, you would typically work with the System.Drawing.Bitmap class, so that’s what I’ll use. In C# WPF, there are other classes you’d use instead, but I won’t go into that in this blog post.

Initially I’ll use two methods, one that allows me to compute the color of each pixel in the image. Another that allows me to perform an arbitrary action for each pixel in the bitmap – the action could set the color of the pixel, but it’s not required.

Here are my extension methods for image manipulation;

using System;
using System.Drawing;

namespace LambdaImageProcessing.Core
{
    public static class BitmapExtensionMethods
    {
        public static void ExecuteForEachPixel(this Bitmap bitmap, Action<Point, Bitmap> action)
        {
            Point point = new Point(0, 0);
            for (int x = 0; x < bitmap.Width; x++)
            {
                point.X = x;
                for (int y = 0; y < bitmap.Height; y++)
                {
                    point.Y = y;
                    action(point, bitmap);
                }
            }
        }

        public static void ExecuteForEachPixel(this Bitmap bitmap, Action<Point> action)
        {
            Point point = new Point(0, 0);
            for (int x = 0; x < bitmap.Width; x++)
            {
                point.X = x;
                for (int y = 0; y < bitmap.Height; y++)
                {
                    point.Y = y;
                    action(point);
                }
            }
        }

        public static void SetEachPixelColour(this Bitmap bitmap, Func<Point, Color> colourFunc)
        {
            Point point = new Point(0, 0);
            for (int x = 0; x < bitmap.Width; x++)
            {
                point.X = x;
                for (int y = 0; y < bitmap.Height; y++)
                {
                    point.Y = y;
                    bitmap.SetPixel(x, y, colourFunc(point));
                }
            }
        }

        public static void SetEachPixelColour(this Bitmap bitmap, Func<Point, Color, Color> colourFunc)
        {
            Point point = new Point(0, 0);
            for (int x = 0; x < bitmap.Width; x++)
            {
                point.X = x;
                for (int y = 0; y < bitmap.Height; y++)
                {
                    point.Y = y;
                    bitmap.SetPixel(x, y, colourFunc(point, bitmap.GetPixel(x, y)));
                }
            }
        }
    }
}

Using my lambda method to draw the color of each pixel as a gradient given the distance to the center of the image. That code looks like this;

        private void renderDistanceFromCenterButton_Click(object sender, EventArgs e)
        {
            // Build the bitmap
            Bitmap bitmap = new Bitmap(pictureBox.Width, pictureBox.Height);
            Point imageCenter = new Point(pictureBox.Width / 2, pictureBox.Height / 2);

            // Ok, this is terrible, you _really_ shouldn't use lambda like this... But you can...
            Func<double, double, double> distance = (x, y) => Math.Sqrt(x * x + y * y);

            double maxDistance = distance(imageCenter.X, imageCenter.Y);
            bitmap.SetEachPixelColour(
                point =>
                {
                    // Pythagoras
                    double dist = distance((point.X - imageCenter.X), (point.Y - imageCenter.Y));
                    byte b = Convert.ToByte(255 * dist / maxDistance);
                    return Color.FromArgb(b, b, b);
                });
            pictureBox.Image = bitmap;
        }

Running this code produces this image;

DistanceFromCenter

Not very pretty, but it works. And I didn’t have to write a single loop, which I find myself doing over and over again when not using lambda functions.

Make image black and white

Converting a color image to black and white can be done this way;

        private void makeBWButton_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = new Bitmap("lena.jpg");
            bitmap.SetEachPixelColour(
                (point, color) =>
                {
                    // Simplest way for making BW
                    byte b = (byte)((color.R + color.B + color.G) / 3);
                    return Color.FromArgb(b, b, b);
                });
            pictureBox.Image = bitmap;
        }

Here’s Lena in color;

lena

And with the BW method above;

lenaBW

Tinting an image – method 1

If you have an image that you wish to tint (mix it with a color) – for instance make it sepia toned – you can use this method;

        public static Color TintColor(Color originalColor, Color tintColor, byte strength)
        {
            byte s1 = (byte)(100 - strength);
            return
                Color.FromArgb(
                (s1 * originalColor.R + strength * tintColor.R) / 100,
                (s1 * originalColor.G + strength * tintColor.G) / 100,
                (s1 * originalColor.B + strength * tintColor.B) / 100);
        }

        private void tintBitmapButton_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = new Bitmap("lena.jpg");
            bitmap.SetEachPixelColour(
                (point, color) =>
                {
                    return TintColor(color, Color.Blue, 50);
                });
            pictureBox.Image = bitmap;
        }

Which produces this Lena;

lenaTint1

Tinting an image – method 2

This method converts the pixel to black and white before mixing in the tint color – so that nothing of the original image color remains;

        private void tint2BitmapButton_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = new Bitmap("lena.jpg");
            Color targetColor = Color.SpringGreen;
            bitmap.SetEachPixelColour(
                (point, color) =>
                {
                    double luminence = ((color.R * 30 + color.G * 59 + color.B * 11) / 100.0) / 255.0;
                    return
                        Color.FromArgb(
                            Convert.ToByte(targetColor.R * luminence),
                            Convert.ToByte(targetColor.G * luminence),
                            Convert.ToByte(targetColor.B * luminence));

                });
            pictureBox.Image = bitmap;
        }

Which produces this Lena;

lenaTint2

Compare two images – the naive way

In a later blog post, I’ll talk about robust ways of comparing images, but here’s a naive approach for comparing two images of the same size. It computes the summed “colour distance” between the images.

        private double CompareBitmaps(Bitmap firstBitmap, Bitmap secondBitmap)
        {
            if (firstBitmap.Width != secondBitmap.Width || firstBitmap.Height != secondBitmap.Height)
            {
                return 1;
            }

            double difference = 0;
            firstBitmap.ExecuteForEachPixel(
                point =>
                {
                    Color firstColor = firstBitmap.GetPixel(point.X, point.Y);
                    Color secondColor = secondBitmap.GetPixel(point.X, point.Y);
                    difference += Math.Abs(secondColor.R / 255.0 - firstColor.R / 255.0);
                    difference += Math.Abs(secondColor.G / 255.0 - firstColor.G / 255.0);
                    difference += Math.Abs(secondColor.B / 255.0 - firstColor.B / 255.0);
                });

            // Normalize the difference so it's not size dependent
            difference /= (firstBitmap.Width * firstBitmap.Height);

            return difference;
        }

Comparing identical images returns 1, comparing totally de-similar images returns 0.