Published: 06 Sep 2010
By: Xianzhong Zhu

In this series of articles, you will learn how to integrate the famous 3D Engine - Balder into your Silverlight applications. Since there are few documents, especially tutorials, with Balder, you will first learn the elementary stuffs associated with Balder through small pieces of sample applications. At last, you can accumulate all your strength to develop a real 3D Silverlight game application mainly based the 3D engine Balder, which is named SpaceAdventuring.

Contents [hide]

The Integrate the 3D Engine Balder into Your Silverlight Applications Series

  • Part1 In this series of articles, you will learn how to integrate the famous 3D Engine - Balder into your Silverlight applications.
  • Part2  In this second part of the series, we are going to continue to discuss the Balder engine in the aspect of other advanced concepts and features, i.e. Light, View and Camera.
  • Part 3 In this final part of this series, we are going to learn other advanced concepts support in Balder, such as Sprite, Skybox, HeightMap, the MVVM pattern, and more.
  • Introduction

    In this series of articles, you will learn how to integrate the famous 3D Engine - Balder into your Silverlight applications. Since there are few documents, especially tutorials, with Balder, you will first learn the elementary stuffs associated with Balder through small pieces of sample applications. At last, you can accumulate all your strength to develop a real 3D Silverlight game application mainly based the 3D engine Balder, which is named SpaceAdventuring.

    One more word is to finish our last complete sample game application you'd better also familiarize yourself with another Silverlight open sourced 2D engine - Farseer. To obtain introductory materials about the 2D engine Farseer, you can surf the web to find related documents or refer to my previous article published in dotnetslackers from here.

    NOTE

    The development environments and tools we'll use in these series of articles are:

    1. Windows XP Professional (SP3);

    2. .NET 4.0;

    3. Visual Studio 2010;

    4. Microsoft Silverlight 4 Tools for Visual Studio 2010;

    5. Silverlight 4 Toolkit (http://silverlight.codeplex.com/releases/view/43528);

    6. Farseer Physics Engine 2.1.3 (Download: http://farseerphysics.codeplex.com/releases/view/35490);

    7. Balder (download address: http://balder.codeplex.com/)– a 3D graphics engine, targeting Silverlight, Windows Phone 7, XNA and OpenGL;

    8. (Optional) 3D modeling tools, such as 3DS MAX 2009 (commercial) or Blender (open source project, http://www.blender.org/features-gallery/);

    Why Balder?

    As is well known, Microsoft Windows Presentation Foundation has supplied full support for 3D scene and animation. You can easily find plenty of samples related to WPF 3D applications. In the long term, WPF hopes to be the substitute for traditional Windows GDI applications. However, Siverlight, including the latest version 4.0, has not provided effective support for 3D like WPF. For this, Silverlight MVP Einar Ingebrigtsen launched a great open source project Balder at codeplex, with its ambitious target towards Silverlight, Windows Phone 7, XNA and OpenGL.

    Since 2007, Balder has gone through 4 years with the latest steady release of 0.8.8.8. In this version, fundamental 3D work has been established. So the next step of Balder is possible towards more optimization with the engine itself, as well as expanding into XNA and OpenGL scenarios.

    Starting from the next section, we are going to cover basic support provided by Balder with related examples.

    Integrating Balder into your Silverlight applications

    Then, how can we introduce Balder into our own Silverlight applications? It's easy.

    Install Balder 3D engine and set up a Silverlight project

    In this section, we are going to create a new Silverlight application adding the necessary references to use the Balder 3D engine:

    1. Download the latest release of Balder from http://www.codeplex.com/Balder.

    2. Save all the uncompressed files in a new folder (such as d:\download\ Balder_0_8_8_8, refer to Figure 1 below). Here, I highly recommend you to download all the source code of the Balder engine together with the bin release, so that you can look into the source code to find out more how-tos.

    Figure 1: The bin form of balder 0.8.8.8

    The bin form of balder 0.8.8.8

    3. Create a new C# project using the Silverlight Application template in Visual Studio 2010. Use Balder_tut_Programatic as the project's name.

    4. Select File | Add Reference... and add the following two DLLs from Balder's folder: Balder.dll and Ninject.dll. Note in the latest release of Balder things get vastly simplified. Now, you merely need to deal with the above one assemble, Balder.dll (the NInject component is an component that Balder uses internally, which is in fact an open source dependency injector for .NET), rather than more in earlier versions.

    Up till now, we have downloaded Balder and added the necessary references to use it in a Silverlight project. The previously explained steps are the only ones required to access Balder's components and services in any new Silverlight application.

    By researching into the subfolder \Source\Balder or looking into the infrastructure of the Balder engine using the Object Browser or .NET Reflector, you can see it is composed of plenty of hierarchical 3D concepts related C# classes, such as Node, Scene, Viewport, Display, OmniLight, DirectionalLight, Material, Box, Cylinder, HeightMap, Skybox, etc.

    Another good news is with the help of the newly-introduced Architecture tools in Visual Studio 2010, you can generate your interested assemble related dependency graphs by assemble, namespace or class to gain a more intuitive look at the underlining work. Figure 2 illustrates part of the dependency graph inside the Balder engine.

    Figure 2: Using the Architecture tools in Visual Studio 2010 to visualize the infrastructure of the Balder engine

    Using the Architecture tools in Visual Studio 2010 to visualize the infrastructure of the Balder engine

    With everything getting ready, we are next going to describe the typical two ways of using Balder.

    Using Balder 3D engine in the XAML form

    As you may image, we can use the Balder objects directly in the XAML mode. To use the components, you need to add a namespace declaration referencing the related namespace, which is put at the top of your Silverlight Page or UserControl.

    Add the following attribute in your UserControl start tag:

    1. About the Game control

    In order to get anything rendered you need to add a Game control. The Game control is the one in charge of all the 3D contents, events and game logic. Figure 3 shows the important members defined in this control.

    Figure 3: The class diagram for the Game control

    The class diagram for the Game control

    It is very important that you specify the exact width and height of the Game control, as Balder does not support dynamic resizing at the moment. I.e. you can add the following inside the Grid or other container in your page/UserControl.

    Another point worth noticing is the Game control derives from the Actor control while the latter derives from Silverlight Grid control. Therefore, as you may image, the Game control in some degree occupies the position of the Grid control. And further, you can place common Silverlight controls around the Game control if required (for instance, to indicate info related to the Balder objects).

    2. The first example

    Now, let's take a close look at the whole XAML markups in the first sample (in file Primitive_Box.xaml), as shown in Listing 1.

    Listing 1: Put a 3D box, a Light, and a Camera in the game scene in the XAML markups

    Note inside the Game component, we place a Camera and an OmniLight (one kind of Light supported by Balder). As you may image, without the Camera object you have no eyes to watch things; without the Light object you can only see a black box. As for the details concerning the Light and Camera objects, we'll delve into them later on.

    In the above simple sample, nothing needs be added into the behind file Primitive_Box.xaml.cs. Figure 4 below illustrates one of the running time snapshots of this sample.

    Figure 4: One of the running time snapshots of the first sample

    One of the running time snapshots of the first sample

    Note, in the figure, a light and a camera are all placed at pretty high position, and so you mainly see the top face of the box in the light, and the other faces at the front seems black.

    Using Balder 3D engine in the imperative mode

    Using Balder engine in the programming way is also easy. The general idea is define a custom class derived from the Game control and populate necessary stuffs (such as camera, light, meshes) into it. Then, put a related instance of the class inside Silverlight page/UserControl. That's all. Of course, you can also define parts of the contents in the XAML way while define the rest in the programming mode. Next, let's look at a corresponding example.

    First, define a custom class named CustomGameforBox. Derive it from the Game control and add necessary namespace references.

    Listing 2: The empty custom Game control class (in file CustomGameforBox.cs)

    Next, we switch to the Class View tab to open the class diagram of the class CustomGameforBox in order to add related members. In this case, we right click the class CustomGameforBox and select IntelliSence | Override members to override two methods from the parent Game class – OnInitialize and OnLoadContent. Note another method OnUpdate (from the parent Actor) is usually overridden to achieve animation effects. This is not used in our case.

    Now, inside the related methods put all the stuffs related to the XAMLed one, as shown below.

    Listing 3: The main code for the custom Game control

    After creating the instance of the OmniLight class and specifying the required properties we should call the method AddNode of the Scene property of the Game object to add it into the game scene. However, for the Camera, since it is a public property of the Game object we only need to specify the related sub properties.

    NOTE

    In Balder, we can only set up one Camera in a Game control, but can build lights as many as you need. To achieve the complex several cameras related scene, we can fall back upon several corresponding Game controls (which is supported in the version 0.8.8.8, to be discussed later on).

    Next, right the click your Siverlight project and add a new Silverlight UserControl named UCforCustomGameforBox.xaml. Add the following into it.

    Listing 4: In file UCforCustomGameforBox.xaml

    Now, save up all your newly-created files and press F5 to launch your sample application. And then you will see a same running-time snapshot like before. I believe after a few minutes' pondering, you will grasp all related to the above imperative programming.

    NOTE:

    For simplicity, we change the line this.RootVisual = new MainPage(); in file app.xaml.cs into this.RootVisual = new UCforCustomGameforBox(); to test the above sample. It's the SAME for all the rest small samples.

    In the next section, let me introduce to you a very elementary problem associated with Balder – the coordinate system.

    Left Handed Coordinate System

    In any 3D app development, we should first learn the related kind of coordinate system used in our target framework, as well as other basic concepts, such as Vector, Light, Camera, etc. for balder, things are the same.

    Different from OpenGL and 3DS MAX (both of which are using a right handed coordinate system), Balder is using a left handed coordinate system (same as DirectX), positive X going to the right, positive Z going into the screen and positive Y going upwards. Figure 5 indicates the intuitive comparison between a left handed coordinate system and a right one.

    Figure 5: A left handed coordinate system and a right one

    A left handed coordinate system and a right one

    Balder doesn't provide support for drawing the left handed coordinate system itself. For this, we can create our own sample to illustrate the coordinate system, with a general Box geometry inside it. Next, let's build up a related example.

    First, let's add a new Silverlight UserControl named CoordinateSystem.xaml. Then, insert the following XAML code into it:

    Listing 5: XAML markups for creating a left handed coordinate system in Balder

    As seen above, three simple Geometries, X_Axis, Y_Axis, and Z_Axis, are rendered serving as the x-axis (red), y-axis (green), and z-axis (blue) in the left handed coordinate system.

    For brevity, we are only going to list the definition for the X_Axis class, as shown in Listing 6. As for the other two classes, Y_Axis, and Z_Axis, code is quite similar.

    Listing 6: Definition for the class X_Axis

    As you've seen, by overriding the method Prepare, we finish the drawing of the x-axis. Here, the derived property FullDetailLevel is the MUST HAVE for you to deal with. For details, you can pick up your .NET Reflector to give it a thorough study.

    NOTE

    Although the adept said somewhere at codeplex "...if your boxes are statically positioned during initialization, there will be something called MergedGeometry that allows for merging all your boxes into one larger geometry and still allow for identifying each individual element plus be able to change Color and such as well.", I for now found I could not create a custom compound geometry derived from the MergedGeometry class. Was there anything wrong? Interested readers can refer to the commented code in file MyCoordinateSystem.cs. Welcome any suggestions.

    Figure 6 below gives the related running-time snapshot.

    Figure 6: Draw our own left handed coordinate system

    Draw our own left handed coordinate system

    Next, let's delve into the basic geometry support in Balder.

    Basic Geometries Support

    Up till now, Balder only provides the following basic support for geometries:

    • Box - simple box with dimensions. You can find many samples in the source code.
    • Cylinder, you can find a related sample in the source code file Primitive_Cylinder.xaml.
    • Ring, you can find a related sample in the online samples.
    • ChamferBox - simple box with a chamfer segment. You can find a related sample in the source code file Primitive_ChamferBox.xaml.
    • HeightMap - a plane that consist of a set of vertices (points) that can be manipulated by its height.
    • ArbitraryHeightMap - a derivative of HeightMap, but its plane is arbitrary.
    • Mesh - a complex mesh which can be loaded from a file.

    Basic Geometries

    As is enumerated just before, Balder offers the basic ready-to-made geometries support, such as 2D objects –currently only two, SkyBox and Sprite, and 3D objects – Box, ChamferBox, Cylinder, HeightMap, Ring, Mesh, and other trivial 3D components.

    As for the SkyBox, Sprite, and HeightMap, we are going to discuss them in the second article of this series. Here, we mainly show interest in the Mesh.

    Mesh

    For handling 3D geometries that are loaded from a file, there is a control called Mesh, located in the Balder.Objects.Geometries namespace. The control is a Node and has all the properties of a node, such as positioning, color and more. For specifying what 3D model to load, it has a property called AssetName. The AssetName can be specified in two ways, either as a relative path to the path defined in the ContentManager, which is by default pointing to a subfolder in your Silverlight project called Assets. You can in addition specify in detail where your asset is located, and the Silverlight implementation of the file loading mechanism will load the asset correctly. The format of the specific path is: "/Package name;component/asset name".

    Currently, the Mesh file format is only towards .ase file (text format). For example, you can export your 3DS MAX model info from a .max file into an .ase file. Note the .ase file merely contains the model info as well as the material info while removes the light and camera related info. Therefore, to introduce the .ase file into a Silverlight application, we should set up our own light and camera objects according to the known geometry info (mainly the size, length, width, and height, and other possible complex info).

    NOTE

    1. It's said by the author that the Balder engine supports 90% of the Autodesk Ascii Scene Export format for 3D objects.

    2. All assets must be marked as "Resource" in the "Build Action" property of the file in your project.

    Let's next take a look at a simple sample to deal with an .ase file.

    1. Right click the Silverlight project and add a new Silverlight User Control named Primitive_teapot.xaml.

    Modify the .xaml file like the following:

    To make a comparison, we've also placed a Box object around the teapot. As mentioned previously, you can also reference the mesh with a default path like the following:

    Under this case, the Balder system will automatically retrieve a subfolder in your Silverlight project called Assets, where your .ase file is placed. Other details concerning Mesh need no more iteration.

    Figure 7: Render the Mesh teapot and Box into the scene

    Render the Mesh teapot and Box into the scene

    Till now, although we've used material somewhere in the previous samples we have not normally discusses this concept. Let's next look into the plentiful material support provided in the Balder engine.

    Material Support

    As far as 3D modeling is concerned, Material is another basic related concept. As you may image, Balder engine also provides the basic material support, with the key features listed below:

    • Diffuse color
    • Ambient color
    • Specular color
    • Diffuse map
    • Reflection map
    • Opacity for the different maps can be specified

    Here, we are not going to introduce the basic material related concepts one after another, since you are supposed to have become familiar with some 3D modeling tools.

    First, please note, for now, Balder mainly supports PNG and JPEG imaging. And, as a common 3D common sense, for textures, you must use images with dimensions being power of 2 (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 and so on), which is decided by the behind related complex mapping algorithms. As a common developer, you just need to obey the rule.

    Moreover, around the above-listed basic concepts, there are still many small trivial concepts. For all of these concepts, interested readers can delve into the sample illustrated below.

    A simplified material editor

    To gain a quick impression upon how materials affect the 3D models and all related concepts, let's see a sample adapted and simplified from the online Balder tutorials. Figure 8 shows one of the related running-time snapshots.

    Figure 8: A simplified material editor supported by Balder engine

    A simplified material editor supported by Balder engine

    From the figure above, you can get yourself familiarized with the good many material related concepts. Although simplified, the material editor sample is a pretty complex one. To grasp all aspects inside it, you need to be fully acquainted with AOP (aspect-oriented programming) and the MVVM pattern. However, due to space limit, we don't plan to detail into how the sample is constructed; you can refer to the source code yourselves.

    Now, let's look at the direct material related XAML code, as shown in Listing 8.

    Listing 7: Define material to decorate the mesh

    As is seen, here Balder uses the compound property element syntax to specify each property (Ambient, Diffuse, Specular, and Shade) of the material that will be assigned to the box geometry. That's it.

    As for the above-mentioned .ase file related materials, there is mainly one point deserved to be pointed out.

    In order to envelope 3D models using textures, you must bear in mind to export the model from your favorite 3D tool including the references to the images used as textures. Then, you will be able to replace the image used as a texture with another one in your Silverlight applications.

    Using the mapped .ase 3D models in Silverlight

    In this section, I will give you more detailed instructions concerning things covered a moment ago. Let's take 3DS MAX 2009 for example.

    1. Start 3DS MAX 2009. Create a simple sphere, and then use the material editor to specify the file cloudless.png as the diffuse map of the sphere, as shown in Figure 9.

    Figure 9: A simple sphere (earth.max) with a specified map in 3DS MAX 2009

    A simple sphere (earth.max) with a specified map in 3DS MAX 2009

    2. Click File | Export to export the above file earth.max to the text formatted file earth.ase.

    3. Add the file earth.ase to the sub folder Assets (the recommended place) under your Silverlight project. Do remember to mark it as "Resource" in the "Build Action" property of the file.

    4. This is the most important step. In short, we have to ensure the .ase file matches the corresponding independent map file, with appropriate path specified. To achieve this, we have to manually manipulate the file.

    5. Open the code for the recently added ASE file (earth.ase) using Notepad.exe (or any other text file editor you prefer to).

    6. Search the line that begins with *BITMAP, like the bold part in the following:

    Listing 8: Our interested part of the text file .ase (note the bold lines)

    7. Replace the full path and the filename that follows the *BITMAP(D:\2008-2009________\______\2010__\src\Balder_tut_Programatic\Balder_tut_Programatic\Assets\cloudless.png) with your desired PNG bitmap(or .jpg file). In our case, we change the above into the following:

    At last, save the modified file earth.ase.

    NOTE

    We omitted the absolute path after the *BITMAP in the above code, while in fact we used the default and recommended sub path "assets".

    8. Now, take a look at the related XMAL code (see file Sphere_material_Test.xaml) in action.

    Till now, I believe, no more explanations need to be given. Figure 10 shows one of the related running-time snapshots.

    Figure 10: A mapped mesh in action

    A mapped mesh in action

    Summary

    In this installment, I've introduced to you the very elementary concepts in relation to the Balder engine in Silverlight applications through piles of small samples (you can find others in the source code). In the next article, we will shift to discuss more advanced concepts and features in the Balder engine, such as Sprite, Skybox, HeightMap, Light, View and Camera, the MVVM pattern, etc.

    The Integrate the 3D Engine Balder into Your Silverlight Applications Series

  • Part1 In this series of articles, you will learn how to integrate the famous 3D Engine - Balder into your Silverlight applications.
  • Part2  In this second part of the series, we are going to continue to discuss the Balder engine in the aspect of other advanced concepts and features, i.e. Light, View and Camera.
  • Part 3 In this final part of this series, we are going to learn other advanced concepts support in Balder, such as Sprite, Skybox, HeightMap, the MVVM pattern, and more.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.

    You might also be interested in the following related blog posts


    Visual Studio Add-In vs. Integration Package Part 3 read more
    Why Embedded Silverlight Makes Sense read more
    Telerik Announces Support for Microsoft Silverlight 3 read more
    What is .NET RIA Services? read more
    Moonlight 1.0 Released, Silverlight script updated – and a Chrome hack read more
    Rendering A Single View Using Multiple ViewEngines read more
    URL Rewrite for IIS - SEO Friendly URLs love it ! read more
    Some Silverlight ecosystem updates read more
    Search for Rich Internet Applications read more
    The Social API we really need. read more
    Top
     
     
     

    Please login to rate or to leave a comment.