Here Comes the Win2D

Win2D - VS2015

I am very fortunate to be able to attend the Singapore .NET Developer meetup of this month. The topics of the meetup are MVVM, Windows 10, and Win2D. We are glad to have experienced developer, Riza, to be one of the speakers.

Riza's sharing his thoughts about Win2D.

Riza’s sharing his thoughts about Win2D. (Image Credit: .NET Developer Singapore Community)

Due to time constraint, Riza only managed to show us some basic codes for Win2D, a WinRT API for Immediate Mode 2D Graphic Rendering with GPU Acceleration.

Immediate Mode and Retained Mode are two main categories in Graphics API. What are they? I always use the following explanations to help me differentiate between the two modes.

Retained Mode does not directly cause actual graphic rendering. Example: WPF.

Immediate Mode will directly cause actual graphic rendering. Example: Direct2D and System.Drawing library.

Last year, Microsoft proudly announced the Win2D which developers could use it to bring hardware accelerated Direct2D graphics to Windows 8.1 Universal Apps. This undoubtedly is a great news for game developers who would like to publish their games on Surface and Windows Phone in the future.

Let’s Start Coding!

I thus decided to read through some online tutorials to try out this new cool API. The following are two tutorials that I read.

  1. Introduction to Win2D
  2. Win2D – WinRT API for 2D Graphics

The first app that I developed is an app similar to what is being shown in the first tutorial listed above.

Pavel’s code doesn’t work well when I am using the latest version of Win2D from Nuget (Version 0.0.20). For example, the way he sets the speed of the moving circle is as follows.

circle.Speed = new Vector2(-circle.Speed.X, circle.Speed.Y);

However, this won’t work in my project. So, I changed it to the code below.

circle.Speed = new Vector2() { X = -circle.Speed.X, Y = circle.Speed.Y };

For those who play with XNA Framework often should know Vector2 quite well. Yup, it is a vector with 2 components, X and Y. In Win2D, besides Vector2, there are also Vector3 and Vector4.

Required Nuget Package

Before doing the coding, there is a need to add Win2D to the Windows 8.1 Universal App project first.

The interface of Nuget Package Manager has changed in VS2015! Here, we can find Win2D package.

The interface of Nuget Package Manager has changed in VS2015! Here, we can find Win2D package.

VS2015 and Azure

As you can see from the screenshot above, it’s actually VS2015 on Microsoft Azure! On Azure, we can easily create a VM with one of the following editions of VS2015 installed: Professional, Enterprise, and Community. Hence, I no longer need to download VS2015 to my own laptop. =)

However, when I first started the VS 2015 on the new VM, I encountered two problems once I tried to compile my Windows 8.1 Universal App.

Firstly, it said developer license couldn’t be approved because of having no Desktop Experience feature enabled.

“We couldn’t get your developer license for Windows Server 2012 R2”

This was easily solved by enabling the Desktop Experience feature. In the beginning, I was having a hard time finding where to enable the Desktop Experience. Thanks to a blog post written by Tamer Sherif Mahmoud, I found the option as shown in the following screenshot.

Desktop Experience option is actually under User Interfaces and Infrastructure.

Desktop Experience option is actually under User Interfaces and Infrastructure.

Secondly, VS2015 complaint that the Windows 8.1 Universal App couldn’t be activated by the Built-in Adminstrator.

“This app can’t be activated by the Built-in Adminstrator”

What I did to fix this problem is only switching on the Admin Approval Mode for the Built-in Administrator account in Local Group Policy Editor, as shown in the screenshot below.

Enable the UAC: Admin Approval Mode for the Built-in Administrator Error - Solution Step 3 - UAC Admin Approval Mode for Built-in Administrator account.

Enable the UAC: Admin Approval Mode for the Built-in Administrator Error – Solution Step 3 – UAC Admin Approval Mode for Built-in Administrator account.

After doing all these, I could finally compile my first Windows 8.1 Universal App in VS2015.

The UI

<Page
 x:Class="MyUniversal.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:MyUniversal"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 xmlns:win2d="using:Microsoft.Graphics.Canvas.UI.Xaml" 
 mc:Ignorable="d">
    <Grid x:Name="_mainGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <win2d:CanvasControl ClearColor="Black" Grid.Row="1" Draw="OnDraw" x:Name="_canvas" Tapped="OnTapped" />
    </Grid>
</Page>

In order to use CanvasControl, I need to include Microsoft.Graphics.Canvas.UI.Xaml, as highlighted in green in the code above.

The Logic

The following is my Main method.

public MainPage()
{
    this.InitializeComponent();
    _width = (float)Window.Current.Bounds.Width;
    _height = (float)Window.Current.Bounds.Height;
    _timer.Tick += (s, e) => {
        Dictionary<CircleData, int> reference = _circles.ToDictionary(x => x.Key, x => x.Value);

        foreach (var circleKeyPair in reference)
        {
            var circle = circleKeyPair.Key;

            int circleRadiusChangingSpeed = circleKeyPair.Value;

            float posX = circle.Speed.X + circle.Center.X; 
            float posY = circle.Speed.Y + circle.Center.Y;
            circle.Radius += circleRadiusChangingSpeed;

            if (circle.Radius > _height / 4 || circle.Radius <= 0)
            {
                _circles[circle] = -1 * circleKeyPair.Value;
            }

            var radius = circle.Radius;
            if (posX + radius > _width || posX - radius < 0) 
            {
                circle.Speed = new Vector2() { X = -circle.Speed.X, Y = circle.Speed.Y };
            } 
            else if (posY + radius > _height || posY - radius < 0) 
            {
                circle.Speed = new Vector2 { X = circle.Speed.X, Y = -circle.Speed.Y };
            }
            circle.Center = new Vector2 { X = circle.Speed.X + circle.Center.X, Y = circle.Speed.Y + circle.Center.Y };
        }
        
        _canvas.Invalidate();
    };
    
    _timer.Start();
}

In the code, I first define the area to have the circles by declaring two variables _width and _height to be the width and height of the current window. I can’t use the width and height (or even actualWidth and actualHeight) of the grid because they are always 0.

Then same as Pavel, I also move the circles around by having the following code.

circle.Center = new Vector2 { X = circle.Speed.X + circle.Center.X, Y = circle.Speed.Y + circle.Center.Y };

Here, I can’t set X = posX and Y = posY because the circle.Speed here, which is used to define the moving speed and direction, can be already different as the circle.Speed when posX and posY were calculated.

In addition, I also add in the code to change the size of the circle every time it moves. The circle will grow until a certain size and then its radius will be decreased to 0. Once the radius is 0, it will start to increase again.

if (circle.Radius > _height / 4 || circle.Radius <= 0)
{
    _circles[circle] = -1 * circleKeyPair.Value;
}

For those who are wondering what the following line of code does, it is basically just a way to make the canvas control to redraw.

_canvas.Invalidate();

For the OnTapped and OnDraw, I am using the same codes as Pavel’s.

The following screenshot shows the colourful circles created by clicking on the app a few times.

Colourful circles created with DrawCircle.

Colourful circles created with DrawCircle.

That is done using DrawCircle. So, let’s see what will happen if I change to use FillCircle with an image, as taught in the second tutorial mentioned above.

session.FillCircle(circle.Center, circle.Radius, circle.CircleInnerImageBrush);

The CircleInnerImageBrush is created in the following way.

CanvasBitmap image = await CanvasBitmap.LoadAsync(_canvas.Device,
    new Uri("<URL to the image here>"));
CanvasImageBrush imageBrush = new CanvasImageBrush(_canvas.Device, image)
{
     ExtendX = CanvasEdgeBehavior.Clamp,
     ExtendY = CanvasEdgeBehavior.Wrap,
     SourceRectangle = new Rect(0, 0, image.Bounds.Width, image.Bounds.Height)
};

Then I am able to get the following cool effects!

FillCircle + Image

FillCircle + Image

Win2D is Open Source

That’s what I have learnt so far after listening to Riza’s 10-minute sharing on Win2D. I will probably try out the API more in the near future because Win2D looks very promising!

In case, you wonder how much I spent on running VS2015 on Azure, running an A4 (8 cores, 14GB memory) instance for about one week costed me about USD 90.

Oh ya, Win2D is open source! For those who are interested to find out more, please take a look at their GitHub site.

Advertisements

One thought on “Here Comes the Win2D

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s