Collections Part 1

Contents

1. Introduction

Just like C++, C# has different types of collections you can use to manage data. In this knol, we’ll discuss arrays and the containers from the System.Collections namespace.
 
Note that the containers of the System.Collections namespace are not recommended. The reason is that they cause a lot of boxing and unboxing. You should use generic collections from the System.Collections.Generic namespace (like List<T>), which I will explain in part 2.
 

2. Array

2.1 General

Unlike C++, where an array is just a pointer to the first item in that array, in C# an array is an object of type System.Array. This means an array is a real class with properties and methods, which makes handling arrays a lot easier in C# than C++. You also can’t go beyond the memory allocation of the array. If you try to access an element outside of the bounds of the array, you will get an IndexOutOfRange exception.
 
Just like C++, an array is a sequence of elements, and all elements must be of the same type. The elements also live in a continuous block of memory.
 
Declaring an array is similar to the way you do it in C++, except the fact that you put the square brackets after the type, not the variable name.

int[] arr = new int [5];

The code above creates an array of integers, that reserves memory for 5 elements.  You always have to call new in order to create a new array. The size of the array can be determined at runtime. The code below is completely valid (assuming you enter the correct input in the console).

int[] arr = new int[int.Parse(Console.ReadLine())];

When you create an array instance, all elements are initialized to their default value (depending on their type). You can also initialize the elements to a specific value, by specifying them between curly braces.

int[] arr = new int [5] {1,2,3,4,5};

Or even shorter:

int[] arr = {1,2,3,4,5};

2.2 Iterating an array

An array has a property Length, which tells you how many items the array contains. This property makes iterating an array very easy.

for (int i = 0; i < arr.Length; ++i)
     Console.WriteLine(i.ToString());

You can also use the foreach statement to iterate through an array, and all collections as a matter of a fact. This is because they implement the IEnumerable interface. In future knols, you will learn more of IEnumerable, but for now it’s enough if you know that implementing the interface enables you to loop through a collection using a foreach statement.

foreach(int i in arr)
     Console.WriteLine(i.ToString());

Foreach always iterates though all the items of the collection, from the first to the last element. If you want to iterate backwards, or skip certain items, you must use the ‘for’ statement.
 

2.3 Copying arrays

2.3.1 Shallow and deep copy

First of all, it’s necessary that you know the difference between shallow and deep copy. If the elements that your array contains are reference types, a shallow copy will copy the references, but not the objects to which they point. So after the copy operation both the original and the copy point to the same objects. A deep copy will clone the objects themselves, so the original and the copy don’t point to the same objects.
 
All copy methods you will see below perform shallow copying. If you want to create a deep copy, you’ll need to write the code yourself.
 

2.3.2 Copy

The System.Array class has a static method Copy. You can use this method to create a shallow copy of an array. It takes the original array, the destination array and the length as arguments.

int[] original = new int[10] { 1, 2, 3, 4, 5 };
int[] copy = new int[5];

Array.Copy(original, copy, 5);

2.3.3 CopyTo

Another way to copy an array is to use the CopyTo method. It takes to destination array and a starting index as arguments.

int[] original = new int[5] { 1, 2, 3, 4, 5 };
int[] copy = new int[5];

original.CopyTo(copy, 0);

2.3.4 Clone

An array also has a Clone method, which creates a shallow copy of the array and returns the copy. The Clone method creates the object for you; you do have to cast the return value to the appropriate type.

int[] original = new int[5] { 1, 2, 3, 4, 5 };
int[] copy = (int[]) original.Clone();

3. Collections

Unlike C++, it is safe to use arrays in C#. However they do have certain limitations. In the System.Collections namespace, several collections that will make your life easier are provided. All collections implement the IEnumerable interface, so you can make use of the foreach statement. Most collections from the System.Collection namespace use object as type for their elements. So object[] instead of int[] for example. The System.Collections.Generics namespace offers a solution for that. This will be discussed in the 2ndcollections knoll.
 

3.1 ArrayList

An arraylist is a collection that doesn’t have a fixed number of elements like an array does. It’s also very useful when you want to add, insert and remove a lot of elements at runtime.
 
When you use an array and you want to resize it, you have to create a new one, copy the elements, update references, … Removing items from the array means you’ll have to move all trailing elements, … The arraylist does all this for you. You use an ArrayList as is shown below:

// Create a new arraylist
ArrayList myAL = new ArrayList();
myAL.Add(“Hello”);
myAL.Add(“!”); 

// Insert World between Hello and !
myAL.Insert(1, “World”); 

// Add two items to the end of the arraylist
myAL.Add(“test”);
myAL.Add(“test2″); 

// Remove the items that have “test” as value
myAL.Remove(“test”); 

// Remove the item at index 3
myAL.RemoveAt(3); 

// Displays the properties and values of the ArrayList.
Console.WriteLine(“myAL”);
Console.WriteLine(“    Count:    {0}”, myAL.Count);
Console.WriteLine(“    Capacity: {0}”, myAL.Capacity);
Console.Write(“    Values:”); 

// Write all objects to console. Note the object keyword!
foreach (Object obj in myAL)
     Console.Write(“   {0}”, obj); 

Console.WriteLine();

3.2 BitArray

The BitArray container is a compact array of bit values that represent booleans. 1 indicates that the bit is on (true), 0 that the bit is off (false).
 

3.3 Hashtable

An arraylist for example, makes it easy to map an integer (index) to a certain value. But sometimes we want the key (the index) to be something different than an integer.  A hashtable has two arrays internally, one for the keys, and one for the objects. A hashtable is very similar to the C++ map.
 
There are some things one should be aware of however:
  1. A hashtable cannot contain duplicate keys.
  2. A hashtable can contain duplicate values.
  3. When using the foreach statement on a hashtable, you get back objects of type DictionaryEntry.

Hashtable openWith = new Hashtable(); 

// Add some elements to the hash table. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add(“txt”“notepad.exe”);
openWith.Add(“bmp”“paint.exe”);
openWith.Add(“dib”“paint.exe”);
openWith.Add(“rtf”“wordpad.exe”); 

// The Add method throws an exception if the new key is
// already in the hash table.
try
{
     openWith.Add(“txt”“winword.exe”);
}
catch
{
     Console.WriteLine(“An element with Key = \”txt\” already exists.”);
}

foreach (DictionaryEntry entry in openWith)
     Console.Write(“   {0}, {1}”, entry.Key, entry.Value);

Console.WriteLine();

3.4 Queue

The queue in C# is very similar to the C++ queue. It’s a collection that implements the first-in, first-out (FIFO) principle. Items that are queued are inserted at the back, and removed from the front.
 
Usage is very straightforward:

Queue myQ = new Queue();
myQ.Enqueue(“Hello”);
myQ.Enqueue(“World”);
myQ.Enqueue(“!”); 

// Displays the properties and values of the Queue.
Console.WriteLine(“myQ”);
Console.WriteLine(“\tCount:    {0}”, myQ.Count);
Console.Write(“\tValues:”); 

// Write all items to the console
foreach (Object obj in myQ)
     Console.Write(“   {0}”, obj); 

// dequeue the first item (Hello)
string hello = (string) myQ.Dequeue();
Console.WriteLine();

3.5 SortedList

A sorted list is very similar to a hashtable, except that the values are sorted by key. The usage and restrictions of the sorted list are similar to the hashtable.

// The items will be sorted by key
SortedList mySL = new SortedList();
mySL.Add(“First”“Hello”);
mySL.Add(“Third”“!”);
mySL.Add(“Second”“World”); 

// Displays the properties and values of the SortedList.
Console.WriteLine(“mySL”);
Console.WriteLine(“  Count:    {0}”, mySL.Count);
Console.WriteLine(“  Capacity: {0}”, mySL.Capacity);
Console.WriteLine(“  Values:”); 

foreach (DictionaryEntry entry in mySL)
     Console.Write(“   {0}, {1}”, entry.Key, entry.Value);

Console.WriteLine();

3.6 Stack

The stack in C# is also very similar to the C++ stack. It’s a collection that implements the last-in, first-out (LIFO) principle. An element is added (push) to the top of the stack, and removed (pop) from the top as well.

Stack myStack = new Stack();
myStack.Push(“Hello”);
myStack.Push(“World”);
myStack.Push(“!”); 

// Displays the properties and values of the Stack.
Console.WriteLine(“myStack”);
Console.WriteLine(“\tCount:    {0}”, myStack.Count);
Console.Write(“\tValues:”); 

foreach (Object obj in myStack)
     Console.Write(“   {0}”, obj); 

// Pop the first item (!)
string exlamationmark = (string)myStack.Pop(); 

Console.WriteLine();

Value types and reference types

Contents

Introduction

When programming in C#, it is of utter importance that you understand the differences between value types and reference types, because using them has consequences that will become apparent after reading this document.

Value Types

Types such as int, float, double, char, structs, … are value types. This means that when you declare a variable of such a type, the compiler will allocate a block of memory that is large enough to contain the corresponding value. For example, the compiler will allocate 4 bytes of memory when you declare a variable of type int. When assigning a value to this variable (example 1), the block of memory will be copied.
Example 1:
Declare a variable of type integer (i) and initialize it to 1. Then declare a second variable of type integer (y), and assign it to the value of i. Executing i++ doesn’t affect y, because a copy is made.

int i = 1; // Declare and initialize i

int y = i; // Make a copy

i++; // Increment i, y doesn’t change

Value Types
 
It is often stated that value types reside on the stack and reference types reside on the heap. This is incorrect. Value types are types which reside in their own memory, and don’t have a pointer to them. The type of an object doesn’t really have anything to do with the place where it’s stored; it’s the lifetime that matters. More info about this confusion can be found in the article “The truth about value types”.
In C#, almost all primitives are value types, with string as an exception. All structs are also value types. This has some consequences.
An example: a form has a property Location that you can use to set the location of your form. This property is a struct. When I access the location of the form, I get back a copy. This means you can’t change the location like follows:

this.Location.X = 3;

This code will result in a compiler error, although it looks like reasonable code. Let us write the code above in C++:

this->getLocation().setX(3);

Obviously this doesn’t have the intented effect: getLocation returns a local copy of the location, and setX would change this local copy, having no effect on the instance itself.

You have to use the following workaround:

Point loc = this.Location;
loc.X = 3;
this.Location = loc;

Reference Types

When declaring an object that is a reference type, the compiler takes different actions than with value types. The compiler won’t allocate a block of memory that is large enough to contain your object. Instead it will allocate a small block of memory that can contain a reference (managed pointer) to your object. It is often said that references go on the stack because they themselves are value types. This is incorrect. References aren’t value types, they’re just values (they have no type in the c# type system). The reference does point to your object, which resides on the heap. So reference types have references to blocks of memory on the heap.
Objects of type string are also reference types, as the keyword string is just an alias for the class System.String.
Example:
Declare a variable of type Button (button1). This variable can point to a Button object. Declare a second variable of type Button (button2). When I assign the value of button1 to button2, both references point to the same object. There is only 1 Button object, but there are two references. When changing button2, button1 also changes.

// Declare and initialize a new Button
Button button1 = new Button();  

// Declare a variable of type Button and let it point to button1
Button button2 = button1; 

// button2 also changes the text of button1, because
// only 1 object exists
button2.Text = (“I also change button1″); 

Reference Types
 
One consequence of reference types is that you can changes these from within a method. An example: when I pass button1 as argument to a function, this function can change the object. With value types, you would just pass a copy.

private void ReferenceDemo(Button btn)
{
        // I change the original Button here
        btn.Text = “changed”;
}

Note that in C#, there is no way to pass the button object as a const argument.

 

Ref and Out parameters

General

When passing an argument to a method or function, a copy is passed by default. This is true for value types and reference types. It is however so that with reference types, a copy of the reference is passed, and the object to whom it refers stays the same. This has as a consequence that you can’t change the value of the parameter passed.
Example:

private void ReferenceDemo(Button btn)
{
        // I change the original Button here
        btn.Text = “changed”;


    
// The original reference isn’t changed
        btn = null;
}

In the method above, it is possible to change the text of the button, but making the reference point to null has no impact on the original object, only on the copy of the reference which has been passed to the method ReferenceDemo.
On the other hand, when I pass a variable of type int as parameter to a method, I can’t change the value of the original int. In C++, you would pass an int-reference (not to be mistaken with a C# reference) to solve this.
In C#, there are 2 ways to get the results we want, via the keywords ref and out.

Ref

When you place the ref keyword before the type of an argument, the parameter becomes an alias to the argument, and not a copy. So by using the ref keyword, you can change the original object.
Example 1: int

private void RefDemo(ref int i)
{
        // I change the original object here
        i = 3;
}

Example 2: Button

private void ReferenceDemo(ref Button btn)
{
        // I change the original object here
        btn.Text = “changed”;

      // The original reference is changed
        btn = null;
}

To call a method which has a ref parameter as argument, you also need to add the ref keyword during the method call:

int i = 10;

RefDemo(ref i);

Button btn = new Button();

ReferenceDemo(ref btn);

One thing you have to be aware of when using the ref keyword is that the variable has to be initialized in order to pass it as an argument to a method. The code below will result in a compile error.

Button btn;

ReferenceDemo(ref btn);

In some cases, this could be a problem. Sometimes you want the method itself to initialize the variable. For example, in this case, I could want that the method ReferenceDemo has a bool as return value, that informs me if everything went right (the C++ way :-)  ), and as argument an object of type Button that is initialized in the method ReferenceDemo. This behavior can be obtained by making usage of the out keyword.

Out

The out keyword is very similar to the ref keyword. Prefixing an argument with the out keyword passes an alias to the argument, and not a copy. The only difference is that when making use of the out keyword, the method itself must assign a value to the object. The code below will result in a compile error.
private void ReferenceDemo(out int i)
{          

}

The code below will work:

int i;

ReferenceDemo(out i);

private void ReferenceDemo(out int i)
{
        i = 42;
}

Nullable Types

General

The keyword null is very handy when using reference types, because then you can see if the object is initialized. With value types, it is not possible to use the null keyword. The code below will result in a compile error.
int i = null;
This is because null itself is a reference type. But there is a way to assign null to a value type, by using the ‘?’ operand. An example will clarify things.
int? i = null;

 

The code above works, but what happens? The C# compiler will make an object of type Nullable. Nullable is a generic structure that internally looks like this:
public struct Nullable where T : struct
{

        public Nullable(T value);

        public static explicit operator T(T? value);

        public static implicit operator T?(T value);

        public bool HasValue { get; }

        public T Value { get; }

        public override bool Equals(object other);

        public override int GetHashCode();

        public T GetValueOrDefault();

        public T GetValueOrDefault(T defaultValue);

        public override string ToString();
}

The rule int? i creates an object of type Nullable with as generic parameter an integer. Take into account that this object is still a value type (Nullable is a struct). Note that the Nullable class has a property HasValue; because it is possible to assign null to the variable, there has to be a way to see if the object has a value.
Also note that when you want to pass a nullable type as argument to a method, this also has to be a nullable type.

int? i = null;

NullableDemo(i);

private void NullableDemo(int? i)
{
        if(i.HasValue)
           int valueOfi = i.Value;
}

The code above can also be written as follows:

private void NullableDemo(int? i)
{
        if(i != null)
           int valueOfi = (int) i;
}

An introduction to C# and the .NET framework

1. Introduction

C# is an object oriented programming language built on top of the .NET framework. C# Is a higher level language that enables you to write code fast. Compared to C++, there are some differences one should be aware of. These differences will be handled in this article. This article will not offer you in depth knowledge about C# and the .NET framework, but rather glance at the differences. You will gain in depth knowledge in future articles. At the moment of writing, we’re at C# version 4.

2. .NET framework

2.1 General

The .NET framework is built by Microsoft. It offers seamless collaboration between libraries written in different programming languages. .NET is a managed framework, meaning certain things are handled for you, such as garbage collection. .NET programs aren’t, unlike C++, compiled to machine code, but rather to an intermediate language, called CIL (Common Intermediate Language). This CIL code is then translated to machine code at run time by the CLR (Common Language Runtime), by making usage of JIT (Just In Time) compilation.
There are several programming languages you can use to develop on the .NET framework, such as C#, VB.NET, C++/CLI, Boo, … All these languages are compiled to the same CIL. Because all programs are compiled to an intermediate language, it’s also fairly easy to decompile it again (to the same, or another programming language). If you want to decompile .NET code, take a look at Reflector.NET.

2.2 History

2002: .NET framework 1.0 + Visual Studio 2002
2003: .NET framework 1.1 + Visual Studio 2003
2005: .NET framework 2.0 + Visual Studio 2005
2006: .NET framework 3.0
2007: .NET framework 3.5 + Visual Studio 2008
2010: .NET framework 4.0 + Visual Studio 2010

2.3 Advantages and Disadvantages

Development using the .NET framework has its advantages and disadvantages when comparing to development in C++. Let us start with the advantages. First of all, you can develop a lot faster when compared to C++. One might say that you produce code at about 5 times the speed than you would in C++. Second of all, it’s a lot easier an more accessible than C++. And you have a garbage collection system which offers automatic deallocation, eliminating almost all memory leaks. It’s also cross platform, meaning your code will work on several versions of Windows, and if you use the compact framework, your code will work on mobile devices, Xbox 360 and Windows Phone. With the help Mono, your code will even run on Linux (Note: not all .NET features are supported on Mono). The Unity3D gamdev IDE is built on top of Mono.

Development using the .NET code also has some disadvantages. First of all, because your code is compiled to an intermediate language, it’s a lot easier to decompile code than it would be with C++ code. Luckily several obfuscating techniques exist that make this process more difficult. The garbage collector (“GC”) can also be a disadvantage. One has to have a good understanding about what it does to make sure it doesn’t become a bottleneck. The GC on the Windows is fairly advanced,  but the one on the compact framework isn’t as effective. When building games in XNA for Xbox 360 and Phone 7 Series, the GC will be something you will have to pay attention to. Then the final thing is that .NET code can run slower than C++. But let us be honest, isn’t this the same discussion that we have when moving from Assembler to C? Or from C to C++? Also, bear into mind that it’s fairly easy to write slow C++ code if you don’t know what you’re doing; doing so in .NET is a bit harder since the framework manages a lot for you.

3. The C# programming language

3.1 Introduction

C# (pronounced C Sharp) is an object oriented programming language developed by Microsoft. It is accepted as a standard by the ECMA (ECMA-334) and ISO (ISO/IEC 23270). C# has an object oriented, procedural syntax and is based upon the C++ syntax. It also has some Java elements, and even some functional and dynamic programming language influences. At the moment of writing, C# is at version 4.0. The Microsoft compiler for C# 4.0 was released in 2010, but the language specification dates from 2006.
Now let us start with mentioning some differences between C# and C++.

3.2 Everything is an Object

In C#, and the .NET framework, everything inherits from System.Object. This leads to the fact that in C#, you could write the following code:

            (7).ToString();
            “THIS IS A STRING”.CompareTo(“SECOND STRING”);

This means you can also cast everything to System.Object, since they’re all derived from that base class.

3.3 Headers

C# doesn’t use header files. Because .NET is compiled to an intermediate language, there is no need for header files, since the DLLs it compiles to (called “assemblies”) contain all information about the classes and methods in it.

Take a look at the class below:

    public class Hero
   {
        // FIELD (called data member in C++)
        private string _nemesis;
        // CONSTRUCTOR
        public Hero()
        {

        }

        // NO DESTRUCTOR IS NEEDED!!!
        // METHOD (called member function in C++)
        public void SaveTheWorld()
        { 
        }
        private void AskForHelp()
        { 
        }
    }
The class itself has the ‘public’ access specifier. Each method has its own access specifier as well. So do the fields.
Note that classes in C# don’t have destructors, since they are collected automatically by the GC (you do have finalizers, but these are only used when you inter-operate with native APIs like DirectX)

3.4 Pointers

C# has pointers (in unsafe mode), but you’ll almost never use them. C# has two different kinds of types: value types (structs and enums), that hold the data in its own memory allocation and reference types (classes and arrays), that store a reference to the data. Unlike C++, it is the definition of type itself that determines if the data is passed by copy or by reference.  This reference is not to be confused with C++ references. References in C# can be compared with a sort of managed pointer, without the overloaded pointer operations. This also means you shall almost never use the -> operand. You can always access type members by using the “.” operand. For example, if I would want to call the method SaveTheWorld on a Hero object, I would just write the following code:

// Create a new instance of the Hero class, 
// and store a reference to it in the hero local variable
Hero hero = new Hero(); 
// Call the method SaveTheWorld.
hero.SaveTheWorld(); 
In C++, this would look like:
Hero* hero = new Hero(); 
hero->SaveTheWorld(); 

3.5 Properties

C# has a special syntax for writing getters and setters, called properties. When you would want to expose a member called Nemesis, in C++, you would write the following code:
class Hero
{
public:
  const char* getNemesis() {return m_Nemesis;}
  void setNemesis(const char* nemesis) {m_Nemesis = nemesis;}
private:
const char* m_Nemesis;
};
If you want to set the name of the hero, you need to call hero->setName(“Name”).
In C#, you would write the code as follows:
public class Hero
{
   private string _nemesis;

   public string Nemesis
   {
    get return _nemesis; }

    set { _nemesis  = value; }
   }

}

The C# compiler will then generate getters and setters methods for you. If you would like to set the name of the hero, you would have to write the following code:
        hero.Nemesis = “nemesis”;

If you would like to get the name of the nemesis, you would have to write the following code:

        string nemesis = hero.Nemesis;

If the property call is on the left of the assignment operator, then the setter is called; if it is on the right side, the getter is called.

3.6 Interfaces

An interface contains the signatures of methods, delegates, events, but has no implementation. You can compare an interface with an abstract class that only contains pure virtual methods.
    public interface IHero
    {
        void SaveTheWorld();
    }

    public class Hero IHero
    {
        public void SaveTheWorld()
        {
            // IMPLEMENTATION
        }
    }
An interface could be seen as a blueprint of what methods a class should contain. An interface can inherit from one or more base interfaces.

3.7 Inheritance

In C#, inheritance is different than in C++. First of all, the distinction between structs and classes has to be made. Structs (value types) do not support inheritance, classes (reference types) do. C# doesn’t have multiple inheritance where one class can be derived from several other classes. You can only derive from one base class. You can implement multiple interfaces though.
So our class Hero could inherit from a base class person, and still implement the IHero interface.

3.8 Arrays

An array in C# is an object of type Array (a reference type). An Array is a class (unlike C++, where an array is just a pointer to the first element of the array). An array in C# has methods and properties, such as the property Length. Another difference is that the square brackets ([]) follow the type and not the variable.
In C#, a variety of higher level collection classes exists, such as ListDictionary (these are similar to C++ std::vector, std:map, …)

3.9 Strings

A C# string object is an instance of the System.String class. In C++, strings are an array of characters, and always a hassle to work with. In C#, a string is an immutable object, meaning you cannot change the string object itself.  You can however combine strings into new strings (for example concatenating two strings using the + operator).

3.10 Casting

C# has support for c-style casts, just like C++, but it doesn’t have static_cast support. All casts in C# are like C++ dynamic_cast, but they will throw an exception if the object is not of the correct type.

object obj = …
Hero hero = (Hero)obj;

You can also use the ‘as’ keyword, which returns null it the cast fails. This is similar to the dynamic_cast in C++.
Hero hero = obj as Hero;

HLSL Shaders

Koen Samyn, lecturer interactive programming at the University College of West Flanders (curriculum Digital Arts and Entertainment) wrote an excellent KNOL (a unit of knowledge) on HLSL Shaders. You can find the article here:
http://knol.google.com/k/samyn-koen/-/2lijysgth48w1/2#

Extract:

What is a shader ?
A shader ( or effect) is a program that is executed on the GPU (Graphical Processing Unit). The GPU is located on the graphics card off course and the GPU contains many cores that can execute a shader program concurrently. This allows the GPU to have high throughput (number of triangles that can be processed per second).

If for example a GPU has 4 available cores (run of the mill GPU have much more then that) each code transform the vertices of 4 triangles simultaneously. There are several shader API’s and languages that are targeted to curent GPU’s : …

XNA 3.0 Beta Released

Microsoft has released a Beta for XNA 3.0. This new update features many improvements and new features for Zune, XBox 360 and PC.

Zune

* Compatibility with the upcoming Zune 3.0 Firmware release. Please note that the XNA Game Studio 3.0 CTP will no longer work once you have upgraded your Zune device to the 3.0 firmware.
* Improved deployment stability.
* Support for Zune deployment on Windows Vista x64 Systems!
* You can now use the Remote Performance Monitor for Zune games.

Xbox 360

* Xbox 360 project templates (You will not be able to develop on the Xbox 360 until our final release. We felt this was important to include so that you could get projects converted over and look at the system, even if you are not able to run the games, yet).
* Support for the Big Button Pad.

Framework & Visual Studio Features

* Enumerate and play back media on your Windows computer or Xbox 360.
* Simple sound effect support on Windows computers and Xbox 360.
* Support for Rich Presence (lets friends know what’s going on in your game).
* Support for Invites (ask your friends to join you in a multiplayer game) and Join Session In Progress (after you see what your friends are doing, you can join their current session with just a couple of button presses, even if that’s a different game to the one you are currently playing)
* Compress your content and save space with the new content compression features!
* ClickOnce packaging support for distributing your XNA Framework games on Windows.
* Upgrade your project from XNA Game Studio 2.0 using the Project Upgrade Wizard!
* Take screen captures of your game running on Zune through the XNA Game Studio Device Center.
* Support for .NET language features like Linq
* Create multiple content projects and leverage cross project synchronization in Visual Studio.
* FBX importer improvements: read materials containing multiple textures, and export custom shader materials directly out of Max or Maya.

Earn Money from your Xbox LIVE Community Games

Today Microsoft announced the pricing plan for your XNA Community Games on Xbox LIVE. This payment plan is fairly flexible allowing you to charget between 2.50 and 10.00 dollars for your game on Xbox LIVE. Microsoft will let you keep 70 percent of the profit and may even advertise the game for you if it is very successful.

Read More on the XNA Team Blog

Xbox Live Community Games

Source: ziggyware

XNA games coming to the Zune, Xbox Live Arcade

This morning at the Game Developers Conference in San Francisco, Microsoft announced the next step in its Xbox Live and XNA initiative: the Zune will become the third pillar supporting XNA software, with over 1,000 games ready for the device by year end. XNA software developed for the Xbox Live Arcade is now going to be opened to the public.

Microsoft showed off an XNA game running on a Zune during a keynote speech presented by vice president John Schappert. A top-scrolling space shooter was shown running on a PC, an Xbox 360, and, lastly, a Zune. In addition, Zune games will be multiplayer: users will be able to play against each other online. Games for the platform will be arriving this year alongside the launch of Xbox Live Community Games.

The new XNA-oriented service, Xbox Live Community Games, allows select user-created software to be distributed through Xbox Live, effectively opening user-created games to the masses. Titles will be selected through a democratized game distribution system pulling on the Creator’s Club user base. Members will be able to screen and vote on games, with those reaching a certain level of approval cleared and released to the public. A handful of these games are now available as trials on the Xbox Live Marketplace.

Creator’s Club members are paying subscribers who have access to the XNA development platform. Much like the gamercard, a “creator card” will show what games specific creators have built. XNA is a suite of development software which Microsoft introduced in 2006. The suite allows developers to create projects that can easily be translated between the support platforms. Previously only the PC and the Xbox 360 were supported, but the Zune represents Microsoft’s first significant step into the mobile gaming market.

excerpt from http://arstechnica.com/news.ars/post/20080220-xna-games-coming-to-the-zune-xbox-live-arcade.html

A preview release of XNA Game Studio 3.0 will be available in the Spring 2008 timeframe, with a final release scheduled for the holiday 2008 season.

Zune

XNA_BUG : February 2008 XNA Contest

The XNA Belgian User Group organizes the February 2008 XNA Contest

This contest is open for developers and designers, working on XNA Games. The development and demo can be done on a PC platform or XBOX 360.
The participants can form teams of 2 people working together. Participants have to be 16 years old at the days of the finals, but not older than 36 years (born between February 23, 1972 and February 23, 1992) AND live in Belgium.

The contest is based on a ‘starter kit’, consisting of a ‘nearly finished’ game, build on top of XNA. The purpose of the contest is to extend this starter kit in the best and most creative way. The starter kit will be made available from February 1 on http://www.xnabug.net/starterkits.htm
Submissions will be judged on creativity, innovation and ‘playability’ of the demo.

To judge the submissions, participating teams need to:
- Enroll for the contest by mailing an enrollment form to [BRECHT at XNABUG dot NET]. The enrollment form is available here. The enrollment form has to be received by February 18 midnight.

- Prepare 2 ‘posters’ explaining the submission. The posters have to be printed on A3 paper size. These posters will be used during round one on during the finals, February 23. Based on the posters and questions and answers, the jury will select the teams which will present and demo their submission.

- Prepare a presentation/demo of 10 minutes and 5 minutes of questions and answers. This demo and presentation will be done February 23 in front of the jury and the audience. It will be executed on the equipment of the participating team. The facility to project on a large screen will be provided by the organization.

Judging criteria:
The submissions, posters and presentations/demo’s will be judged by a multidisciplinary team of gaming specialists., active in training, development, design and press. The judging criteria will be: |innovation|, |creativity| and |play, demo|.

What can you win:
The winning team will receive an XBOX 360 elite for every participant (up to 2). Every team presenting / demo during the finals will receive an XNA Creators Club account and more.
The finals will take place in the auditoria of Groep T, Campus Vesalius, Vesaliusstraat 13, 3000 Leuven (INFO).

For more information:

http://www.xnabug.net
http://www.microsoft.com/xna

Rendertarget changes in XNA Game Studio 2.0

Shawn Hargreaves wrote about the changes of the Rendertarget in XNA 2.0, and more important, why.

From the article:

Rendertarget changes in XNA Game Studio 2.0

The bad news:

If you had a program using rendertargets that worked with the XNA Framework 1.0, it might not still work with 2.0.

The good news:

Things are actually much more consistent now, honest!

Let me explain…

How rendertargets used to work (1.0)

On Windows:

* Each rendertarget lives in a separate piece of video memory
* After you select the rendertarget, you can draw onto that video memory
* When you are done drawing, you call GetTexture to reuse that same area of video memory as a texture
* You can draw onto the same rendertarget as many times as you like, and its contents will always remain valid

On Xbox:

* All rendertargets share a single special piece of EDRAM memory
* This means only one of them can physically exist at a time
* When you finish drawing to a rendertarget, the GraphicsDevice.ResolveRenderTarget method copies from EDRAM to a separate area of texture memory
* You can then use this texture in any way you like
* But EDRAM is now being reused by some other rendertarget!
* This won’t work like you expect:
o Draw to backbuffer (EDRAM contains what you just drew)
o Switch to rendertarget
o Draw to rendertarget (EDRAM contains what you just drew)
o Resolve rendertarget (RenderTarget.GetTexture() contains a copy of what you drew)
o Switch back to backbuffer (problem! the act of selecting a different rendertarget has overwritten what you previously drew to the backbuffer, so the EDRAM no longer contains that backbuffer image)

* The rules in summary:
o Any time you change rendertarget, the contents of EDRAM are overwritten, so all previous rendertargets (including the backbuffer) are clobbered
o Rendertarget data which was resolved into the associated texture remains valid, however
o This is ok:
+ Draw to rendertarget A
+ Draw to rendertarget B
+ Draw textures from rendertargets A and B onto rendertarget C
o But this is not:
+ Draw to rendertarget A
+ Draw to rendertarget B
+ Switch back to A and continue drawing over the top of it

Problem with the 1.0 behavior:

It was far too easy to write a program that worked fine on one platform, but then rendered incorrectly when you run it on the other!

How rendertargets work now (2.0)

By default:

* You get what used to be the Xbox behavior
* On Xbox, it works exactly the same as before
* On Windows, we automatically clear your rendertargets at the right times to emulate the Xbox behavior
* This is fast on both platforms (Clear is very cheap)

If you don’t like that default:

* You can specify a different RenderTargetUsage
o RenderTarget2D constructor parameter
o To change it for the backbuffer, use the GraphicsDeviceManager.PreparingDeviceSettings event to alter GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage
* Specify RenderTargetUsage.PreserveContents to get what used to be the Windows behavior
o Works exactly the same as before on Windows
o On Xbox, we automatically copy data back from the resolved texture into EDRAM to restore its contents when you change rendertarget
o This is not cheap! Use it if you must, but be aware of the performance penalty
* Specify RenderTargetUsage.PlatformContents to get the exact same behavior as 1.0, which is different on Xbox versus Windows

Shawn recommends:

* If at all possible, use the default RenderTargetUsage.DiscardContents mode. This gives good performance and consistent behavior on both platforms.

Other good stuff:

* In 2.0, you no longer need to call the GraphicsDevice.ResolveRenderTarget method. In fact you can’t, because we removed it. We now do this automatically when you switch away from the rendertarget.
* In 2.0, we now support multiple simultaneous rendertargets (MRT) on Xbox.

Few Seats Left for XNA Game Studio Event in Belgium on 29 November

XNA

Only a few seats are left for the XNA Game Studio event on 29 November in Utopolis, Mechelen. Register here. And thanks to Walter and Tom, I can share some more details about the event below.

Are you interested in learning how to build great video games for either Microsoft® Windows® or the Xbox 360™ console? Would you like to be one of the first to see the all new version of Microsoft XNA Game Studio before it releases later this year? Want to discover just how easy it is to build a game with XNA Game Studio in just 60 minutes and get to grips with the XNA Framework and the disciplines of games development?

Then the XNA Game Studio European Tour 2007 is a not to be missed event, visiting seven different countries and bringing together top speakers from the Microsoft XNA product group in the US, local Microsoft speakers as well as experts from the games industry.

Microsoft XNA Game Studio is the revolutionary tool that makes it easy to develop video games for Windows and Xbox 360. So whether you’re an experienced games developer or a total newbie, sign up for the XNA Game Studio European Tour to build the games of your dreams.

Agenda

* Welcome
* Keynote: The Ongoing Democratization of Game Development, Dave Mitchell, Microsoft Corp (US)
* Games Industry Overview, Tommy Boffin & Hector Fernandez BGin & Streamline Studios
* Diving in to XNA Games Studio 2.0, XNA Framework and the disciplines of game development, Dave Mitchell, Microsoft Corp (US)
* Putting XNA to the test: Building a game in 60 minutes, Charles Cox, MS Corp (US)
* Closing & Wrap Up, Luc Van de Velde, Director DPE, Microsoft Belgium & Luxembourg

Keynote: The Ongoing Democratization of Game Development, Dave Mitchell, Director, Microsoft XNA, Microsoft Corporation
Join Dave Mitchell from the Microsoft XNA organization as he shares Microsoft’s plans to democratize game development beyond the initial XNA Game Studio Express offering. As the video game industry is reaching a critical juncture in its growth as a mainstream entertainment form, consumers are becoming an increasingly important partner in the creation of innovative, fun gameplay experiences which compliment commercially released titles. This keynote will share the next instalment of the XNA vision to further democratize game development by the community.

Diving in to XNA Game Studio 2.0 and the XNA Framework, Dave Mitchell, Director, & Charles Cox, Developer Educator, Microsoft XNA, Microsoft Corporation
XNA Game Studio 2.0 is the highly anticipated new release of a revolutionary game development tool that gives hobbyist, academic and indie game programmers a chance to develop and share their own games on Windows and Xbox 360. This demo-heavy session will take a closer look at what is new in 2.0 including the newly-added networking libraries based on Xbox LIVE, support for Visual Studio 2005 Standard, Professional and Team editions, new multiplayer starter kits, samples and more.

Building a Game in 60 Minutes with XNA Game Studio 2.0, Charles Cox, Developer Educator, Microsoft XNA, Microsoft Corporation
During this live session we put XNA Game Studio 2.0 to the test and build a fully-realized casual game running on an Xbox 360 in just sixty minutes. Whether you are a seasoned games coder or a programmer thinking of moving into game development, this demo-packed session will give you plenty of food for thought and the information to get you started.

Speaker Biographies
Dave Mitchell, Director, Microsoft XNA, Microsoft Corporation
Dave is a Director in the Microsoft XNA organization and manages the Microsoft XNA community offerings in addition to global business development, marketing execution and PR for XNA. XNA not only includes XNA Game Studio but also spans all tools, technologies, and services used in game development by game developers ranging from hobbyists and academics up to the largest of commercial game studios. Dave has been with Microsoft for nearly ten years and has been heavily involved with developer tools and platform technology for more than 17 years. His passion and love for video games easily outstrips that however and dates back to his Atari 2600, nearly 30 years ago.

Charles Cox, Developer Educator, Microsoft XNA, Microsoft Corporation
Charles is a Developer Educator, a role which focuses on developing and delivering innovative educational materials for game developers using XNA. His contributions focus on “quick-start” beginner instruction, and include the popular “Going Beyond” video tutorial series, presentations at several universities and the 2007 Game Developers Conference, and most recently the creation of the new XNA Game Studio Express Beginner’s Guide DVD. Prior to joining Microsoft, Charles worked at Sierra Studios on the popular Police Quest: SWAT action series. Charles is a graduate of the Digipen Institute of Technology, a video game development school in Redmond, Washington.

Your way, Your play, XNA: Modify a 2D Game in 10 minutes

Your way, Your play, XNA: Modify a 2D Game in 10 minutes is a video based learning on Springboard. The Video: Your Way, Your Play, XNA: Modify a 2D Game in 10 minutes is an introduction to Gaming: Modify your first 2D Game using XNA Games Studio Express. It walks you through some of the key gaming concepts and then add in Collision Detection and Score Keeping to the game.

Resources:

* Original 2D Project
* XNA Creators Club
* XNA Team Blog
* TorqueX (Drag & Drop Game Components)

Now Available: XNA Game Studio 2.0 (Beta)

Now Available: XNA Game Studio 2.0 (Beta) from the XNA Team Blog has the announcement.

The XNA team is pleased to announce the Beta release of XNA Game Studio 2.0! This Beta release is your chance to try out the new features available in XNA Game Studio 2.0, including support for Visual Studio 2005, multiplayer support over System Link and LIVE, and many more features and enhancements, many suggested by you, the community members.

If you’re an existing XNA Game Studio Express user, you won’t have to worry about uninstalling anything – XNA Game Studio 2.0 (Beta) lives comfortably side-by-side with XNA Game Studio Express. Just follow the link below to find out what’s new in XNA Game Studio 2.0 and download the Beta, as well as updated sample content you can use with the Beta right away. There’s even a multiplayer-enabled starter kit you can use to familiarize yourself with multiplayer programming in the XNA Framework.

XNA Game Studio 2.0 (Beta) supports multiplayer gaming over Games for Windows – LIVE. If you are planning on making multiplayer games on Windows that make use of any Games for Windows – LIVE features, you will need an Xbox LIVE Gamertag that has an active XNA Creators Club membership, and a special token.
To receive your token, send a message to xnacgp@microsoft.com with the subject “Beta Key Request”. Note that you must send this message from the same e-mail address that is associated with an Xbox LIVE Gamertag that has an active XNA Creators Club membership. (Note it may take up to a few days to receive your code in email)
If you’re not an XNA Creators Club member, you can use the System Link functionality or program against the multiplayer API’s without a code.

Please keep in mind that the timeframe between this release and our final release will be very short, in fact we’ve already had a chance to fix some of the larger issues that you may run into during the beta. That said, if you do run into issues I would encourage you to file them through our Microsoft Connect site at: http://connect.microsoft.com/site/sitehome.aspx?SiteID=226

XNA Game Studio 2.0 (Beta) Download Page

Thank you for your interest in XNA Game Studio 2.0, and we hope you enjoy the Beta!

September Content Update

A new content update for creators club and a lot of cool new demo’s for us to play with!

This week brought us some great new content for the XNA Creators Club Online website. Included in the release are the following.

Samples
Collision Series 4: Collision with a Heightmap – This sample demonstrates how to move objects along a heightmap, useful when creating a game that requires interaction between moving objects and terrain.

Custom Model Class – This sample shows how to go beyond the limits of the Model class that comes built in to the XNA Framework, loading geometry data into an entirely custom class that can be extended more easily to cope with specialized requirements.

Mesh Instancing – This sample shows how to efficiently render many copies of the same model, using GPU instancing techniques to reduce the cost of repeated draw calls.

Shatter – This sample shows how you can apply an effect on any model in your game to shatter it apart.

Utilities
Curve Editor – This utility provides an easy-to-use visual editor for creating curves for use with the XNA Framework Curve class. The curve control used to display and edit curves inside the editor can also be imported into your own applications.

Input Reporter – This utility displays input data for all controllers connected to the system. The utility supports multiple controller types, including flight sticks, dance pads, and guitars.

Xbox 360 Controller Button Glyphs – This utility is a set of images that represent the buttons, thumbsticks, and triggers on the Xbox 360 Controller.

Other
Ship Game Article – 3D Collision using the BoxCollider library – This supplemental article introduces the BoxCollider library provided in Ship Game. BoxCollider is a collision detection and response library that features an octree implementation, collision response with friction effects, and prebuilt collision-aware camera classes.

Enjoy!!

Head/Eye aiming with skeletal meshes

Check out this article at ziggyware about Head/Eye aiming with skeletal meshes. You can download the pdf and source code.
From the article:

A Method for Head and Eye Aiming using Steepest Descent by Scott M.Johnson
Abstract
A solution is presented to aim an animated character’s eyes at a target point. Optionally, the character can look directly at a target point by turning the character’s neck. This is a good solution because visual results are good, and there is an accompanying XNA project (based off the XNA Skinning Sample) that implements the solution so that you can try it and evaluate it before you decide to add it to your title. Of course since the solution is in XNA it is implemented in C#. This problem has also been called Eye and Head Tracking but “aiming” seemed more appropriate.

Head/Eye aiming with skeletal meshes

Sample controls:

Moving the targetPoint – I, J, K, L, M, N
Moving the camera – usual keys from the Skinning Sample – Arrow Keys, Z, X
Showing the reference frames of the bones – Q, A

read more | digg story

SOFTIMAGE|XSI Mod Tool Released

SOFTIMAGE has released a new version of the SOFTIMAGE|XSI Mod Tool. This version of Mod Tool comes with a set of tools for creating content to be used with Microsoft XNA Game Studio Express.

XSI Mod Tool has videos, sample content and plugins to help get you started. Head over to the SOFTIMAGE|XSI Mod Tool site.

Glenn Wilson has posted the following article on his blog: Using SoftImage XSI Mod Tool with XNA and Game Studio Express. Be sure to check that out.

August XNA Creators Club Online Update

Another update on creators.xna.com. Here’s a list of what’s new.

# Premium starter kit – Ship Game

Ship Game is a 3D spaceship combat game set inside a complex tunnel system. Ship Game features advanced lighting and textures, a full GPU particle system, and advanced physics. Explore the tunnels on your own, or take on a friend head-to-head using split-screen mode. This starter kit is only available for XNA Creator Club Members.

# Optimization Tutorial

This tutorial teaches you how to find and correct performance problems in your game, and highlights solutions to common performance problems on Xbox 360, using a particle system as an example.

# Distortion Sample

Using a particle system as an example, this tutorial teaches you how to find and correct performance problems in your game, and highlights solutions to common performance problems on Xbox 360.

# Shader Series 4: Materials and Multiple Light Sources Sample

Until now, the shader series has focused on single meshes, single lights, and single materials. This sample demonstrates how a developer might combine the techniques leading up to this sample into a usable system for composing a 3D scene.

Announcing XNA Game Studio 2.0

XNA Game studio is finally anounced. Let’s see what’s new.

What’s New with XNA Game Studio?

* XNA Game Studio 2.0 works in all versions of Visual Studio 2005. This includes Standard and Professional, as well as many other specific editions.

* The new and improved interface makes it easier for you to manage your Xbox 360 console.

* You’ll find that managing and building content is easier and more consistent in XNA Game Studio.

* We’ve included project templates for content importers and processors.

* You can configure how content is processed with the new ability to set parameters on Content Processors.

What’s new in the XNA Framework? Now you can:

* Create rich multiplayer games over Xbox LIVE using the new networking APIs.

* Create Audio more effectively with the new XACT editor!

* Host XNA Framework games easily inside a Windows Form.

* Use the virtualized GraphicsDevice: no more special code to handle device reset and recreate!

* Take advantage of render targets that are more flexible, consistent, and easier to use. Xbox 360 and Windows now support multiple render targets (MRTs) as well.

* Easily nest one component inside another thanks to improvements in GameComponent.

* Enjoy many more enhancements and tweaks!