3D Game Development with Microsoft Silverlight 3: Beginner's Guide

By Gaston C. Hillar
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Lights, Camera, and Action!

About this book

Microsoft Silverlight is a programmable web browser plug-in that enables the animation, vector graphics, and audio-video playback features that characterize Rich Internet Applications. Silverlight is a great (and growing) RIA platform and games are the next level to exploit in it. But it doesn't offer 3D capabilities out of the box and integrating a 3D engine can involve lot of complex mathematics and matrix algebra. This book will help C# developers to get their fingers on the pulse of 3D in Silverlight.

This book uses Balder, an open source 3D engine offering 3D capabilities for Silverlight 3. It leaves out boring matrix algebra and complex 3D mathematics. By the end of the book you will have explored the entire engine, and will be able to design and program your own 3D games with ease!

The book begins by introducing you to the fundamental concepts of 2D games and then drives you into the 3D world, using easy-to-follow, step-by-step examples. The book employs amazing graphics and impressive performance, and increasingly adds more features to a 3D game giving you a rich interactive experience.

By following the practical examples in this book, you will learn the important concepts, from the creation of the initial models, up to the addition of physics and artificial intelligence.

The book helps you to provide realistic behaviors for 3D characters by enveloping models with different textures, using lights to create effects, animating multiple 3D characters using a physics engine (Farseer Physics Engine), and simulating real-life physics. Videos, music, and sounds associated with specific events offer the final touches to the 3D game development learning experience.

Publication date:
September 2009
Publisher
Packt
Pages
452
ISBN
9781847198921

 

Chapter 1. Lights, Camera, and Action!

We want to develop 3D games using Silverlight 3. We will need to work hard in order to achieve this exciting goal. First, we must understand some fundamentals related to various tools and 2D graphics, and their relevance to Silverlight 3. In this chapter, we will cover many topics that will help us understand the new tools and techniques involved in preparing 2D graphics to be used in Silverlight games. This chapter is all about graphics.

In this chapter, we will:

  • Prepare a development environment to develop games using Silverlight 3

  • Recognize the digital art assets from an existing game

  • Create and prepare the digital content for a new 2D game

  • Understand the tools involved in a 2D game development process

  • Learn to manipulate, preview, and scale the digital content

  • Build and run our first graphics application using the digital content

UFOs in the sky!: Invaders

You love 3D games. You have always wanted to develop a 3D game with amazing characters, dazzling scenarios, outstanding effects, and many skill levels. And now you have the opportunity. A legendary game developer drives a new game contest. He challenges Silverlight developers to show him some ideas for a modern 2D Invaders game. If he likes a developer's idea, he will contract him to develop 3D games for his well-known gaming web site using Silverlight 3. This web site pays high wages to developers. It is an incredible opportunity and you cannot miss this train. Tickets, please!

Developing 3D games is an exciting process, but it is also difficult. However, working with a 2D game before moving into the 3D world is a nice starting point. That is exactly what we are going to do.

During our journey, we will need to exploit our creativity as much as possible. Game development requires many heterogeneous skills. However, the most important ingredient is creativity.

We already know how to develop some applications using the C# programming language. However, RIAs (Rich Internet Applications) offer an exciting way ahead for game development because they provide a rich experience for users without the need to install software on their computers. Users expect RIAs to be like conventional downloadable games that offer amazing graphics, impressive performance, and a very interactive experience. Silverlight is a great (and growing) RIA platform, and games are the next level to exploit in Silverlight. 3D games represent our challenge in this book and we shall take full advantage of our C# knowledge here.

So, let's take our C#, XAML, and Silverlight development skills to the next level. We want to take full advantage of modern technologies. First of all, we must install the latest tools and begin working on some 2D games' basics. Later, we will use that knowledge in developing 3D games using Silverlight 3, the newest kid on the block from Microsoft.

The only requirements needed to develop 3D games using Silverlight are to understand the basics of the C# programming language, XAML code, and the Visual Studio IDE. We will cover the rest of the requirements in our journey through the 3D game development world!

 

UFOs in the sky!: Invaders


You love 3D games. You have always wanted to develop a 3D game with amazing characters, dazzling scenarios, outstanding effects, and many skill levels. And now you have the opportunity. A legendary game developer drives a new game contest. He challenges Silverlight developers to show him some ideas for a modern 2D Invaders game. If he likes a developer's idea, he will contract him to develop 3D games for his well-known gaming web site using Silverlight 3. This web site pays high wages to developers. It is an incredible opportunity and you cannot miss this train. Tickets, please!

Developing 3D games is an exciting process, but it is also difficult. However, working with a 2D game before moving into the 3D world is a nice starting point. That is exactly what we are going to do.

During our journey, we will need to exploit our creativity as much as possible. Game development requires many heterogeneous skills. However, the most important ingredient is creativity.

We already know how to develop some applications using the C# programming language. However, RIAs (Rich Internet Applications) offer an exciting way ahead for game development because they provide a rich experience for users without the need to install software on their computers. Users expect RIAs to be like conventional downloadable games that offer amazing graphics, impressive performance, and a very interactive experience. Silverlight is a great (and growing) RIA platform, and games are the next level to exploit in Silverlight. 3D games represent our challenge in this book and we shall take full advantage of our C# knowledge here.

So, let's take our C#, XAML, and Silverlight development skills to the next level. We want to take full advantage of modern technologies. First of all, we must install the latest tools and begin working on some 2D games' basics. Later, we will use that knowledge in developing 3D games using Silverlight 3, the newest kid on the block from Microsoft.

The only requirements needed to develop 3D games using Silverlight are to understand the basics of the C# programming language, XAML code, and the Visual Studio IDE. We will cover the rest of the requirements in our journey through the 3D game development world!

 

Time for action—preparing the development environment


First, we must download and install various Silverlight development tools.

We need to install Visual C# 2008 (.NET Framework 3.5) with Service Pack 1 or greater (Visual C# 2010) in order to successfully complete the installations provided here. Installing Silverlight 3 Tools will uninstall the previous Silverlight versions. We will not be able to create Silverlight 2 applications using Visual C# 2008 with Silverlight 3 Tools installed in our system. Visual C# 2010 does not have this restriction because it allows us to choose the desired Silverlight version target.

Note

You can use the free Visual Web Developer 2008 Express Edition or greater (http://www.microsoft.com/express/vwd/). However, you have to read the documentation and consider its limitations carefully.

The following are steps for preparing the development environment:

  1. 1. Download the following files:

    Application name

    Download link

    File name

    Description

    Expression Design

    http://www.microsoft.com/expression/products/Overview.aspx?key=design

    Design_Trial_en.exe

    It is a commercial tool, but the trial offers a free fully functional version for 30 days. This tool will enable us to transform vector assets to the appropriate format for use in Silverlight 3.

    Inkscape

    http://inkscape.org/download/?lang=en

    Inkscape-0.46.win32.exe

    It is a very complete free, open source, vector drawing program. This tool will enable us to import many vector assets in different, popular file formats and export them to a format recognized by Expression Design.

    Silverlight 3 Tools for Visual Studio

    http://www.microsoft.com/downloads/details.aspx?familyid=9442b0f2-7465-417a-88f3-5e7b5409e9dd&displaylang=en

    Silverlight3_Tools.exe

    We must install it to create Silverlight 3 applications in Visual Studio IDE using XAML and C#. This will uninstall previous Silverlight SDKs (Software Development Kits).

    Silverlight 3 Offline Documentation (in a CHM format)

    http://www.microsoft.com/downloads/details.aspx?familyid=0A9773A7-C854-41FA-B73D-535ABFB73BAF&displaylang=en

    Silverlight_3_Docs.zip

    We must download and decompress this file, as we will be needing access to the Silverlight 3 official documentation.

    Expression Blend 3 + SketchFlow

    http://www.microsoft.com/expression/try-it/Default.aspx#PageTop

    Blend_Trial_en.exe

    This tool will enable us to create content and prototypes that target Silverlight 3. It will be really helpful to use Expression Blend 3 to create rapid prototypes for some game scenes.

    .NET RIA Services

    http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&displaylang=en

    RiaServices.msi

    This framework allows the creation of business applications that are capable of talking to our games. In the same link, there is a PDF file available for download with interesting documentation about this framework.

    Silverlight Toolkit (updated for Silverlight 3 compatibility)

    http://codeplex.com/Silverlight

    Silverlight 3 Toolkit July 2009.msi

    It is convenient to download the latest stable release. This toolkit provides a nice collection of Silverlight controls, components, and utilities made available outside the normal Silverlight release cycle. It will be really helpful to use these controls to provide many game statistics. Besides, it includes more Silverlight themes.

  2. 2. Run the installers in the same order in which they appear in the previous list, and follow the steps to complete the installation wizards. Take into account that to install Silverlight 3 Tools for Visual Studio, you will need an Internet connection for a small download when the wizard begins. One of the items enumerated under the Products affected by the software update: list is Download Preparation, as shown in the following screenshot:

  3. 3. Once the installations have successfully finished, run Visual Studio 2008 or Visual Web Developer 2008 (or later). You will see the Microsoft Silverlight Projects label displayed on the splash screen, as shown in the following picture:

  4. 4. If the splash screen disappears too quickly, you will not be able to check Silverlight's availability. However, you can check it once Visual Studio 2008 or Visual Web Developer 2008 (or later) is running. Select Help | About Microsoft Visual Studio. A dialog box will appear and you will see Microsoft Silverlight Projects 2008 displayed under the Installed products list. Select this item and check whether Product details shows number 3 after the second dot (.). For example, 9.0.30730.126 indicates that Silverlight 3 is installed, as shown in the following picture:

What just happened?

We installed Silverlight 3 Tools for Visual Studio, Expression Blend 3 for Silverlight 3, .NET RIA Services, and Silverlight Toolkit.

Now, we have everything we need to begin creating and testing amazing 2D games using Silverlight 3 and C#.

 

Time for action—recognizing digital art assets


One of the best ways of explaining a new game idea is showing it in a very nice picture. This is exactly what you want to do. However, it is very difficult to find a new game idea from scratch. Therefore, in working out how to impress the legendary game developer, you ask for some help in an 8-bit retro gaming community. You meet a legendary space shooter games' expert and he shows you many remakes of the classic 8-bit Invader game—also known as Space Invaders. The remakes are too simple and they do not exploit modern widescreen displays, as they run in very low resolutions inside the web browsers. A dazzling remake of an Invaders game sounds like a very nice idea!

We are going to take a snapshot of the first scene of one of the most exciting 8-bit implementations of the Invaders game—the legendary TI Invaders—as shown in the following picture:

What just happened?

Looking at the TI Invaders scene picture, we can recognize the following digital art assets:

  • Green aliens

  • Blue aliens

  • Red aliens

  • Tents to protect our ship against the aliens' attack

  • A ship

These assets are organized as shown in the following picture:

The aliens are organized in five rows and eleven columns. There are four tents and just one ship to challenge all these aggressive invaders.

 

Time for action—creating the raster digital content


This prehistoric game used a 256X192 pixels screen (49,152 pixels). We are going to prepare raster digital assets for the game optimized for a 1680X1050 pixels screen (1,764,000 pixels). The game should look nice when compared to the older version.

The old version used 8X8 pixels raster digital assets. In this new version, we can use 50X50 pixels raster digital assets.

Note

The creation of raster digital assets for a 2D game is very complex and requires professional skills. Digital artists and graphic designers are very important members of a professional game development team. They provide great quality digital assets to the programming team.

As you do not have access to professional digital artists yet, you must download some freeware icons and then prepare them to be a part of a game demonstration. Luckily, you will find some nice space and zoom-eyed creatures in PNG (Portable Network Graphics) format that are free to download from Turbomilk (a professional visual interface design company, http://turbomilk.com). They are ideal to use in the game.

Note

PNG is an open, extensible image format with lossless compression. Silverlight 3 works great with PNG images. I recommend not using the JPEG (Joint Photographic Experts Group) format for foreground digital assets or iconic graphics because it uses a lossy compression method that removes some information from the image.

First, we are going to download, manipulate, resize, and finally save the new versions of the new raster digital content for the game:

  1. 1. Download the PNG images for the green, blue, and red aliens, the tents, and the ship. You can take some nice images from http://turbomilk.com/downloads/.

  2. 2. Save all the original PNG images in a new folder (C:\Silverlight3D\Invaders\GAME_PNGS), as shown in the following picture:

  3. 3. Open the images for the aliens, ship, and tents using an image-manipulation tool. You can use a free and open source software such as GIMP (the GNU Image Manipulation Program) that is available at http://www.gimp.org, or a commercial software such as Adobe Photoshop available at http://www.adobe.com, or free software such as Picasa available at http://picasa.google.com.

  4. 4. Remove the shadows from the images because we are not going to use them as icons. You can select the shadows and delete them using the magic wand tool (fuzzy select tool). It requires high precision in the selection to avoid deleting the original drawing. Shadows have to be removed because we want to use them as raster content for the game, as shown in the following picture:

  5. 5. Remove the transparent pixels from the images (that is, erase the selection).

  6. 6. Resize the images for the aliens and the ship to 50X50 pixels square, while keeping proportions. Save them in a PNG format using the following names:

    • ALIEN_01_01.png—the blue alien, the octopus

    • ALIEN_02_01.png—the red alien, the gothic cherry

    • ALIEN_03_01.png—the green alien, the eye

    • SHIP_01_01.png—the ship

  7. 7. Resize the image for the tents to 100X100 pixels square, while keeping proportions. Save it in a PNG format using the name TENT_01_01.png.

  8. 8. Now, copy the newly manipulated and resized images in a new folder (C:\Silverlight3D\Invaders\GAME_PNGS_RESIZED), as shown in the following picture:

What just happened?

We created raster digital content for the game optimized for a 1680X1050 pixels screen. We downloaded some images, and manipulated them to remove the shadows and prepare them for the game's main scene. We used a naming convention for the images as we want to keep everything well organized for the game.

The game will look nice using these modern raster digital art assets.

Digital Content Creation tools

The Digital Content Creation tools (DCC) are very important partners for game designers and developers. They allow digital artists and graphic designers to concentrate on the creation of different kinds of digital art assets, which are then used in the applications.

Note

We can also use everything we are learning in developing the applications that have intensive graphical resources. However, we will call them games in the rest of the book.

It is very easy to understand their purpose using an example. If you want to show a sky with stars as an application's background, the easiest way to do it is by loading a bitmap (PNG, BMP, JPG, and so on) using the procedures or controls provided by the programming language.

A digital artist will create and manipulate the sky bitmap using an image manipulation tool such as GIMP, Photoshop, or Picasa.

Developing games requires the usage of a great number of resources; it is not just programming tasks. We are going to use many popular DCC tools during our journey to create Silverlight 3D games. As many of these tools are very expensive, we will use some open source and free alternatives to carry out the most important tasks.

A good practice before beginning 2D and 3D game development is to research the tools used to create the 2D and 3D digital content. This way, we will have a better idea of how to create the different scenes and the most common techniques. Later, we will learn the programming techniques used to give life to these graphics-related operations. We will be able to provide great real-time interaction to all these digital content assets, as shown in the following diagram:

Basic elements of a 2D and/or 3D real-time game

A modern 2D and/or 3D real-time game uses the basic elements shown in the previous diagram. Let's go through them in the following list:

  • 2D images: These can be raster bitmaps as used in our previous example, or vector graphics—also known as vector-based illustrations. In some cases, they are useful as a background made of a starry sky, or a cloudy sky. In other cases, they are used as textures to envelope different 3D objects. For example, a 2D brick's image is used as a texture to envelope a 3D object representing a wall.

  • 3D models: These contain information about the representations of primitive elements (point, lines, triangles, and polygons) to create great meshes, similar to a wire mesh that describes a 3D model. Their different parts can be enveloped by textures. Then everything renders in a representation in the 2D space shown by the players' screens.

  • Effects definitions: These can be applied to 3D models to offer more realism in the production of many scenes. To simplify the development process, there are many specific programming languages used to define the behavior of effects.

  • Maps: It is easier to create real-time digital content using different kinds of maps and diverse proprietary formats. Maps can specify the location of the different kinds of houses and trees in a game that involves driving a car in a city. It is possible to create many levels based on the same logic and behavior programmed for a game, but by using many different maps.

Many specialized DCC tools help in creating the basic elements explained in the aforementioned list. For example, using GIMP you can see the alpha channel for the ship's PNG image, as shown in the following picture:

Programming responsibilities

We do not have to write lines of code dedicated to creating an image. Instead, modern game programming focuses on the following tasks:

  • Loading: We must load 2D images, 3D models, textures, effects definitions, and maps using different kinds of content loaders, parsers, import techniques, and translators. They are going to help us in transforming the original file formats to the ones supported by the programming language and the framework used to develop the game.

  • Drawing: A game's main goal is to show real-time graphics content in a screen. One of the main problems is that 3D scenes have to be shown in a screen capable of showing just two of these three dimensions.

  • Logic and control: While the content is being loaded and shown, it is necessary to apply some AI (Artificial Intelligence) to logic operations, and to provide feedback according to the controls offered to the user for certain game actors and aspects. In order to achieve this goal, it is necessary to develop accurate time-management techniques coordinated with the information obtained from the hardware applied to control the game—the keyboard, mouse, racing wheel, gamepad, or the Wiimote (Wii Remote), among others. All of these tasks must be done while managing many heterogeneous pieces and showing a very complex audiovisual production. Thus, we must take into account everything related to the execution speed and issues of performance.

Programming games requires more knowledge about the underlying hardware on which the game will be run. We must establish performance baselines and minimum requisites to achieve a desirable performance for the game. Besides, we must specify the recommended input devices to take full advantage of the game. These tasks could seem pretty trivial, but they are very important because some games are very complex and demand many difficult optimizations to be able to run on the mainstream hardware available.

This is a simple summary of a game's programming responsibilities. We will work through them all throughout this book.

 

Time for action—installing tools to manipulate scalable digital content


Your cell phone rings. An old friend sees your name in the participants' list and calls you because he has some interesting information. He tells you the game has to scale to huge resolutions such as the ones found in exclusive XHD (eXtreme High Definition) displays. These displays can support resolutions as high as 2560X1600 pixels.

Scaling the raster digital assets is a big problem because pixelation becomes easily visible. If you scale the final alien for using it in a higher resolution, it will look really pixelated as shown in the following picture:

You want the game to use the entire screen space, even in the XHD displays. To make this possible, you could prepare another set of raster digital assets for the game optimized for a 2560X1600 pixels screen (4,096,000 pixels). However, the game can also be run using a 1920X1080 pixels screen (2,073,600 pixels). There is another alternative of creating a new set of scalable vector graphics (vector-based illustrations), which are ready to scale to any screen resolution without generating pixelation problems.

This way, you can provide two versions of the same game—one using raster digital assets optimized for a 1680X1050 pixels screen and the other using scalable vector graphics. There is no restriction in the number of games per participant. Therefore, you can submit both versions.

Note

The creation of scalable vector graphics assets for a 2D game is very complex and involves professional skills. We are going to simplify this process by using the existing clipart.

First, we must download and install some additional tools that will help us in converting the existing scalable vector graphics to the most appropriate file formats to use in Silverlight 3:

Note

The necessary tools will depend on the applications the digital artists use to create the scalable vector graphics. However, we will be using some tools that will work fine with our examples.

  1. 1. Download the following files:

    Application name

    Download link

    File name

    Description

    Expression Design

    http://www.microsoft.com/expression/products/Overview.aspx?key=design

    Design_Trial_en.exe

    It is a commercial tool, but the trial offers a free fully functional version for 30 days. This tool will enable us to transform vector assets to the appropriate format for use in Silverlight 3.

    Inkscape

    http://inkscape.org/download/?lang=en

    Inkscape-0.46.win32.exe

    It is a very complete free, open source, vector drawing program. This tool will enable us to import many vector assets in different, popular file formats and export them to a format recognized by Expression Design.

  2. 2. Run the installers and follow the steps to complete the installation wizards.

  3. 3. Once Inkscape's installation is finished, you will be able to load and edit many vector assets in different file formats as shown in the following picture:

What just happened?

We installed Expression Design and Inkscape. Now we have the necessary tools to convert the existing vector clipart to the most appropriate formats to use in Silverlight 3.

XAML works fine with Silverlight 3

Why do we need to install so many tools to create a simple vector asset to use in Silverlight 3? It's because Silverlight 3 uses XAML (eXtensible Application Markup Language), and the best way to add scalable vector content is using objects defined in XAML. However, many tools that offer functions to export to XAML do not work as expected and are not compatible with Silverlight 3. Besides, many converters are still in alpha versions and have problems when we need to convert complex vector art.

The game must be finished on or before the due date. Therefore, to avoid problems related to XAML vector assets, we are going to perform additional steps. But we will be sure that the resulting XAML will work fine with Silverlight 3.

 

Time for action—creating the scalable digital content in XAML


As you do not have access to professional digital artists yet, you must download some free clipart and then prepare it to be a part of a scalable game demonstration. This time, you want to offer a different version of the game by mixing some Halloween monsters (the new invaders) with the ship. This will be the vector-graphics based game. Luckily, you find some nice, free-to-use clipart in WMF (Windows Meta-File) scalable vector format from Microsoft Office Clipart. They are great to use for offering a different scalable version of the game.

Note

WMF is an old, scalable vector format. Silverlight 3 does not offer direct support for WMF graphics. Therefore, we must convert WMF graphics to XAML. Following the next steps, we can also convert from any vector formats supported by Inkscape such as SVG (Scalable Vector Graphics), AI (Adobe Illustrator), PDF (Adobe PDF), and EMF (Enhanced Meta-File) among others.

First, we are going to download, organize, and convert some scalable vector graphics to XAML which is compatible with Silverlight 3:

  1. 1. Download or copy the vector graphics for the green, blue, and red aliens, the tents, and the ship. Remember that this version is themed on Halloween monsters. You can take some nice graphics from the Microsoft Office Clipart Collection.

  2. 2. Save all of the original WMF images in a new folder (C:\Silverlight3D\Invaders\GAME_WMFS), as shown in the following picture:

  3. 3. Repeat the following steps (4 to 13) for each vector graphic (WMF file).

  4. 4. Open the vector graphic file in Inkscape.

  5. 5. Select File | Save a copy.... A dialog box showing many export options will appear.

  6. 6. Remove the extension from the filename. For example, if the filename shown is ALIEN_01_01.wmf, the new name will be ALIEN_01_01.

  7. 7. Choose the PDF via Cairo (*.PDF) option in the combo box that lists the available file formats to export. Click on Save and then on OK. Now, you will have the vector graphic as a PDF file. You will be able to open the file using any PDF reader such as Adobe Acrobat Reader or Foxit Reader.

  8. 8. Rename the new PDF file and change its PDF extension to AI. For example, if the file name generated by Inkscape is ALIEN_01_01.pdf, the new name will be ALIEN_01_01.ai.

  9. 9. Now, open the file with the .ai extension in Microsoft Expression Design.

  10. 10. Select File | Export.... A dialog box with many export options will appear.

  11. 11. Choose XAML Silverlight Canvas in the Format combo box under Export properties. Now, you will be able to see a nice image preview as shown in the following picture:

  12. 12. Click on Browse... and choose the destination folder for the new XAML file (C:\Silverlight3D\Invaders\GAME_XAML).

  13. 13. Click on Export All and Expression Design will create the XAML file. You can preview the XAML file in Internet Explorer, as shown in the following picture:

What just happened?

We created scalable vector graphics and converted them to an XAML format, which is compatible with Silverlight 3. We downloaded some images and used a process to convert them to a format that Microsoft Expression Design can read. As this tool does not work with WMF files, we needed to provide an AI-compatible format.

We converted the files to a PDF format, which is compatible with the newest AI formats. Expression Design can read this format, but it requires the files to have the .ai extension. That is why we needed to rename the files exported from Inkscape as PDF.

We used Inkscape because it is free, open source, and compatible with the most popular scalable vector graphics formats. However, we did not export to XAML from Inkscape because there are some incompatibilities in that conversion. The most secure way to export to XAML these days is using Expression Design.

This scalable vector content for the game could be optimized for any resolution. We used the same naming convention previously employed by the raster graphics, as we want to keep everything well organized for the two versions of the game. One will show raster aliens and the other, scalable Halloween monsters.

The game will look nice on XHD monitors using these scalable vector art assets.

Previewing and scaling XAML vector graphics

The XAML vector graphics can scale while keeping their quality intact when they are used in Silverlight 3 applications. This is not new; this happened with all the vector graphics formats. Scaling the vector graphics is not a problem because they do not have pixelation problems. However, they require more processing time than raster graphics to be shown on a screen.

If you scale one of the Halloween monsters to use it in a higher resolution, it will look really great as shown in the following picture:

A very interesting hidden tool that can help us when working with XAML and XAML vector graphics is XamlPad.

XamlPad is a part of the WPF (Windows Presentation Foundation) SDK. Once Visual Studio is installed, it is available in the following folder: Program Files\Microsoft SDKs\Windows\v6.0A\bin. You must create a manual shortcut to XamlPad.exe in that folder because it is not available in a menu shortcut.

 

Time for action—testing the scalable digital content using XamlPad


Now, we are going to test how an XAML vector graphic scales using XamlPad:

  1. 1. Open one of the XAML vector graphics exported by Expression Design using Windows Notepad.

  2. 2. Select all of the text and copy it to the clipboard.

  3. 3. Run XamlPad.

  4. 4. Paste the clipboard's content (the XAML definition) in the XAML area. You will see the illustration appearing in the top panel, as shown in the following picture:

  5. 5. Change the zoom many times, taking into account that you can enter manual values. You will see the illustration appearing with different sizes without pixelation problems.

  6. 6. Click on Show/Hide the visual tree. The Visual Tree Explorer and Property Tree Explorer will allow you to navigate through the different components of this scalable XAML vector illustration, as shown in the following picture:

What just happened?

We used a very simple yet handy tool called XamlPad to preview XAML-scalable vector illustrations. Now, we are sure that the scalable clipart for the game is going to work fine in different resolutions. We can include these vector illustrations in Silverlight 3 applications.

Editing vector illustrations using Expression Design

Expression Design is a very useful tool if we need to create special effects with 2D XAML vector graphics. Using this tool, a digital artist can create and manipulate vector graphics. Also, this tool can define a name for each shape. Thus, we can later add some code to change some of the properties of these shapes by using the names to identify them.

For example, we can change an eye's color. However, we need 2D XAML vector graphics that use nice names to identify each shape. The following picture shows Expression Design editing our well-known Halloween monster to provide nice names for the shapes that define the eye's background and background border:

Using expression design, we can also add effects to many shapes and layers. Hence, if we are going to work hard with Silverlight 3, it is a very important tool for the digital artists involved in the project.

Note

Our main goal is to develop games using Silverlight 3. However, it is very important to understand the preparation of digital art assets.

Have a go hero—preparing scalable digital content for a new remake

You have to win the game contest. As you know, there is no restriction on the number of games per participant. What about preparing another completely different game to participate in this contest?

Take a classic game that is based one screen and does not have scrolling capabilities, similar to the Invaders game. Prepare scalable vector graphics in an XAML format to represent its characters. However, this time, prepare some additional animation frames for each character. We will use them in the following chapter to prepare that game using a new framework.

You can do it. If you are not a good artist, you can download free clipart from the Web and then use the techniques and tools previously explained to create vector graphics in XAML format that are ready for use in Silverlight 3 games.

 

Preparing a gaming framework


Silverlight 3 does not provide a gaming framework. However, it offers outstanding graphics-rendering capabilities that are combined with really useful time-management features. Hence, we will have to add some code to prepare a framework to simplify the development of games, combining the powerful C# programming language and the flexibility of XAML.

We will have to work harder in our initial games because we will be preparing a gaming framework. However, once we have the framework, we will be able to develop new games reusing a lot of code. Thus, we can focus more on the game behavior and graphic effects.

 

Time for action—creating Silverlight applications


First of all, you have to create a Silverlight application and see how it works in a web browser. To best understand how it works, we can see it in action and experience a vector graphic moving on the screen while the mouse pointer changes its position. These are the steps to do it:

  1. 1. Create a new C# project using the Silverlight Application template in Visual Studio or Visual C# Express. Use SilverlightMonster.Web as the project's name.

  2. 2. The IDE is going to present a dialog box showing many options for a new Silverlight application. Activate the Host the Silverlight application in a new Web site checkbox, as shown in the following screenshot:

  3. 3. Click on OK and the IDE will create an empty Silverlight application, including a Web project. The Web project will allow us to change some properties to configure the Silverlight runtime.

  4. 4. Right-click on SilverlightMonster (the main project) in the Solution Explorer and select Add | Existing item... from the context menu that appears.

  5. 5. Choose the destination folder for the previously generated XAML files (C:\Silverlight3D\Invaders\GAME_XAML) and select a vector asset (ALIEN_01_01.xaml). Now click on Add.

  6. 6. Select the recently added item (ALIEN_01_01.xaml) in Solution Explorer and right-click on it. You will not be able to see the graphic in the IDE's screen. Select Open in Expression Blend. A security-warning dialog box will appear. Do not worry; the project is secure. Click on Yes. Now, the project will be opened in Expression Blend and you will see the vector graphic on the screen, as shown in the following picture:

  7. 7. Right-click on the canvas named Layer_3 under Objects and Timeline window, and select Make Into UserControl... in the context menu that appears. A dialog box will appear.

  8. 8. Enter the name Ghost for this new UserControl and click on OK. A new item will be added to the SilverlightMonster project named Ghost.xaml. Save the changes and go back to Visual Studio or Visual C#, and reload the contents of the solution.

  9. 9. Now, you will be able to see the graphics representation of this UserControl in Visual Studio or Visual C#. Expand Ghost.xaml in the Solution explorer and you will find Ghost.xaml.cs (the C# code related to the XAML UserControl), as shown in the following picture:

    Note

    Silverlight 3 RTW (Ready To Web) made the default XAML preview capabilities invisible for Silverlight projects in Visual C# 2008. We have to resize the preview panel in order to see the graphics representation. The preview capabilities are available without changes in Visual Studio 2010 or Visual C# 2010.

What just happened?

You created your first Silverlight application showing the ghost that will be a part of your game. It required too many steps, and you had to combine two tools: Visual Studio or Visual C#, and Expression Blend. It seems complex, but once you get used to working with graphic manipulation tools and development environments to create Silverlight games, it is going to be easier.

We created a new web site to host our Silverlight application because that is going to allow us to change many advanced parameters related to Silverlight's runtime that are very useful to improve the performance of our games.

We created a UserControl from an existing XAML-scalable vector illustration. A UserControl has its XAML representation and provides its own logic.

 

Time for action—building and running Silverlight applications


Now, you want to see the ghost moving on the screen while the mouse pointer changes its position. In order to do this, we must add some code to show the ghost and to move it. We will add both XAML and C# code as follows:

  1. 1. Stay in the SilverlightMonster project.

  2. 2. Open the XAML code for MainPage.xaml (double-click on it in the Solution Explorer) and replace the existing code with the following:

    <UserControl x:Class="SilverlightMonster.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml
    /presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Cursor="None"
    Width="1366" Height="768" MouseMove="Ghost_MouseMove"
    xmlns:SilverlightMonster="clr-namespace:SilverlightMonster">
    <Canvas x:Name="cnvMovementTest" Width="1366" Height="768"
    Background="Bisque">
    <SilverlightMonster:Ghost Canvas.Left="10" Canvas.Top="10"
    x:Name="ghost"/>
    </Canvas>
    </UserControl>
    
  3. 3. You will see the ghost appearing in the upper-left corner of the page in the designer.

  4. 4. Now, expand MainPage.xaml in the Solution Explorer and open MainPage.xaml.cs (double-click on it). We need to add an event handler to move the ghost on the screen to the position where the mouse has moved.

  5. 5. Add the following lines of code in the public partial class MainPage : UserControl to program the event handler for the MouseMove event:

    private void Ghost_MouseMove(object sender, MouseEventArgs e)
    {
    // Get the mouse current position
    Point point = e.GetPosition(cnvMovementTest);
    // Set the canvas Left property to the mouse X position
    ghost.SetValue(Canvas.LeftProperty, point.X);
    // Set the canvas Top property to the mouse Y position
    ghost.SetValue(Canvas.TopProperty, point.Y);
    }
    
  6. 6. Build and run the solution. The IDE will ask whether you want to turn on debugging or not. It is always convenient to click on Yes because you will need to debug many times. The default web browser will appear showing a bisque background and the ghost will move following the mouse pointer, as shown in the following picture:

What just happened?

The ghost appeared in the web browser and it moved through the bisque rectangle as if it were a mouse pointer. You created and ran your first Silverlight application in the web browser.

First, we changed the XAML code for MainPage.xaml. We made some changes to do the following:

  • Hide the mouse pointer (the cursor):

    <UserControl x:Class="SilverlightMonster.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml
    /presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Cursor="None"
    
  • Specify width and height of 1366X768 pixels:

    Width="1366" Height="768"
    
  • Indicate a MouseMove event handler:

    MouseMove="Ghost_MouseMove"
    
  • Reference the SilverlightMonster namespace to allow access to the definitions specified in it:

    xmlns:SilverlightMonster="clr-namespace:SilverlightMonster">
    

Then, we added a Canvas named cnvMovementTest (with a 1366X768 pixels width and height), a bisque background, and an instance of Ghost (SilverlightMonster:Ghost) named ghost located in the point (10, 10) taking into account both the Canvas and its upper-left corner:

<Canvas x:Name="cnvMovementTest" Width="1366" Height="768"
Background="Bisque">
<SilverlightMonster:Ghost Canvas.Left="10" Canvas.Top="10"
x:Name="ghost"/>
</Canvas>

Programming event handlers in the main page

Once the ghost was shown using XAML code, we had to program code for the event handler, which is triggered when the mouse moves on the main page's UserControl. We had indicated the MouseMove event handler as Ghost_MouseMove. For this reason, we defined a private void method with that name in the C# class MainPage, associated with the previously explained XAML.

As mentioned earlier, we defined the cnvMovementTest Canvas in the XAML section. The code in the event is very simple. However, it interacts with some elements defined in the XAML code.

The following line retrieves the mouse's current position as an instance of Point—a 2D vector, with two coordinates (X and Y):

Point point = e.GetPosition(cnvMovementTest);

Now we call the SetValue method for ghost (the instance of Ghost is already defined in the XAML section). We assign the values of the X and Y coordinates of the 2D vector to the Left and Top properties of the canvas containing the ghost illustration:

ghost.SetValue(Canvas.LeftProperty, point.X);
ghost.SetValue(Canvas.TopProperty, point.Y);

Note

We can create visual objects, such as the ghost of this example, in XAML or using C# code. Sometimes, it is more convenient to use XAML, whereas at other times it is more convenient to use C# code. It depends on the kind of application we are developing.

 

Time for action—creating XBAP WPF applications


Silverlight is a subset of WPF. One of the great advantages of Silverlight applications is that they just require a plugin installed in the web browser to run. However, sometimes, we need to develop games that require more power than what is being provided by Silverlight. In those cases, we can create an XBAP (XAML Browser Application) WPF application by making some small changes to the source code.

Note

XBAP WPF applications are not based on Silverlight. They are .NET WPF applications capable of running in a sandbox (to avoid security problems) inside a web browser. They run with Internet zone permissions and require the entire .NET framework to be installed on the computer that wants to run them. Therefore, they have some limitations when compared with the classic .NET WPF applications that run on the desktop. The XBAP WPF applications are an interesting alternative when the power of Silverlight is not enough.

Now, you want to create the same application that worked with Silverlight as an XBAP WPF application. If you need more power in any of your games, you will want to have the alternative to work with the XBAP WPF applications.

  1. 1. Create a new C# project using the WPF Browser Application template in Visual Studio or Visual C# Express. Use SilverlightMonsterXBAP as the project's name. You will see a slightly different IDE, as it allows access to most of the WPF applications' features and controls.

  2. 2. Right-click on SilverlightMonsterXBAP in the Solution Explorer and select Add | Existing item... from the context menu that appears.

  3. 3. Choose the destination folder for the previously generated XAML files (C:\Silverlight3D\Invaders\GAME_XAML) and select a vector asset (ALIEN_01_01.xaml). Now click on Add.

  4. 4. Select the recently added item (ALIEN_01_01.xaml) in the Solution Explorer and double-click on it. In this case, you will be able to see the graphic in the IDE's screen.

  5. 5. Select Project | Add User Control... from the main menu. A dialog box will appear.

  6. 6. Enter the name Ghost for this new UserControl and click on OK. A new item will be added to the SilverlightMonsterXBAP project, named Ghost.xaml.

  7. 7. Open the XAML code for ALIEN_01_01.xaml. Copy from the following line to the line before the last </Canvas>:

    <Canvas x:Name="Layer_3" Width="193.333" Height="128"
    Canvas.Left="0" Canvas.Top="0">
    
  8. 8. Open the XAML code for Ghost.xaml. Remove the following text (as we want the UserControl to take the size from the ghost illustration):

    Height="300" Width="300"
    
  9. 9. You will see the following code:

    <UserControl x:Class="SilverlightMonsterXBAP.Ghost2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml
    /presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
    </Grid>
    </UserControl>
    
  10. 10. Select the lines from <Grid> to </Grid> (inclusive) that define a Grid, and paste the XAML code previously copied from ALIEN_01_01.xaml.

  11. 11. Now, you will see the graphics representation of this UserControl in Visual Studio or Visual C#. Expand Ghost.xaml in the Solution explorer and you will find Ghost.xaml.cs (the C# code related to the XAML UserControl) as shown in the following picture, but this time in a XBAP WPF application:

What just happened?

You created your first XBAP WPF application showing the ghost that will be a part of your future game. It required some steps that were different from those you learned to create this same application for Silverlight.

We created a WPF UserControl from an existing XAML scalable vector illustration. Once we create the UserControl, the steps and the code required are very similar to the ones explained for the Silverlight version. However, it is very interesting to understand the whole development process.

 

Time for action—building and running the XBAP WPF applications


Now, you want to see the ghost moving on the screen as an XBAP WPF application while the mouse pointer changes its position. In order to do this, we must add some code to show the ghost and to move it. We will add both XAML and C# code as follows:

  1. 1. Stay in the SilverlightMonsterXBAP project.

  2. 2. Open the XAML code for Page1.xaml (double-click on it in the Solution Explorer) and replace the existing code with the following:

    <Page x:Class="SilverlightMonsterXBAP.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml
    /presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    Cursor="None">
    <Canvas Width="1366" Height="768" MouseMove="Ghost_MouseMove"
    xmlns:SilverlightMonsterXBAP=
    "clr-namespace:SilverlightMonsterXBAP">
    <Canvas x:Name="cnvMovementTest" Width="1366" Height="768"
    Background="Bisque">
    <SilverlightMonsterXBAP:Ghost Canvas.Left="10"
    Canvas.Top="10" x:Name="ghost"/>
    </Canvas>
    </Canvas>
    </Page>
    
  3. 3. You will see the ghost appearing in the upper-left corner of the page in the designer.

  4. 4. Expand Page1.xaml in the Solution Explorer and open Page1.xaml.cs (double-click on it). We need to add an event handler to move the ghost on the screen to the position to which the mouse has moved.

  5. 5. Add the same lines of code previously explained for the Silverlight version in the public partial class Page1 : Page to program the event handler for the MouseMove event.

  6. 6. Build and run the solution. The default web browser will appear showing a bisque background and the ghost will move following the mouse pointer. This time, it is running an XBAP WPF application, as shown in the following picture:

What just happened?

The ghost appeared in the web browser and moved through the bisque rectangle as if it were a mouse pointer. The application looked very similar to its Silverlight version. However, in this case, you have access to most of the WPF features and controls. You created and ran an XBAP WPF application in the web browser.

Note

XBAP WPF applications require more time to start than Silverlight applications. Therefore, we should not confuse Silverlight with XBAP WPF. They are two different technologies. However, we can transform a Silverlight application to an XBAP WPF application by making small changes to the source code, as shown in this example.

First, we changed the XAML code for Page1.xaml. We made some changes to do the following:

  • Hide the mouse pointer (the cursor) using the following code:

    <Page x:Class="SilverlightMonsterXBAP.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1"
    Cursor="None">
    
  • Replace the Grid definition with a Canvas and indicate a MouseMove event handler:

    MouseMove="Ghost_MouseMove"
    
  • Reference the SilverlightMonsterXBAP namespace to allow access to the definitions specified in it:

    xmlns:SilverlightMonsterXBAP="clr-namespace:SilverlightMonsterXBAP">
    

Next, we added a Canvas named cnvMovementTest with a resolution of 1366X768 pixels (width and height), a bisque background, and showed an instance of Ghost (SilverlightMonster:Ghost) named ghost located on the point (10, 10) by taking into account both the Canvas and its upper-left corner:

<Canvas x:Name="cnvMovementTest" Width="1366" Height="768" Background="Bisque">
<SilverlightMonsterXBAP:Ghost Canvas.Left="10" Canvas.Top="10"
x:Name="ghost"/>
</Canvas>

Once the ghost is shown using XAML code, we had to program the code for the event handler that triggered when the mouse moved on the main page's UserControl. We followed the same procedure previously explained in the Silverlight version of this application.

Have a go hero—creating a prototype for the remake

You receive an email from the game contest. They require each participant to send a Silverlight prototype of the first scene of the game without movement—a still snapshot.

Using the scalable vector graphics in an XAML format prepared for the Invader game, create a new Silverlight application that reproduces the first screen of the game with the aliens organized in five rows and eleven columns, the four tents, and the ship.

You can do it creating one UserControl for each vector graphics as we did for the ghost. Now, you can organize a nice Silverlight prototype by defining a Canvas for each alien and tent, and then for the ship using 2D coordinates.

Pop quiz—preparing the digital content

  1. 1. When scaling raster digital assets:

    • a. Pixelation becomes easily visible.

    • b. Pixelation is no problem.

    • c. We must previously perform a conversion to XAML to avoid pixelation.

  2. 2. When scaling vector graphics:

    • a. We must previously perform a conversion to WMF to avoid pixelation.

    • b. Pixelation becomes easily visible.

    • c. Pixelation is no problem.

  3. 3. XamlPad is an utility whose main goal is:

    • a. To preview XAML content.

    • b. To convert WMF and EMF formats to XAML.

    • c. To test a Silverlight 3 application.

  4. 4. Silverlight 3 works great with raster digital assets in:

    • a. The TGA (Targa) format.

    • b. The PNG (Portable Network Graphics) format.

    • c. The XJT (Compressed XJT GIMP) format.

  5. 5. Silverlight 3 works great with vector graphics in:

    • a. The WMF (Windows Meta-File) format.

    • b. The CDR (CorelDRaw) format.

    • c. The XAML (eXtensible Application Markup Language) format.

  6. 6. Silverlight is:

    • a. A subset of WPF.

    • b. An extension to WPF.

    • c. A plugin to add more controls to the XBAP WPF applications.

  7. 7. XBAP WPF applications are:

    • a. The same as Silverlight applications (with just a different name).

    • b. .Net WPF applications that can run in a sandbox or inside a web browser with some security restrictions.

    • c. .Net WPF applications that can run on a desktop or in a web browser with no security restrictions.

 

Summary


We learned a lot in this chapter about digital content recognition, manipulation, conversion, and creation. Specifically, we prepared a development environment and the tools to work with 2D content and Silverlight 3. We recognized digital art assets from an existing game—the legendary Invaders. We created and prepared digital content for two new 2D games—one raster art based and the other vector graphics based. We understood the different tools involved in a 2D game development process and learned many techniques to manipulate, convert, preview, and scale digital content. We acknowledged the advantages of vector-based graphics as well as its performance trade-offs. We created our first Silverlight application using vector-based XAML graphics, and then developed an XBAP WPF version of the same application. Now, we are able to begin preparing and organizing the digital content for a simple yet impressive 2D game.

Now that we've learned about the principles of development environment preparation and digital content manipulation, we're ready to learn the techniques to work with 2D characters in a 2D game and to manage resolutions and frameworks, which is the topic of the next chapter.

About the Author

  • Gaston C. Hillar

    Gaston C. Hillar is Italian and has been working with computers since he was 8 years old. Gaston has a Bachelor's degree in computer science (graduated with honors) and an MBA. Currently, Gaston is an independent IT consultant and a freelance author who is always looking for new adventures anywhere in the world. He was a senior contributing editor at Dr. Dobb's, and has written more than a hundred articles on software development topics. He has received the prestigious Intel Black Belt Software Developer award eight times. He has written many articles about Java for Oracle Java Magazine. Gaston was also a former Microsoft MVP in technical computing. He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial