Thursday, 4 October 2012

Fancy playing with C++ and DirectX 11

Well I am starting out down that road too, my C++ is rusty, I know little about DX11, but what the hell, you have to start somewhere right? So if you fancy trying your hand at it to, check out my first post on the subject.

Heads up!

As we have seen over the past few days, the future of this site seems uncertain, and so I have decided to archive my historical posts I have here; and have started to move them to a new blogspot blog which you can find here should this site go.

I am also starting to take a look at DirectX11 with C++, and have started a new blog here, so if you are interested in this area of development, then please feel free to pop by, take a look at what I am up to and comment as much as you like :)

I would also like to keep bloging about XNA as I love it so much, so I am intending to continue that here.

To all of you that have followed, commented and helped my out over my time here and with XNA, I thank you so very, very much, without you guys I would not have discovered so much, and to all the people I have met at events and user group meets, it has been a pleasure to have known such an enthusiastic and nice bunch of guys.

Thanks,

Charles.

2D Crepuscular (God) Rays

If you follow my blog, you know I have already covered this as a 3D implementation, well while having a nose on twitter, I spotted that x35mm (another XNA developer from the midlands :D) was writing what looked like a pretty cool hack and slash Ronin game for DBP, and I thought, that would look nice with some God rays to give it some more lighting details, so sent x35mm my 2D implementation of the God ray post process, and this is what he did with it:



Pretty cool eh :D
So, I am going to post here this 2D implementation. Keep in mind that this effect will not work on the WP7 device as it uses custom shaders to do what it needs to do, might have a look at a CPU implementation, but I reckon it will suck.
Overview
If you refer back to my post on this for 3D you will see all the same shaders, the difference in this 2D sample is the way the light mask is built. Effectively you need to render your light source, over that render the elements in your scene that are obscuring that source over the top in black to create the light mask, then apply the Crepuscular post processing effect. Then render the scene as you would normaly and then using an additive blend apply the god ray’s over the top.
1. Draw Light Source

Here the post processor is rendering the light mask at the position we want on the screen, as you can see I have put up a few keyboard controls you can use to alter the parameters to the effect, so you can move the light source around, alter the exposure, stuff like that.
2. Draw Light Mask

There are a few items in this scene, a number of “mountain” images which are just wrap able textures and a samurai head icon for my mouse pointer, all png’s so we can use the alpha channel on them to allow light to bleed through. The post process is then applied to this to make the light bleed past the edges of the mask to give the god ray effect.
3. Draw Scene

The scene is then drawn ready to be blended with the processed mask.
4. Combine Scene and Ray Images

Finally it’s all brought together to give the overall effect.
5. Animate It
So I am scrolling the mountains at different speeds to give the sense of movement over the terrain and moving the mouse icon to obscure the light showing how dynamic this technique is. Also at the same time altering the parameters as I go.
As you can see it renders at a good frame rate, 60fps,  and this is at 900x1440 on my laptop. I have not personally ran this sample on my 360, buy x35mm has I believe.
Check out Dawn of the Ronin (pre god rays) here.
The solution for this sample can be found here.
I have also made an update to this so that the effect takes screen resolution into account here.
If you use this technique in your work, please let me know, be cool to see it used in the real world, just like x35mm has done in his game.

XNA with BulletSharp Physics Engine

Did a quick clip to show the progress of my current engine as I have started to put a third party physics engine in. For years I have struggles and struggled with writing my own, with some success, but to be honest, I never could quite get it right. So I have took it on the chin and decided to go with a third party engine. I chose BulletSharp as it’s the physics engine used in ST Excalibur. In this clip I have the engine with a load of cubes, a sphere and terrain. As expected the lighting is deferred, with a single shadow casting light source.

Simple Active Tiles using XNA on WP7

So another quick post I want to do is on using active tiles in XNA, or rather how you instantiate them in you WP7 application using XNA, like in the last post we have to have the assets in the project rather than the content project.
So, simply enough I created a method called SetTile, this will create the active tile for you, so when your game is pinned it will display the tile and the information you want on it. I used the same sample I did last time to implement this so it’s all rolled in with the ringtone source.
        public void SetTile(string title, string data, string tileAsset)
        {
            ShellTile tile = ShellTile.ActiveTiles.First();

            if (tile != null)
            {
                StandardTileData tileUpdate = new StandardTileData
                {
                    BackTitle = title,
                    BackContent = data,
                    BackBackgroundImage = new Uri(tileAsset, UriKind.Relative)
                };

                tile.Update(tileUpdate);
            }
        }
So you could call the method like this:
            SetTile("Ringtones", "Play them or save them", "Tile.jpg");
So, now when you pin your application you can get something like this when the tile flips:



Naturally you would have much better icons and messages on your tiles, but you could use this to show the players last high score, or there current progress in a currently saved game etc..
Source can be found here [Not Yet Uploaded]



Ringtones on WP7 using XNA

So, I did a sample for a friend a while back on how to add ringtones to a WP7 title that has been written in XNA. As we all know if you are writing it in Silverlight, there are plenty of samples out there, but I never spotted one for XNA. So I wrote this, as ever I may well be going about it in a cack handed manner, so please feel free to comment and/or correct anything you see in this post by adding a comment below. Thanks.
For this sample, the first thing I did was create some ring tones, now I did this in a very simplistic manor, I got a copy of Hammerhead and just used a few samples off that, 4 ring tones.
Now in XNA, we normally just throw our assets into the content pipeline and it sorts it all out for us, but due to the way MS have implemented ringtones we can’t just do that in XNA, we have to have them in the content pipeline as wav’s and as they are intended to be in the game project it’s self as mp3’s. This is all due to the lack of control XNA has compared with the Silverlight implementation over the MediaPlayer, read into that what you will…
[EDIT]Just found this post, which will get around this :S [/EDIT]
So, with my 4 new super duper ring tones my project(s) look like this:



Here is a quick shot of the code in my Update method
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                // If it's paused, start it back up again...
                if (MediaPlayer.State == MediaState.Paused)
                    MediaPlayer.Resume();

                this.Exit();
            }

            // First of all, and this is probably the only situation you can do this
            // Pause the media player if it is playing, this will also pause the
            // users own music, might be work you wanrning them before you enter
            // your ring tone screen
            if (MediaPlayer.State == MediaState.Playing)
            {
                MediaPlayer.Pause();
            }
When playing your ring tones, you don’t want the media player playing at the same time, this situation is probably the only time you can just pause the media player…
I am not going to go over the code that renders the ringtone options, just show you the method used to play and to save the ringtones to the device.
Play a Ringtone
        class ScreenSprite { }
        public void playThisRingTone(object sender)
        {
            ScreenSprite thisRT = (ScreenSprite)sender;

            if (playingRTNo != -1)
            {
                ringTonesText[playingRTNo].Shadow = true;
                ringTonesText[playingRTNo].Color = Color.Red;
            }

            int rt = int.Parse(thisRT.Tag);
            playingRTNo = rt;

            // Play the RT.
            if (playingRT != null && playingRT.State == SoundState.Playing)
                playingRT.Stop();

            playingRT = Content.Load<SoundEffect>(string.Format("Audio/Ringtones/RingTone {0}", rt + 1)).CreateInstance();

            ringTonesText[rt].Shadow = false;
            ringTonesText[rt].Color = Color.DarkRed;

            playingRT.Play();
        }
The sender is the object that has been taped, so the play button for a given ring tone, this has a tag with the ring tone number to be played, you could put the full ring tone name in there if you liked. I then get that into a SoundEffect object and play it, this is a global SoundEffect object as I only want to play 1 at any given time and may want to stop it mid play.


Save a Ringtone
        public void SaveRingTone(string ringtone)
        {
            try
            {
                if (!Guide.IsTrialMode)
                {
                    SaveRingtoneTask srt = new SaveRingtoneTask();
                    srt.Completed += new EventHandler<TaskEventArgs>(srt_Completed);

                    srt.Source = new Uri(string.Format("appdata:/{0}", ringtone));
                    srt.DisplayName = "";
                    srt.IsShareable = true;
                    srt.Show();
                }
                else
                {
                    dialogButtons.Clear();
                    dialogButtons.Add("OK");

                    Guide.BeginShowMessageBox("Trial Mode",
                                      "Purchase the full game to get the ringtones",
                                      dialogButtons, 0, MessageBoxIcon.Alert, null, null);
                }
            }
            catch (Exception e)
            {
                dialogButtons.Clear();
                dialogButtons.Add("OK");

                Guide.BeginShowMessageBox("Error",
                                  e.Message,
                                  dialogButtons, 0, MessageBoxIcon.Alert, null, null);
            }
        }

        void srt_Completed(object sender, TaskEventArgs e)
        {
            switch (e.TaskResult)
            {
                //Logic for when the ringtone was saved successfully
                case TaskResult.OK:
                    dialogButtons.Clear();
                    dialogButtons.Add("OK");

                    Guide.BeginShowMessageBox("Ringtone Saved",
                                      "The ringtone was saved successfully",
                              dialogButtons, 0, MessageBoxIcon.Alert, null, null);

                    break;

                //Logic for when the task was cancelled by the user
                case TaskResult.Cancel:
                    break;

                //Logic for when the ringtone could not be saved
                case TaskResult.None:
                    dialogButtons.Clear();
                    dialogButtons.Add("OK");

                    Guide.BeginShowMessageBox("Can't Save..",
                                      "Can't save this ringtone",
                              dialogButtons, 0, MessageBoxIcon.Alert, null, null);
                    break;
            }
        }
The method to save a ring tone, first checks we are not in trial, and if not then allows the user to save the ringtone, this is why I put the mp3’s in the game project so they are accessible from “appdata:/”. The SaveRingToneTask Show method is then called:


The srt_Completed call back method then informs the user if it’s all gone well.
So that’s about it, my way of saving/playing ringtones on WP7 in XNA. As ever, comments are more than welcome…
Source code can be found here [Not yet uloaded]












Android NDK Beginner’s Guide



First thing that got me about this book was the comprehensive installation instructions, covering the installation of the JDK (Java Development Kit), Android SDK (Software Development Kit), Android NDK  (Native Development Kit) and the IDE (Eclipse) across a number of platforms, Windows PC, Mac OS X and Linux PC. Now this it great as it’s sure to cover all those wanting to develop on this platform, but does lead to a lot of page skipping, but I guess that can’t be helped.
Having already played with Eclipse and the Android SDK, I only had to install the NDK and refresh what I already had installed (indigo upgrade), but still it’s a lot of work to get this all lined up for Android development, really makes you appreciate Visual Studio and all it’s quirks. Another draw back as a VS developer is all the command line compilation, but once you are all set up you can then get into the book samples.
Anyway, back to the book and it’s content, from the off you get to command line compile some samples and see them running on the Android, then into the IDE (Eclipse) and creating your first simple project in eight pretty simple steps. Then onto the C/C++ integration, now, it may well have been me but I found an issue when trying to set javah.exe up as described in the book, just in case you also have the same issue, here is the arguments string that I ended up using to generate my header file:
-jni -verbose -d ${workspace_loc:/MyProject/jni} -classpath ${workspace_loc:/MyProject/bin/classes/} com.myproject.MyActivity
Other than my own issues with Eclipse and the odd typo, I quite enjoyed playing with native code on the Android plat form, the book will show you how to pass data to and from your hybrid Java/C++ code, to creating a fully native application, rendering with OpenGL ES (which i am playing with now) as well as handling devices and sensors and even has a chapter for porting existing libraries to the Android platform.
I think the only other suggestion I would have would be how the code is rendered, it may well be different in a physical book (I have an ebook) but it would have been nice if tabulation and syntax highlighting was used. Other than that I have enjoyed it :)