XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   
My XNA Book
      
       Go to section on this site

Additional info


Latest Forum posts

 Account settings
  Posted by: Anonymous
  When: 07/05/2014 at 09:48:39

 forced subtitle
  Posted by: Applefly
  When: 07/05/2014 at 06:00:48

 convert DVD into PMS
  Posted by: Applefly
  When: 07/05/2014 at 05:55:25

 DVD to Digital Copy easily
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:52:29

 DVD on Xbox 360/Xbox One Console
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:51:47

 Extract .Srt Subtitles
  Posted by: Applefly
  When: 04/05/2014 at 03:54:38

 Encode Movie collection
  Posted by: Applefly
  When: 04/05/2014 at 03:52:41

 Convert DVD to WMV
  Posted by: Applefly
  When: 29/04/2014 at 05:53:50

 rip DVDs into digital files
  Posted by: Applefly
  When: 29/04/2014 at 05:51:20

 iTunes movies/music to Kindle Fire
  Posted by: ciciyu80
  When: 29/04/2014 at 05:10:20


Ads

Playing sounds in 3D using DirectSound

Last chapter was only half the fun you can have with DirectSound. We simply played a single sound, using stereo speakers. This chapter were going to add an explosion sound whenever a bullet hits a target. Now we cannot use the technique from last chapter, because when the target is on our right, we expect the explosion sound to be played by our right speaker only. This is the aim of this chapter.

Well start by loading the new sound file into a SecondaryBuffer, and make a 3Dbuffer based on this buffer. So start by adding these variables to the top of your code:

 private SecondaryBuffer explosionsound;
 private Buffer3D explosion3D;

Goto our InitializeSound method, and add these lines to it:

 BufferDescription description3D = new BufferDescription();
 description3D.ControlEffects = false;
 description3D.Control3D = true;
 explosionsound = new SecondaryBuffer("explosion.wav", description3D, sounddevice);
 explosion3D = new Buffer3D(explosionsound);

We again create a BufferDescription, and again we set ControlEffects to false, so well be able to clone the buffer later on in this chapter. We also set Control3D to true, which is a requirement if we want to create a 3Dbuffer from this SecondaryBuffer. The we load the appropriate wav file, which you can find here (link). The last line creates the 3Dbuffer from the SecondaryBuffer.

You can set the Position property of the 3Dbuffer, after which you can play the SecondaryBuffer. We need of course to supply the position of our airplane. This is done using the 3DListener object, of which you can have only 1 in the whole scene, while you can have as much 3Dbuffers in one scene as you want.

Go on and add these lines to you variables at the top of the code:

 private Listener3D listener;
 private DS.Buffer primary;

A Listener3D object needs to be created with a primary buffer, which is the second variable. Go again to the InitializeSound method, and add the following lines:

 BufferDescription descriptionlistener = new BufferDescription();
 descriptionlistener.ControlEffects = false;
 descriptionlistener.Control3D = true;
 descriptionlistener.PrimaryBuffer = true;
 primary = new DS.Buffer(descriptionlistener, sounddevice);
 listener = new Listener3D(primary);

This looks very much like creating a Buffer3D; the only difference here is that we have to use a PrimaryBuffer, which we indicate in the property of the desriptionlistener. We create the buffer, and pass it to the method that creates our Listener3D object. Of course we have to reposition our listener every time the position of our plane is changed, so create this small method:

 private void UpdateListenerPosition()
 {
  listener.Position = spacemeshposition;
  Listener3DOrientation orientation = new Listener3DOrientation();
  orientation.Front = new Vector3((float)Math.Sin(spacemeshangles.Z), (float)Math.Cos(spacemeshangles.Z), (float)Math.Sin(spacemeshangles.Y));
  orientation.Top = new Vector3((float)Math.Sin(spacemeshangles.Z), (float)Math.Sin(spacemeshangles.X), (float)Math.Cos(spacemeshangles.X));
  listener.Orientation = orientation;
 }

The first line sets the current position of our airplane as the position of the listener. Then, we have to indicate a vector that points into the direction our airplane is flying, and another one that indicates the up position of our airplane. Only by specifying the position of our plane and these 2 vectors, the position and orientation of the Listener3D object is uniquely defined.

-- ATTENTION because I write these tutorials while commuting by train, I dont have the luxury of having 3D speakers. As such, I cannot guarantee these vectors are correct, but you should get the idea. As always, feel free to send me any corrections you have found ;) --

Make sure you call this method from within your OnPaint method!

 UpdateListenerPosition();

With the Listener set up correctly and the wav file loaded into the Buffer3D, its easy to finish this chapter. Find your DrawSprites method, the part where you check for a collision type 3, indicating a collision between a bullet and a target. Add this portion of code between the brackets:

 SecondaryBuffer newexplosionsound = explosionsound.Clone(sounddevice);
 explosion3D.Position = currentsprite.position;
 newexplosionsound.Play(0, BufferPlayFlags.Default);
 soundlist.Add(newexplosionsound);

Its almost identical to playing the sound of last chapter. First we create a new instance of our explosionsound, using the Clone method of the SecondaryBuffer object. The big difference is that here we specify the position of the origin of the sound as the position of the target being hit by the bullet. Then the sound is played and we can simply add this 3D sound to our soundlist! Very convenient, this way it will automatically be disposed when finished by the SoundAffairs method!

Go try this out now. Youll notice the sound coming from different positions as you move away from the targets before actually hitting them! If almost all explosion sound very weak, chances are you forgot to put a call to yourUpdateListenerPosition method.




DirectX Tutorial 16 - Sounds in 3D

If you appreciate the amount of time I spend creating and updating
these pages, feel free to donate -- any amount is welcome !



Click here to go to the forum on this chapter!

Or click on one of the topics on this chapter to go there:
  • ArgumentException on Control3D
          Hey there! Great tutorials! I tried leaving a mess...
  • 3D Sound position
          I found an small logical error in your code when y...


    One final chapter on sounds remains and its not the least important: playing the background music. More on this in the next chapter.

     using System;
     using System.Drawing;
     using System.Collections;
     using System.ComponentModel;
     using System.Windows.Forms;
     using System.Data;
     using Microsoft.DirectX;
     using Microsoft.DirectX.Direct3D;
     using D3D = Microsoft.DirectX.Direct3D;
     using Microsoft.DirectX.DirectInput;
     using DI = Microsoft.DirectX.DirectInput;
     using Microsoft.DirectX.DirectSound;
     using DS = Microsoft.DirectX.DirectSound;
     
     namespace DirectX_Tutorial
     {
         public class WinForm : System.Windows.Forms.Form
         {
             private int[,] int_Floorplan;
             private int WIDTH;
             private int HEIGHT;
             private int differentbuildings = 5;
             private float gamespeed = 0.02f;
             private int[] buildingheights = new int[] { 0, 10, 1, 3, 2, 5 };
             private int maxtargets = 80;
     
             private System.ComponentModel.Container components = null;
             private D3D.Device device;
             private Texture scenerytexture;
             private Material material;
             private CustomVertex.PositionNormalTextured[] verticesarray;
             ArrayList verticeslist = new ArrayList();
             private Mesh spacemesh;
             private Material[] spacemeshmaterials;
             private Texture[] spacemeshtextures;
             private float spacemeshradius;
             private float scaling = 0.0005f;
             private Vector3 spacemeshposition = new Vector3(8, 2, 1);
             private Vector3 spacemeshangles = new Vector3(0, 0, 0);
             private DI.Device keyb;
             private double score = 0;
             private Mesh skyboxmesh;
             private Material[] skyboxmaterials;
             private Texture[] skyboxtextures;
             private ArrayList targetlist = new ArrayList();
             private Mesh targetmesh;
             private Texture bullettexture;
             private ArrayList spritelist = new ArrayList();
             private DS.Device sounddevice;
             private SecondaryBuffer shotsound;
             private ArrayList soundlist = new ArrayList();
             private SecondaryBuffer explosionsound;
             private Buffer3D explosion3D;
             private Listener3D listener;
             private DS.Buffer primary;
     
             struct targetstruct
             {
                 public Vector3 position;
                 public float radius;
                 public Material material;
             }
     
             struct spritestruct
             {
                 public Vector3 position;
                 public Vector3 angles;
             }
     
             struct myownvertexformat
             {
                 public float xval;
                 public float yval;
                 public float zval;
                 public float PointSize;
                 public int color;
     
                 public myownvertexformat(float fxval, float fyval, float fzval, float psize, int icolor)
                 {
                     xval = fxval;
                     yval = fyval;
                     zval = fzval;
                     PointSize = psize;
                     color = icolor;
                 }
             }
     
             public WinForm()
             {
                 InitializeComponent();
                 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
             }
     
             public void InitializeDevice()
             {
                 PresentParameters presentParams = new PresentParameters();
                 presentParams.Windowed = true;
                 presentParams.SwapEffect = SwapEffect.Discard;
                 presentParams.AutoDepthStencilFormat = DepthFormat.D16;
                 presentParams.EnableAutoDepthStencil = true;
                 device = new D3D.Device(0, D3D.DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
     
                 device.RenderState.Lighting = true;
     
                 device.Lights[0].Type = LightType.Directional;
                 device.Lights[0].Diffuse = Color.White;
                 device.Lights[0].Direction = new Vector3(1, 1, -1);
                 device.Lights[0].Update();
                 device.Lights[0].Enabled = true;
     
                 device.Lights[1].Type = LightType.Directional;
                 device.Lights[1].Diffuse = Color.White;
                 device.Lights[1].Direction = new Vector3(-1, -1, -1);
                 device.Lights[1].Update();
                 device.Lights[1].Enabled = true;
     
                 device.SamplerState[0].MinFilter = TextureFilter.Anisotropic;
                 device.SamplerState[0].MagFilter = TextureFilter.Anisotropic;
     
                 device.SamplerState[0].AddressU = TextureAddress.Mirror;
                 device.SamplerState[0].AddressV = TextureAddress.Mirror;
     
                 device.RenderState.PointSpriteEnable = true;
                 device.RenderState.PointScaleEnable = true;
                 device.RenderState.PointScaleA = 0f;
                 device.RenderState.PointScaleB = 0f;
                 device.RenderState.PointScaleC = 100f;
     
                 device.RenderState.SourceBlend = Blend.One;
                 device.RenderState.DestinationBlend = Blend.One;
             }
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 ReadUserInput(gamespeed);
                 UpdatePosition(ref spacemeshposition, spacemeshangles, gamespeed);
                 UpdateListenerPosition();
                 if (CheckCollision(spacemeshposition, spacemeshradius) > 0)
                 {
                     spacemeshposition = new Vector3(8, 2, 1);
                     spacemeshangles = new Vector3(0, 0, 0);
                     gamespeed /= 1.1f;
                     score /= 2;
                 }
     
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkSlateBlue, 1.0f, 0);
                 device.BeginScene();
     
                 device.RenderState.Ambient = Color.DarkGray;
                 device.Transform.World = Matrix.Translation(-(float)spacemeshposition.X, -(float)spacemeshposition.Y, -(float)spacemeshposition.Z) * Matrix.RotationYawPitchRoll((float)spacemeshangles.X, (float)spacemeshangles.Y, (float)spacemeshangles.Z);
                 device.VertexFormat = CustomVertex.PositionNormalTextured.Format;
                 device.Material = material;
                 device.SetTexture(0, scenerytexture);
                 device.DrawUserPrimitives(PrimitiveType.TriangleList, verticeslist.Count / 3, verticesarray);
     
                 device.Transform.World = Matrix.Scaling(scaling, scaling, scaling) * Matrix.RotationX((float)Math.PI / 2);
                 DrawMesh(spacemesh, spacemeshmaterials, spacemeshtextures);
     
                 DrawTargets();
     
                 device.RenderState.Ambient = Color.White;
                 device.Transform.World = Matrix.RotationX((float)Math.PI / 2) * Matrix.RotationYawPitchRoll((float)spacemeshangles.X, (float)spacemeshangles.Y, (float)spacemeshangles.Z);
                 DrawMesh(skyboxmesh, skyboxmaterials, skyboxtextures);
     
                 DrawSprites();
     
                 device.EndScene();
                 device.Present();
                 this.Invalidate();
     
                 SoundAffairs();
             }
     
             private void SetUpCamera()
             {
                 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, (float)this.Width / (float)this.Height, 0.3f, 500f);
                 device.Transform.View = Matrix.LookAtLH(new Vector3(0, -1f, 0.2f), new Vector3(0, 0, 0), new Vector3(0, 0, 1));
             }
     
             private void LoadTexturesAndMaterials()
             {
                 material = new Material();
     
                 material.Diffuse = Color.White;
                 material.Ambient = Color.White;
     
                 scenerytexture = TextureLoader.FromFile(device, "texturemap.jpg");
                 bullettexture = TextureLoader.FromFile(device, "bullet.jpg");
             }
     
             private void LoadFloorplan()
             {
                 WIDTH = 20;
                 HEIGHT = 15;
     
                 int_Floorplan = new int[,]
                 {
                     {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,1,1,0,0,0,1,1,0,0,1,0,1},
                     {1,0,0,1,1,0,0,0,1,0,0,0,1,0,1},
                     {1,0,0,0,1,1,0,1,1,0,0,0,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,1,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,1,1,0,0,0,1,0,0,0,0,0,0,1},
                     {1,0,1,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,1,0,0,0,0,0,0,0,0,1},
                     {1,0,0,0,0,1,0,0,0,1,0,0,0,0,1},
                     {1,0,1,0,0,0,0,0,0,1,0,0,0,0,1},
                     {1,0,1,1,0,0,0,0,1,1,0,0,0,1,1},
                     {1,0,0,0,0,0,0,0,1,1,0,0,0,1,1},
                     {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
                 };
     
                 Random random = new Random();
                 for (int x = 0; x < WIDTH; x++)
                 {
                     for (int y = 0; y < HEIGHT; y++)
                     {
                         if (int_Floorplan[x, y] == 1)
                         {
                             int_Floorplan[x, y] = random.Next(differentbuildings) + 1;
                         }
                     }
                 }
             }
     
             private void LoadMesh(string filename, ref Mesh mesh, ref Material[] meshmaterials, ref Texture[] meshtextures, ref float meshradius)
             {
                 ExtendedMaterial[] materialarray;
                 mesh = Mesh.FromFile(filename, MeshFlags.Managed, device, out materialarray);
     
                 if ((materialarray != null) && (materialarray.Length > 0))
                 {
                     meshmaterials = new Material[materialarray.Length];
                     meshtextures = new Texture[materialarray.Length];
     
                     for (int i = 0; i < materialarray.Length; i++)
                     {
                         meshmaterials[i] = materialarray[i].Material3D;
                         meshmaterials[i].Ambient = meshmaterials[i].Diffuse;
     
                         if ((materialarray[i].TextureFilename != null) && (materialarray[i].TextureFilename != string.Empty))
                         {
                             meshtextures[i] = TextureLoader.FromFile(device, materialarray[i].TextureFilename);
                         }
                     }
                 }
     
                 mesh = mesh.Clone(mesh.Options.Value, CustomVertex.PositionNormalTextured.Format, device);
                 mesh.ComputeNormals();
     
                 VertexBuffer vertices = mesh.VertexBuffer;
                 GraphicsStream stream = vertices.Lock(0, 0, LockFlags.None);
                 Vector3 meshcenter;
                 meshradius = Geometry.ComputeBoundingSphere(stream, mesh.NumberVertices, mesh.VertexFormat, out meshcenter) * scaling;
             }
     
             private void LoadMeshes()
             {
                 float dummy = 0;
                 LoadMesh("xwing.x", ref spacemesh, ref spacemeshmaterials, ref spacemeshtextures, ref spacemeshradius);
                 LoadMesh("skybox2.x", ref skyboxmesh, ref skyboxmaterials, ref skyboxtextures, ref dummy);
                 targetmesh = Mesh.Sphere(device, 1f, 10, 10);
             }
             private void DrawMesh(Mesh mesh, Material[] meshmaterials, Texture[] meshtextures)
             {
                 for (int i = 0; i < meshmaterials.Length; i++)
                 {
                     device.Material = meshmaterials[i];
                     device.SetTexture(0, meshtextures[i]);
                     mesh.DrawSubset(i);
                 }
             }
     
             private void UpdatePosition(ref Vector3 position, Vector3 angles, float speed)
             {
                 Vector3 addvector = new Vector3();
                 addvector.X += (float)(Math.Sin(angles.Z));
                 addvector.Y += (float)(Math.Cos(angles.Z));
                 addvector.Z -= (float)(Math.Tan(angles.Y));
                 addvector.Normalize();
     
                 position += addvector * speed;
             }
     
             private void InitializeInputDevices()
             {
                 keyb = new DI.Device(SystemGuid.Keyboard);
                 keyb.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                 keyb.Acquire();
             }
     
             private void ReadUserInput(float speed)
             {
                 KeyboardState keys = keyb.GetCurrentKeyboardState();
     
                 if (keys[Key.Right])
                 {
                     spacemeshangles.X += 2.5f * speed;
                 }
                 if (keys[Key.Left])
                 {
                     spacemeshangles.X -= 2.5f * speed;
                 }
     
                 if (keys[Key.Down])
                 {
                     spacemeshangles.Z -= (float)(speed * Math.Sin(spacemeshangles.X));
                     spacemeshangles.Y -= (float)(speed * Math.Cos(spacemeshangles.X));
                 }
                 if (keys[Key.Up])
                 {
                     spacemeshangles.Z += (float)(speed * Math.Sin(spacemeshangles.X));
                     spacemeshangles.Y += (float)(speed * Math.Cos(spacemeshangles.X));
                 }
     
                 if (keys[Key.Space])
                 {
                     double distance = 0;
                     if (spritelist.Count > 0)
                     {
                         spritestruct lastsprite = (spritestruct)spritelist[spritelist.Count - 1];
                         distance = Math.Sqrt(Math.Pow(lastsprite.position.X - spacemeshposition.X, 2) + Math.Pow(lastsprite.position.Y - spacemeshposition.Y, 2) + Math.Pow(lastsprite.position.Z - spacemeshposition.Z, 2));
                     }
                     if ((distance > 0.4) || (spritelist.Count == 0))
                     {
                         spritestruct newsprite = new spritestruct();
                         newsprite.position = spacemeshposition;
                         newsprite.angles = spacemeshangles;
                         spritelist.Add(newsprite);
     
                         SecondaryBuffer newshotsound = shotsound.Clone(sounddevice);
                         newshotsound.Play(0, BufferPlayFlags.Default);
                         soundlist.Add(newshotsound);
     
                         if (score >= 10) score -= 10;
                     }
                 }
             }
     
             private int CheckCollision(Vector3 position, float radius)
             {
                 if (position.Z - radius < 0) return 1;
                 if (position.Z + radius > 15) return 2;
     
                 if ((position.X < -10) || (position.X > WIDTH + 10)) return 2;
                 if ((position.Y < -10) || (position.Y > HEIGHT + 10)) return 2;
     
                 if ((position.X - radius > 0) && (position.X + radius < WIDTH) && (position.Y - radius > 0) && (position.Y + radius < HEIGHT))
                 {
                     if (position.Z - radius < buildingheights[int_Floorplan[(int)position.X, (int)position.Y]]) return 1;
                 }
     
                 for (int i = 0; i < targetlist.Count; i++)
                 {
                     targetstruct currenttarget = (targetstruct)targetlist[i];
                     if (Math.Sqrt(Math.Pow(currenttarget.position.X - position.X, 2) + Math.Pow(currenttarget.position.Y - position.Y, 2) + Math.Pow(currenttarget.position.Z - position.Z, 2)) < radius + currenttarget.radius)
                     {
                         targetlist.RemoveAt(i);
                         i--;
                         return 3;
                     }
                 }
     
                 return 0;
             }
     
             private void AddTargets()
             {
                 while (targetlist.Count < maxtargets)
                 {
                     Random random = new Random();
                     int x = random.Next(WIDTH);
                     int y = random.Next(HEIGHT);
                     float z = (float)random.Next(2000) / 1000f + 1;
                     float radius = (float)random.Next(1000) / 1000f * 0.2f + 0.01f;
     
                     bool acceptableposition = true;
                     if (int_Floorplan[x, y] > 0) acceptableposition = false;
                     foreach (targetstruct currenttarget in targetlist)
                     {
                         if (((int)currenttarget.position.X == x) && ((int)currenttarget.position.Y == y)) acceptableposition = false;
                     }
     
                     if (acceptableposition)
                     {
                         targetstruct newtarget = new targetstruct();
                         newtarget.position = new Vector3(x + 0.5f, y + 0.5f, z);
                         newtarget.radius = radius;
                         Material newmaterial = new Material();
                         newmaterial.Diffuse = Color.Red;
                         newmaterial.Ambient = Color.Red;
                         newtarget.material = newmaterial;
                         targetlist.Add(newtarget);
                     }
                 }
             }
     
             private void DrawTargets()
             {
                 device.SetTexture(0, null);
                 foreach (targetstruct currenttarget in targetlist)
                 {
                     device.Transform.World = Matrix.Scaling(currenttarget.radius, currenttarget.radius, currenttarget.radius) * Matrix.Translation(-(float)spacemeshposition.X + currenttarget.position.X, -(float)spacemeshposition.Y + currenttarget.position.Y, -(float)spacemeshposition.Z + currenttarget.position.Z) * Matrix.RotationYawPitchRoll((float)spacemeshangles.X, (float)spacemeshangles.Y, (float)spacemeshangles.Z);
                     device.Material = currenttarget.material;
                     targetmesh.DrawSubset(0);
                 }
             }
     
             private void DrawSprites()
             {
                 myownvertexformat[] spritecoordsarray = new myownvertexformat[spritelist.Count];
     
                 for (int i = 0; i < spritelist.Count; i++)
                 {
                     spritestruct currentsprite = (spritestruct)spritelist[i];
                     UpdatePosition(ref currentsprite.position, currentsprite.angles, gamespeed * 5);
                     spritelist[i] = currentsprite;
     
                     spritecoordsarray[i] = new myownvertexformat((float)currentsprite.position.X, (float)currentsprite.position.Y, (float)currentsprite.position.Z, 0.5f, Color.White.ToArgb());
     
                     int collisionkind = CheckCollision(currentsprite.position, 0.05f);
                     if (collisionkind > 0)
                     {
                         spritelist.RemoveAt(i);
                         i--;
     
                         if (collisionkind == 3)
                         {
                             SecondaryBuffer newexplosionsound = explosionsound.Clone(sounddevice);
                             explosion3D.Position = currentsprite.position;
                             newexplosionsound.Play(0, BufferPlayFlags.Default);
                             soundlist.Add(newexplosionsound);
     
                             score += 200;
                             gamespeed *= 1.02f;
                             AddTargets();
                         }
                     }
                 }            
     
                 if (spritelist.Count > 0)
                 {
                     device.SetTexture(0, bullettexture);
                     device.Material = material;
                     device.VertexFormat = VertexFormats.Position | VertexFormats.PointSize | VertexFormats.Diffuse;
                     device.Transform.World = Matrix.Translation(-(float)spacemeshposition.X, -(float)spacemeshposition.Y, -(float)spacemeshposition.Z) * Matrix.RotationYawPitchRoll((float)spacemeshangles.X, (float)spacemeshangles.Y, (float)spacemeshangles.Z);
                     device.RenderState.AlphaBlendEnable = true;
                     device.DrawUserPrimitives(PrimitiveType.PointList, spritelist.Count, spritecoordsarray);
                     device.RenderState.AlphaBlendEnable = false;
                 }
             }
     
             private void SoundAffairs()
             {
                 if (soundlist.Count > 0)
                 {
                     for (int i = soundlist.Count - 1; i > -1; i--)
                     {
                         SecondaryBuffer currentsound = (SecondaryBuffer)soundlist[i];
                         if (!currentsound.Status.Playing)
                         {
                             currentsound.Dispose();
                             soundlist.RemoveAt(i);
                         }
                     }
                 }
             }
     
             private void InitializeSound()
             {
                 sounddevice = new DS.Device();
                 sounddevice.SetCooperativeLevel(this, CooperativeLevel.Normal);
     
                 BufferDescription description = new BufferDescription();
                 description.ControlEffects = false;
                 shotsound = new SecondaryBuffer("shot.wav", description, sounddevice);
     
                 BufferDescription description3D = new BufferDescription();
                 description3D.ControlEffects = false;
                 description3D.Control3D = true;
                 explosionsound = new SecondaryBuffer("explosion.wav", description3D, sounddevice);
                 explosion3D = new Buffer3D(explosionsound);
     
                 BufferDescription descriptionlistener = new BufferDescription();
                 descriptionlistener.ControlEffects = false;
                 descriptionlistener.Control3D = true;
                 descriptionlistener.PrimaryBuffer = true;
                 primary = new DS.Buffer(descriptionlistener, sounddevice);
                 listener = new Listener3D(primary);
             }
     
             private void UpdateListenerPosition()
             {
                 listener.Position = spacemeshposition;
                 Listener3DOrientation orientation = new Listener3DOrientation();
                 orientation.Front = new Vector3((float)Math.Sin(spacemeshangles.Z), (float)Math.Cos(spacemeshangles.Z), (float)Math.Sin(spacemeshangles.Y));
                 orientation.Top = new Vector3((float)Math.Sin(spacemeshangles.Z), (float)Math.Sin(spacemeshangles.X), (float)Math.Cos(spacemeshangles.X));
                 listener.Orientation = orientation;
             }
     
             private void VertexDeclaration()
             {
                 float imagesintexture = 1 + differentbuildings * 2;
     
                 for (int x = 0; x < WIDTH; x++)
                 {
                     for (int y = 0; y < HEIGHT; y++)
                     {
                         int currentbuilding = int_Floorplan[x, y];
                         verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(0, 0, 1), (currentbuilding * 2 + 1) / imagesintexture, 1));
                         verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, buildingheights[currentbuilding]), new Vector3(0, 0, 1), currentbuilding * 2 / imagesintexture, 1));
                         verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y + 1, buildingheights[currentbuilding]), new Vector3(0, 0, 1), currentbuilding * 2 / imagesintexture, 0));
     
                         verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y + 1, buildingheights[currentbuilding]), new Vector3(0, 0, 1), currentbuilding * 2 / imagesintexture, 0));
                         verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, buildingheights[currentbuilding]), new Vector3(0, 0, 1), (currentbuilding * 2 + 1) / imagesintexture, 0));
                         verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(0, 0, 1), (currentbuilding * 2 + 1) / imagesintexture, 1));
     
                         if (y > 0)
                         {
                             if (int_Floorplan[x, y - 1] != int_Floorplan[x, y])
                             {
                                 if (int_Floorplan[x, y - 1] > 0)
                                 {
                                     currentbuilding = int_Floorplan[x, y - 1];
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(0, 1, 0), (currentbuilding * 2 - 1) / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, buildingheights[currentbuilding]), new Vector3(0, 1, 0), currentbuilding * 2 / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, 0f), new Vector3(0, 1, 0), currentbuilding * 2 / imagesintexture, 1));
     
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, buildingheights[currentbuilding]), new Vector3(0, 1, 0), currentbuilding * 2 / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(0, 1, 0), (currentbuilding * 2 - 1) / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(0, 1, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
     
                                 }
                                 if (int_Floorplan[x, y] > 0)
                                 {
                                     currentbuilding = int_Floorplan[x, y];
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(0, -1, 0), currentbuilding * 2 / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, 0f), new Vector3(0, -1, 0), (currentbuilding * 2 - 1) / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, buildingheights[currentbuilding]), new Vector3(0, -1, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
     
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(0, -1, 0), currentbuilding * 2 / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x + 1, y, buildingheights[currentbuilding]), new Vector3(0, -1, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(0, -1, 0), currentbuilding * 2 / imagesintexture, 0));
                                 }
     
                             }
                         }
     
                         if (x > 0)
                         {
                             if (int_Floorplan[x - 1, y] != int_Floorplan[x, y])
                             {
                                 if (int_Floorplan[x - 1, y] > 0)
                                 {
                                     currentbuilding = int_Floorplan[x - 1, y];
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(1, 0, 0), currentbuilding * 2 / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, 0f), new Vector3(1, 0, 0), (currentbuilding * 2 - 1) / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, buildingheights[currentbuilding]), new Vector3(1, 0, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
     
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, buildingheights[currentbuilding]), new Vector3(1, 0, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(1, 0, 0), currentbuilding * 2 / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(1, 0, 0), currentbuilding * 2 / imagesintexture, 1));
                                 }
                                 if (int_Floorplan[x, y] > 0)
                                 {
                                     currentbuilding = int_Floorplan[x, y];
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, 0f), new Vector3(-1, 0, 0), (currentbuilding * 2 - 1) / imagesintexture, 1));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(-1, 0, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, 0f), new Vector3(-1, 0, 0), currentbuilding * 2 / imagesintexture, 1));
     
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y, buildingheights[currentbuilding]), new Vector3(-1, 0, 0), (currentbuilding * 2 - 1) / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, buildingheights[currentbuilding]), new Vector3(-1, 0, 0), currentbuilding * 2 / imagesintexture, 0));
                                     verticeslist.Add(new CustomVertex.PositionNormalTextured(new Vector3(x, y + 1, 0f), new Vector3(-1, 0, 0), currentbuilding * 2 / imagesintexture, 1));
                                 }
                             }
                         }
                     }
                 }
                 verticesarray = (CustomVertex.PositionNormalTextured[])verticeslist.ToArray(typeof(CustomVertex.PositionNormalTextured));
             }
     
             protected override void Dispose(bool disposing)
             {
                 if (disposing)
                 {
                     if (components != null)
                     {
                         components.Dispose();
                     }
                 }
                 base.Dispose(disposing);
             }
     
             private void InitializeComponent()
             {
                 this.components = new System.ComponentModel.Container();
                 this.Size = new System.Drawing.Size(500, 500);
                 this.Text = "Riemer's DirectX Tutorial using C# -- Season 2";
             }
     
             static void Main()
             {
                 using (WinForm our_directx_form = new WinForm())
                 {
                     our_directx_form.InitializeDevice();
                     our_directx_form.SetUpCamera();
                     our_directx_form.LoadFloorplan();
                     our_directx_form.VertexDeclaration();
                     our_directx_form.LoadTexturesAndMaterials();
                     our_directx_form.LoadMeshes();
                     our_directx_form.InitializeInputDevices();
                     our_directx_form.AddTargets();
                     our_directx_form.InitializeSound();
                     Application.Run(our_directx_form);
                 }
             }
         }
     }


    Google
     
    Webwww.riemers.net


    If you appreciate the amount of time I spend creating and updating
    these pages, feel free to donate -- any amount is welcome !



    - Website design & XNA + DirectX code : Riemer Grootjans -
    ©2003 - 2011 Riemer Grootjans
  • Translations

    This site in English
    This site in Korean
    This site in Czech

    Microsoft MVP Award



    2007 - 2011 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    XNA 3.0 Recipes Book (8)
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Tutorials (160)
    XNA 4.0 using C# (89)
    DirectX using C# (54)
    Series 1:Terrain (14)
    Series 2: Flightsim (19)
    Starting code
    Textures
    The floorplan
    Creating the 3D City
    Meshloading from file
    Ambient light
    Action
    Flight kinematics
    Collision detection
    Skybox
    Texture filtering
    Adding targets
    Point sprites
    Alpha blending
    DirectSound
    Sounds in 3D
    Playing MP3 files
    Displaying text
    Going fullscreen
    Series 3: HLSL (19)
    Short Tuts (2)
    DirectX using C++ (15)
    DirectX using VB (2)
    -- Expand all --


    Thank you!

    Support this site --
    any amount is welcome !

    Stay up-to-date

    I don't have the time to keep a News section, so stay informed about the updates by clicking on this RSS file!