Authoring Particle Systems Using XML and the Content Pipeline
This tutorial teaches you how to extend the Particle 3D Sample so the particle systems are defined using XML files loaded with the Content Pipeline. It contains the following sections:
- Introduction
- Getting Started
- Updating the Game Code
- Creating a Settings Assembly
- Creating XML Settings Files
- Final Result
Introduction
In the original version of the Particle 3D Sample, we defined each particle system by creating a separate class that derived from the abstract ParticleSystem base class. Each new class overloaded the InitializeSettings method to specify how to display the particle system. This meant you had to create a new class each time you wanted to add a new type of particle. Furthermore, you had to recompile your game each time you modified one of these classes to alter the particle behavior. This tutorial shows you how to make that process more efficient. Using external XML files enables you to create and tweak any number of different particle systems without changing the main game executable.
The easiest approach would be to use the .NET XmlSerializer to load the ParticleSettings data from an XML file. However, you are going to use the Content Pipeline instead. This offers several advantages:
- XML files are bulky and can be slow to load. The Content Pipeline enables you to compile your XML data into a compact binary XNB file as part of the content build process.
- Building the XML settings into a binary format makes it harder for anyone to modify your data.
- Using the Content Pipeline enables you to move a lot of setup code out of the main game and into a custom content processor. Doing this work ahead of time during the content build process keeps the game nice and simple. It also ensures good load times.
Getting Started
You are going to use the Windows version of the Particle 3D Sample as a starting point. Begin by downloading version 4.0 of the sample, and then make a copy of the sample that you can edit.
The flow of data through the Content Pipeline goes like this:
-
During the content build process:
- The
ContentImporterreads data from external files. - The
ContentProcessorprocesses the data. - The data is serialized into a binary XNB file.
- The
- Inside the game itself, the
ContentManager.Loadmethod deserializes data from the XNB file.
You do not need to write your own ContentImporter. XNA Game Studio comes
with a built-in XmlImporter that will work well for you. Also, for this
purpose you need not bother with a ContentProcessor because you do not
need to do any special processing on your data. For now, you are going to concentrate
on the basic flow of moving data from XML files into your game.
Updating the Game Code
You need to make some changes inside ParticleSystem.cs.
-
Remove the abstract keyword from the declaration of the
ParticleSystemclass. You are going to be loading XML settings data directly into the baseParticleSystemclass, rather than deriving specialized particle system classes from it, so this should no longer be abstract. -
Inside the
Fieldsregion near the top of theParticleSystemclass, add a new field to store the name of the XML settings file.C# // Name of the XML settings file describing this particle system. string settingsName;
At line 32, change this existing field declaration:
C# ParticleSettings settings = new ParticleSettings();
to:
C# ParticleSettings settings;
Since you are going to be loading settings using the
ContentManager, you no longer need to create a blank settings descriptor here. -
Find the
ParticleSystemconstructor at line 162, and change it to store the settings name.C# /// <summary> /// Constructor. /// </summary> public ParticleSystem(Game game, ContentManager content, string settingsName) : base(game) { this.content = content; this.settingsName = settingsName; } - Delete the
InitializeandInitializeSettingsmethods. You will not need them any more. -
In the
LoadContentmethod (line 173), insert these new lines, which are highlighted in bold. The first line loads your settings data via theContentManager. The others initialize the particles array.C# /// <summary> /// Loads graphics for the particle system. /// </summary> protected override void LoadContent() { settings = content.Load<ParticleSettings>(settingsName); // Allocate the particle array, and fill in the corner fields (which never change). particles = new ParticleVertex[settings.MaxParticles * 4]; for (int i = 0; i < settings.MaxParticles; i++) { particles[i * 4 + 0].Corner = new Short2(-1, -1); particles[i * 4 + 1].Corner = new Short2(1, -1); particles[i * 4 + 2].Corner = new Short2(1, 1); particles[i * 4 + 3].Corner = new Short2(-1, 1); } LoadParticleEffect(); ... -
Now, for something fun. In Solution Explorer, delete the ParticleSystems folder along with all the old hard-coded particle system classes inside it. You no longer need these!
Open Game.cs, go to line 94, and replace this section, which created several different hard-coded classes:
C# // Construct our particle system components. explosionParticles = new ExplosionParticleSystem(this, Content); explosionSmokeParticles = new ExplosionSmokeParticleSystem(this, Content); projectileTrailParticles = new ProjectileTrailParticleSystem(this, Content); smokePlumeParticles = new SmokePlumeParticleSystem(this, Content); fireParticles = new FireParticleSystem(this, Content);
with this new version that creates multiple instances of our new data driven
ParticleSystemclass, specifying a different settings file for each one:C# // Construct our particle system components. explosionParticles = new ParticleSystem(this, Content, "ExplosionSettings"); explosionSmokeParticles = new ParticleSystem(this, Content, "ExplosionSmokeSettings"); projectileTrailParticles = new ParticleSystem(this, Content, "ProjectileTrailSettings"); smokePlumeParticles = new ParticleSystem(this, Content, "SmokePlumeSettings"); fireParticles = new ParticleSystem(this, Content, "FireSettings");
And that is it! We're done.
At least we are done changing our game code. Of course, it won't actually run yet. If we press F5 to launch it, we will get a ContentLoadException with the message Error loading "ExplosionSettings." File not found. This is because we haven't actually created any settings data for the game to load yet.
Creating a Settings Assembly
To build particle system settings data using the Content Pipeline, you must move the ParticleSettings class into a second assembly. You cannot leave this directly inside the main game project for several reasons.
- The Content Pipeline code runs as part of the build process. It does not run inside the game itself. To be able to build settings data, the definition of the settings class must be available while this data is being built. At the time when the data is built, the game itself has not been built yet! So if the settings data was defined inside the game, there would be an impossible circular dependency.
- Because the Content Pipeline code runs as part of the build, you must always run it on Windows, even if the game itself is for Xbox. This means that when you are building an Xbox game, there must be two versions of the settings class: a Windows version for use during the Content Pipeline data build, and an Xbox version that can be used at run time by the game itself.
Putting the settings class into a separate assembly from the game is an elegant way to satisfy both these requirements.
To add a second project
- In Solution Explorer, right-click the Solution node, click Add, click New project, and then select the Windows Game Library template.
- Enter ParticleSettings as the name of your new project.
- Delete the Class1.cs file that the project template gives you by default. You will not need it.
- Move your
ParticleSettingsclass from the original game project to this new assembly. Drag and drop the ParticleSettings.cs file from one project to the other inside the Solution Explorer pane, and then delete the original version. -
Because we need to use the ParticleSettings class both when building content and at run time, you must reference the new project twice: once from the main game project, then again from your Content project.
- Under Particle3DSampleWindows, right-click the References node, and click Add Reference.
- Next, click the Projects tab, and then select the ParticleSettings project.
- Repeat these actions, adding to the References node in the Particle3DSampleContent project.
Creating XML Settings Files
Here we run into a small problem. Most of the data stored in the ParticleSettings class can be automatically serialized by the Content Pipeline, but it has one field of type BlendState, which is a complex GPU type that cannot be automatically serialized. To work around this, we will use Content Pipeline control attributes to tell the pipeline not to bother serializing this field, and instead use a helper property that will convert the blend state setting into a simple string that the serializer will be able to store for us.
To do this, open ParticleSettings.xml, and then add the Microsoft.Xna.Framework.Content namespace to the using statements near the top of the file. At the end of the class, replace this code:
| C# |
|---|
// Alpha blending settings. public BlendState BlendState = BlendState.NonPremultiplied; |
with this code:
| C# |
|---|
|
These control attributes tell the serializer to skip the BlendState field, and instead to use our private BlendStateSerializationHelper property, which converts the name of the blend state to and from an easily serialized string representation.
Nearly there! For your final step, you must create some actual XML files that contain particle settings data. You are going to import these XML files into our ParticleSettings class. You need to ensure they match exactly the layout of that class in order for the deserialization to work. How do we know what this XML should look like? One way is to guess. A much more reliable approach, however, is to write a little test program that constructs an object of the type of which you are interested. After that, you can serialize the object out into the XML format. You can look at the resultant XML file to see how you should format the data.
To test the XML serializer, add a TempMain.cs file to the ParticleSettings project, and then insert this code:
| C# |
|---|
|
In order to run this program, you must temporarily change the ParticleSettings project from a DLL to an executable, and add a reference to the Content Pipeline assembly.
To change the ParticleSettings project from a DLL to an executable
- In Solution Explorer, right-click the ParticleSettings project, and then click Properties.
- In the Application tab, change the Output type from Class Library to Console Application, and then change the Target profile setting from .NET Framework 4 Client Profile to .NET Framework 4.
- Right-click the References node under ParticleSettings, and then click Add Reference.
- On the .NET tab, select Microsoft.Xna.Framework.Content.Pipeline.
-
Right-click the ParticleSettings project, click Debug, and then click Start new instance.
A console window appears briefly.
Look in your ParticleSettings\bin\x86\Debug directory. You will see that it created this test.xml file.
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
<Asset Type="Particle3DSample.ParticleSettings">
<BlendState>NonPremultiplied</BlendState>
<TextureName Null="true" />
<MaxParticles>100</MaxParticles>
<Duration>PT1S</Duration>
<DurationRandomness>0</DurationRandomness>
<EmitterVelocitySensitivity>1</EmitterVelocitySensitivity>
<MinHorizontalVelocity>0</MinHorizontalVelocity>
<MaxHorizontalVelocity>0</MaxHorizontalVelocity>
<MinVerticalVelocity>0</MinVerticalVelocity>
<MaxVerticalVelocity>0</MaxVerticalVelocity>
<Gravity>0 0 0</Gravity>
<EndVelocity>1</EndVelocity>
<MinColor>FFFFFFFF</MinColor>
<MaxColor>FFFFFFFF</MaxColor>
<MinRotateSpeed>0</MinRotateSpeed>
<MaxRotateSpeed>0</MaxRotateSpeed>
<MinStartSize>100</MinStartSize>
<MaxStartSize>100</MaxStartSize>
<MinEndSize>100</MinEndSize>
<MaxEndSize>100</MaxEndSize>
</Asset>
</XnaContent>
So this is what your XML should look like. Now, undo your temporary changes to the ParticleSettings project:
- Change the Output type from Console Application to Class Library.
- Change Target profile from .NET Framework 4 to .NET Framework 4 Client Profile.
- Delete the TempMain.cs file.
- Remove the Microsoft.Xna.Framework.Content.Pipeline reference.
- Press F6 just to make sure everything still builds correctly.
Obviously, a particle system with just those default settings will not be very interesting. We can make an ExplosionSettings.xml file by copying across the hard-coded settings from the original Particle 3D Sample.
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
<Asset Type="Particle3DSample.ParticleSettings">
<BlendState>Additive</BlendState>
<TextureName>explosion</TextureName>
<MaxParticles>100</MaxParticles>
<Duration>PT2S</Duration>
<DurationRandomness>1</DurationRandomness>
<EmitterVelocitySensitivity>1</EmitterVelocitySensitivity>
<MinHorizontalVelocity>20</MinHorizontalVelocity>
<MaxHorizontalVelocity>30</MaxHorizontalVelocity>
<MinVerticalVelocity>-20</MinVerticalVelocity>
<MaxVerticalVelocity>20</MaxVerticalVelocity>
<Gravity>0 0 0</Gravity>
<EndVelocity>0</EndVelocity>
<MinColor>FF808080</MinColor>
<MaxColor>FFA9A9A9</MaxColor>
<MinRotateSpeed>-1</MinRotateSpeed>
<MaxRotateSpeed>1</MaxRotateSpeed>
<MinStartSize>10</MinStartSize>
<MaxStartSize>10</MaxStartSize>
<MinEndSize>100</MinEndSize>
<MaxEndSize>200</MaxEndSize>
</Asset>
</XnaContent>
In addition to the ExplosionSettings.xml file, you need to create the new files ExplosionSmokeSettings.xml, FireSettings.xml, ProjectileTrailSettings.xml, and SmokePlumeSettings.xml. Repeat this process of copying and pasting the parameter values from the original sample. Add these five files to the Particle3DSampleContent project.
Final Result
Press F5 to run the game.
If you followed the previous steps correctly, the results will look the same as the original Particle 3D Sample. One difference is you can now edit your particle systems by modifying the XML files. If you look in the Particle3DSample\bin\x86\Debug\Content directory, you will notice the directory does not contain any XML files. The Content Pipeline was used to compile the settings data into the XNB format.
See the XmlParticles directory for the complete code that you should have ended up with after following this tutorial.