<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sgt. Conker &#187; 3D</title>
	<atom:link href="http://www.sgtconker.com/category/xna/3d/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sgtconker.com</link>
	<description>We are &#34;absolutely fine&#34;</description>
	<lastBuildDate>Wed, 06 Jul 2011 13:29:44 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Hiding a Clingerman to Talk Natively</title>
		<link>http://www.sgtconker.com/2011/04/hiding-a-clingerman-to-talk-natively/</link>
		<comments>http://www.sgtconker.com/2011/04/hiding-a-clingerman-to-talk-natively/#comments</comments>
		<pubDate>Fri, 29 Apr 2011 13:00:25 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Direct3D]]></category>
		<category><![CDATA[Direct3D 11]]></category>
		<category><![CDATA[George W. Clingerman]]></category>
		<category><![CDATA[SharpDX]]></category>
		<category><![CDATA[SlimDX]]></category>
		<category><![CDATA[VoteForGeorge]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1988</guid>
		<description><![CDATA[ In Benchmarking C#/.Net Direct3D 11 APIs vs native C++ (a post from March 14, I wonder why I did not share this already…) Alexandre Mutel explores the cost of calling native APIs from managed code (AKA interop) via micro benchmarking various managed Direct3D 11 APIs. He does this because:
Hopefully, in SharpDX unlike any other [...]]]></description>
			<content:encoded><![CDATA[<p><img style="background-image: none; border-right-width: 0px; margin: 0px 8px 8px 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Hiding a Clingerman" border="0" alt="Hiding a Clingerman" align="left" src="http://www.sgtconker.com/wp-content/uploads/2011/04/Hiding-a-Clingerman.jpg" width="244" height="184" /> In <a href="http://code4k.blogspot.com/2011/03/benchmarking-cnet-direct3d-11-apis-vs.html">Benchmarking C#/.Net Direct3D 11 APIs vs native C++</a> (a post from March 14, I wonder why I did not share this already…) <a href="http://www.blogger.com/profile/05096938106073079832">Alexandre Mutel</a> explores the cost of calling native APIs from managed code (AKA interop) via micro benchmarking various managed Direct3D 11 APIs. He does this because:</p>
<blockquote cite="http://code4k.blogspot.com/2011/03/benchmarking-cnet-direct3d-11-apis-vs.html"><p>Hopefully, in SharpDX unlike any other DirectX .NET APIs, this code has been written to be consistent over the whole generated code, and was carefully designed to be quite efficient… but still, It has obviously a cost, and we need to know it!</p>
</blockquote>
<p><strong>Spoiler:</strong> The offerings Microsoft has in store are, by far, slower than SlimDX/SharpDX.</p>
<p>In other news: There is <a href="http://forums.create.msdn.com/forums/t/81418.aspx">a thread over in the AppBuhAppHub forums praising the XNA MVPs</a>. We here in the barracks fully support that effort – mostly due to the fact that Captain ZSquare has access to various arms here and <em title="We means the Sarg">we</em> lost the keys to lock up the arsenal… – so you might head over to add to the +1 (none of the Google +1 stuff) choir.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/04/hiding-a-clingerman-to-talk-natively/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nuclex Framework, Community Character Voting and Morph Targets</title>
		<link>http://www.sgtconker.com/2011/02/nuclex-framework-community-character-voting-and-morph-targets/</link>
		<comments>http://www.sgtconker.com/2011/02/nuclex-framework-community-character-voting-and-morph-targets/#comments</comments>
		<pubDate>Sat, 05 Feb 2011 21:58:47 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[FatCow]]></category>
		<category><![CDATA[Nuclex]]></category>
		<category><![CDATA[VoteForGeorge]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2011/02/nuclex-framework-community-character-voting-and-morph-targets/</guid>
		<description><![CDATA[Markus “Cygon4” Ewald&#160;announces the immediate availability of an intermediate release of his Nuclex Framework, adding: “There are still outstanding issues, but the previous release is already getting a beard and I'm getting reports for issues already solved  ”
Amit Ginni Patpatia of FatCow Games AS fame reminds the community to vote for a character for [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.nuclex.org/">Markus “Cygon4” Ewald</a>&#160;<a href="http://twitter.com/#!/Cygon4/status/33875462933454849">announces the immediate availability</a> of an <a href="http://nuclexframework.codeplex.com/releases/view/60431">intermediate release of his Nuclex Framework</a>, <a href="http://twitter.com/#!/Cygon4/status/33875616000385025">adding</a>: “<q cite="http://twitter.com/#!/Cygon4/status/33875616000385025">There are still outstanding issues, but the previous release is already getting a beard and I'm getting reports for issues already solved <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </q>”</p>
<p><a href="http://twitter.com/#!/AmitGinni/status/33904490679640064">Amit Ginni Patpatia</a> of <a href="http://www.fatcowgames.net/">FatCow Games AS</a> fame reminds the <a href="http://networkedblogs.com/dIWpw">community to vote for a character</a> for an upcoming game.</p>
<p>Last but not least <a href="http://twitter.com/#!/mvinetwork/status/33927577106124801">Barnaby Smith</a>&#160;<a href="http://twitter.com/#!/mvinetwork/status/33927577106124801">pokes me</a> about an <a href="http://mvinetwork.co.uk/2011/02/02/xna-morph-targets/">XNA 3.1 Morph Target implementation he put online</a>: “<q cite="http://mvinetwork.co.uk/2011/02/02/xna-morph-targets/">This example uses multiple vertex streams and blends between them using a vertex shader. This approach is a differing method to CPU or VTF based implementations and does not require the calculation of vertex textures, making it quite simple and straightforward.</q>”</p>
<p> <iframe title="YouTube video player" height="390" src="http://www.youtube.com/embed/e6PLtA7wgg0?rel=0" frameborder="0" width="480" allowfullscreen="allowfullscreen"></iframe>
<p><a href="http://mvinetwork.co.uk/2011/02/02/xna-morph-targets/">Source code and more details can be found at his post</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/02/nuclex-framework-community-character-voting-and-morph-targets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA 4.0 Light Pre-Pass</title>
		<link>http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass-2/</link>
		<comments>http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass-2/#comments</comments>
		<pubDate>Sun, 23 Jan 2011 09:08:38 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Coluna]]></category>
		<category><![CDATA[light pre pass]]></category>
		<category><![CDATA[Rendering]]></category>
		<category><![CDATA[XNA 4.0]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1947</guid>
		<description><![CDATA[Jorge Coluna posted an article on his site about implementing the Light Pre-Pass technique for rendering in XNA 4.0

Read all about it here.
]]></description>
			<content:encoded><![CDATA[<p>Jorge Coluna posted an article on<a href="http://jcoluna.wordpress.com/"> his site</a> about implementing the Light Pre-Pass technique for rendering in XNA 4.0</p>
<p><a href="http://jcoluna.wordpress.com/2011/01/18/xna-4-0-light-pre-pass/"><img class="alignnone" title="Light Pre-Pass in XNA 4.0" src="http://jcoluna.files.wordpress.com/2011/01/shot-lpp-11.jpg" alt="Light Pre-Pass in XNA 4.0" width="467" height="275" /></a></p>
<p>Read all about it <a href="http://jcoluna.wordpress.com/2011/01/18/xna-4-0-light-pre-pass/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA 4.0 Light Pre-Pass</title>
		<link>http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass/</link>
		<comments>http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass/#comments</comments>
		<pubDate>Fri, 21 Jan 2011 05:42:22 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[light pre pass]]></category>
		<category><![CDATA[VoteForGeorge]]></category>
		<category><![CDATA[XNA 4.0]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass/</guid>
		<description><![CDATA[Jorge Coluna shares the code and an article of his Light Pre-Pass technique for XNA 4.0. Says the Jorge:
The discussion between pros and cons of different techniques for real-time lighting has been running for years. Forward rendering, deferred shading and light pre-pass are some of the most famous techniques nowadays. Their definitions and variations can [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jcoluna.wordpress.com/">Jorge Coluna</a> shares the code and an article of his <a href="http://jcoluna.wordpress.com/2011/01/18/xna-4-0-light-pre-pass/">Light Pre-Pass technique</a> for XNA 4.0. Says the Jorge:</p>
<blockquote cite="http://jcoluna.wordpress.com/2011/01/18/xna-4-0-light-pre-pass/"><p>The discussion between pros and cons of different techniques for real-time lighting has been running for years. Forward rendering, <a href="http://en.wikipedia.org/wiki/Deferred_shading">deferred shading</a> and <a href="http://diaryofagraphicsprogrammer.blogspot.com/2008/03/light-pre-pass-renderer.html">light pre-pass</a> are some of the most famous techniques nowadays. Their definitions and variations can be found with a simple search on internet, with all the most complex mathematics, notations and formulas possible. Therefore I will not focus on this.</p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Voxel Engine on Codeplex</title>
		<link>http://www.sgtconker.com/2010/11/voxel-engine-on-codeplex/</link>
		<comments>http://www.sgtconker.com/2010/11/voxel-engine-on-codeplex/#comments</comments>
		<pubDate>Sat, 06 Nov 2010 10:42:58 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Engine]]></category>
		<category><![CDATA[Minecraft]]></category>
		<category><![CDATA[Steve Marshall]]></category>
		<category><![CDATA[Terrain]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1867</guid>
		<description><![CDATA[Steve Marshall sent us a link to TechCraft, a 'minecraft-style terrain engine in XNA'. You can see a video of it below.

]]></description>
			<content:encoded><![CDATA[<p>Steve Marshall sent us a link to <a href="http://techcraft.codeplex.com/">TechCraft</a>, a 'minecraft-style terrain engine in XNA'. You can see a video of it below.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="560" height="340" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/uy4mLCKBMEI?fs=1&amp;hl=en_US" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="560" height="340" src="http://www.youtube.com/v/uy4mLCKBMEI?fs=1&amp;hl=en_US" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/11/voxel-engine-on-codeplex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA Morphing Meshes Tutorial</title>
		<link>http://www.sgtconker.com/2010/11/xna-morphing-meshes-tutorial/</link>
		<comments>http://www.sgtconker.com/2010/11/xna-morphing-meshes-tutorial/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 20:36:08 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Morphing Meshes]]></category>
		<category><![CDATA[The Cansin]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1864</guid>
		<description><![CDATA[The Cansin posted a new and interesting tutorial about morphing meshes in XNA
With documentation and source code available, the tutorial takes you through the steps of implementing morphing meshes.
Check it out here.
]]></description>
			<content:encoded><![CDATA[<p>The Cansin posted a new and interesting tutorial about morphing meshes in XNA</p>
<p>With documentation and source code available, the tutorial takes you through the steps of implementing morphing meshes.</p>
<p>Check it out <a href="http://thecansin.com/2010/11/xna-morphing-meshes-tutorial/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/11/xna-morphing-meshes-tutorial/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Article: Rolling World Tutorial</title>
		<link>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/</link>
		<comments>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 21:01:46 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Christian Schlager]]></category>
		<category><![CDATA[Content Creation]]></category>
		<category><![CDATA[Rolling World]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1745</guid>
		<description><![CDATA[by Christian Schlager



When you look around the XBox Indie Games Channel, there aren't a lot of  3D games around. Most XNA games only feature 2D graphics. I hope to  contribute with this tutorial to making 3D graphics a bit less  intimidating. And maybe the little prototype we will create throughout  the [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Christian Schlager</h4>
<div align="center">
<img width="60%" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/gfx/aerial_perspective_in_game.jpg">
</div>
<p>When you look around the XBox Indie Games Channel, there aren't a lot of  3D games around. Most XNA games only feature 2D graphics. I hope to  contribute with this tutorial to making 3D graphics a bit less  intimidating. And maybe the little prototype we will create throughout  the next pages will be the starting point of a great 3D indie game by  one of you <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>We will make a prototype that features the kind of rolling world effect  that you can see in games such as Animal Crossing or DeathSpank. We will  also create the textures and 3D models that go along with the rolling  effect and recreate the combination of 2D art with a 3D world you can  see in the game DeathSpank.<br />
<span id="more-1745"></span></p>
<h4>Difficulty</h4>
<p>This tutorial is intended for Beginner/Intermediate developers.<br />
If you played around with XNA and /or worked on 2D games before this tutorial should be no problem for you.</p>
<h4>Content</h4>
<p>The first section of this tutorial covers the creation of the assets for our game.<br />
We will draw textures for the world, for the trees and a very simple one for the hero.<br />
We will also create a simple DirectX effect file which we will use to render the models we create in SoftImage Mod Tool.<br />
Once we have all the assets we will set up our game project in Visual  Studio, load and render game objects and then move the hero of our game  around.<br />
In the last section we will add the rolling world effect. We will  develop a concept of the effect with sketches and pseudo-code and then  implement the effect.<br />
Finally, there is some bonus content you might try once you are done with the tutorial.<br />
This tutorials comes with pre-made assets in case you are only  interested in the programming side of the tutorial. You can also skip  the foreplay completely and jump to the rolling world effect part using  the project in the folder WorldGame.<br />
You can also explore for yourself with the complete rolling world game in the folder RollingWorldGame.</p>
<h4>Software</h4>
<dl>
<dt>Visual C# 2008 Express</dt>
<dd>The Visual Studio 2008 Express is a free set of tools for developing applications for Windows.<br />
<a href="http://www.microsoft.com/express/Downloads/#2008-Visual-CS" target="new">Download Visual C\# 2008 Express</a> </dd>
<dt>XNA Game Studio 3.1</dt>
<dd>This software package contains the XNA framework which includes an  extensive set of class libraries specific to game development. Once you  installed the Game Studio you can use it in Visual Studio:<br />
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=80782277-d584-42d2-8024-893fcd9d3e82" target="new">Microsoft XNA Game Studio 3.1</a> </dd>
<dt>Paint.NET</dt>
<dd>Paint.NET is free image and photo editing software for Windows. We will use it to create textures for our game:<br />
<a href="http://www.getpaint.net/download.html" target="new">Download Paint.NET</a> </dd>
<dt>SoftImage Mod Tool</dt>
<dd>We will be using Autodesk SoftImage Mod Tool to create the 3D  models. The version we will use is for non-commercial use only which is  fine for this tutorial:<br />
<a href="http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&amp;id=13571320" target="new">Download Autodesk Softimage Mod Tool</a></dd>
</dl>
<h4>Feedback</h4>
<p>My name is Christian Schlager and I wrote this tutorial. If you like it,  have constructive feedback or found a mistake in the tutorial please  leave a comment here, or on my page: <a href="http://googoobachoo.blogspot.com/2010/08/rolling-world-tutorial.html" target="new">http://googoobachoo.blogspot.com</a></p>
<h2>Downloads</h2>
<p>This tutorial is accompanied by the following downloads:</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/WorldGame.zip">WorldGame.zip</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/RollingWorldGame.zip">RollingWorldGame.zip</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/Assets.zip">Assets.zip</a></p>
<h4>Next Page: Creating the assets</h4>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Article: Simple 3D Camera in XNA</title>
		<link>http://www.sgtconker.com/2010/09/article-simple-3d-camera-in-xna/</link>
		<comments>http://www.sgtconker.com/2010/09/article-simple-3d-camera-in-xna/#comments</comments>
		<pubDate>Sun, 05 Sep 2010 09:30:13 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1674</guid>
		<description><![CDATA[by Pete Street
How do I make a 3D camera?
This is the most common question I hear from people starting out with 3D game development.
There are many different types of possible cameras and various ways to achieve each of them.  The amount of unique camera samples available online, while some are more complicated than others, [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Pete Street</h4>
<p><strong>How do I make a 3D camera?</strong></p>
<p>This is the most common question I hear from people starting out with 3D game development.<br />
There are many different types of possible cameras and various ways to achieve each of them.  The amount of unique camera samples available online, while some are more complicated than others, can be daunting to those just beginning with 3D games.</p>
<p>Additionally, it’s frustrating and nearly impossible to combine two different samples without doing some serious hacking.<br />
My goal for this tutorial is to remove that frustration from 3D-beginners by providing a back-to-basics approach to three of the most common types of cameras used in games:</p>
<ul>
<li>a free camera</li>
<li>a chase camera</li>
<li>a orbit camera</li>
</ul>
<p><span id="more-1674"></span></p>
<p>The free camera will be able to yaw, pitch, and roll, and move in any direction.</p>
<p>The chase camera follows an object at a specified distance while also allowing for limited rolling and panning.</p>
<p>Finally, the orbit camera follows an object, can rotate any amount around it, and allows for limited rolling.</p>
<p>All three of these cameras are independent of one another and no other code relies on them.  This way, it’s easy to add your own cameras later or modify one of mine without worrying about it changing something else.<br />
The focus for this tutorial will be on simplicity and getting your camera running with as little code as possible.<br />
Interspersed with the code examples, I’ll do my best to thoroughly explain what is going on – however, feel free to skip right to the example at any time.<br />
If you already have a decent understanding of cameras or need help on something specific, the code is structured such that, once the controls are altered to fit your needs, you should be able to plug it right into your existing game.</p>
<p>This tutorial assumes a basic understanding of C#, XNA, vector math, and world matrices.  Nothing taught here is very complicated or math-heavy, but having an idea of how these work ahead of time will help.</p>
<p><strong>On to the Game!</strong></p>
<p>We’ll begin by starting a new XNA game project in Visual C#.  I’ve named my project “SimpleCamerasTutorial,” but you may name yours whatever you wish.<br />
Once your project is created, add the two .fbx models that I’ve included, “ConeModel” and “CubeModel,” to the Content folder.</p>
<p>These models are for demonstration purposes only, as you’ll probably want to use much better-looking art assets in your actual game.</p>
<p>Now that we have everything in the project up and running, it’s time to begin coding.</p>
<p><strong>The Basic Camera</strong></p>
<p>The first thing to do is to add a Camera class.  Right-click on your project and click Add ? Class, and name it “Camera.cs.”  Then add the following Using statements to the top of the class:</p>
<pre class="brush: csharp; title: ;">
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
</pre>
<p>Now we’ll begin to add the class-level variables to Camera.cs.  Type in the following fields:</p>
<pre class="brush: csharp; title: ;">
private Vector3 position;
private Vector3 target;
public Matrix viewMatrix, projectionMatrix;
</pre>
<p>These are the four variables that are absolutely necessary to a 3D camera.  Position is the 3D coordinate of the camera, and target is the 3D coordinate of where the camera is looking at.</p>
<p>The viewMatrix is the “eye” in 3D space, and it takes in the position, target, and an Up vector to determine the camera’s position, where it’s looking, and which way is up.</p>
<p>The up vector will become important once we implement roll in the camera.</p>
<p>Finally, the projectionMatrix determines the camera’s properties like field-of-view, aspect ratio, and what distance in front of the camera to draw.</p>
<p>In essence, the projection matrix takes the 3D data from the view matrix and transforms (or projects) it onto the 2D screen.<br />
The View Matrix will need to be updated any time we change either the position, target, or up vector, but the Projection Matrix only needs to be defined once.</p>
<p>Next, add the constructor to Camera.cs:</p>
<pre class="brush: csharp; title: ;">
public Camera()
{
    ResetCamera();
}
</pre>
<p>We’ll use the ResetCamera() method to define the initial values for the camera.  Here’s ResetCamera():</p>
<pre class="brush: csharp; title: ;">
public void ResetCamera()
{
    position = new Vector3(0, 0, 50);
    target = new Vector3();

    viewMatrix = Matrix.Identity;
    projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), 16 / 9, .5f, 500f);
}
</pre>
<p>As you can see, the default values are set for the position, target, view matrix, and projection matrix.<br />
We’ve set the position to 50 units in front of the origin, initialized the view matrix to a standard identity matrix, and set the projection matrix to standard values.<br />
The first parameter in the projection matrix is field-of-view, which is usually at 45 degrees.  Second is the aspect ratio, set to the 16:9 standard.<br />
The last two values in the projection matrix are the near plane and far plane, which are distances in front of the camera.<br />
The camera will only draw something if it is within these two boundaries.  The target vector isn’t initialized to any values yet, because it will always depend on what type of camera you are using.</p>
<p>Next we’ll add an Update () method which will be called every frame and a private method called UpdateViewMatrix() to re-calculate the view matrix, which will be called from Update():</p>
<pre class="brush: csharp; title: ;">
public void Update()
{
    UpdateViewMatrix();
}
private void UpdateViewMatrix()
{
    viewMatrix = Matrix.CreateLookAt(position, target, Vector3.Up);
}
</pre>
<p>UpdateViewMatrix() calculates a view matrix at the camera’s position, looking at the target, and with the standard up vector Vector3.Up using the Matrix.CreateLookAt() function.<br />
At the moment, the camera doesn’t move and its target and up vectors are fixed.  We’re starting out with the most basic form of a view matrix to make sure that it draws properly.<br />
Later, this this code will be used as a base to add functionality for all of our cameras.</p>
<p><strong>The Basic Game</strong></p>
<p>That’s all we need for a basic, stationary camera.  Now let’s move over to the Game1.cs class to make a sample to use the camera.  Add the following variables to the top of Game1.cs:</p>
<pre class="brush: csharp; title: ;">
Camera camera = new Camera();

Matrix cubeWorld;
Matrix coneWorld;

Model cubeModel;
Model coneModel;
</pre>
<p>In Initialize(), set both of the world matrices to their identities:</p>
<pre class="brush: csharp; title: ;">
protected override void Initialize()
{
    cubeWorld = Matrix.Identity;
    coneWorld = Matrix.Identity;

    base.Initialize();
}
</pre>
<p>Then in the LoadContent() method, load both of the models:</p>
<pre class="brush: csharp; title: ;">
protected override void LoadContent()
{
    cubeModel = Content.Load&lt;Model&gt;(&quot;CubeModel&quot;);
    coneModel = Content.Load&lt;Model&gt;(&quot;ConeModel&quot;);
}
</pre>
<p>In the Update() method, we’ll be updating the camera, and thus the camera’s view matrix:</p>
<pre class="brush: csharp; title: ;">
protected override void Update(GameTime gameTime)
{
    camera.Update();
}
</pre>
<p>Finally, let’s draw both of the models using a private method named DrawModel(), and call that method in Draw():</p>
<pre class="brush: csharp; title: ;">
protected override void Draw(GameTime gameTime)
{
    //Draws both models
    DrawModel(cubeModel, cubeWorld);
    DrawModel(coneModel, coneWorld);
}

private void DrawModel(Model model, Matrix worldMatrix)
{
    Matrix[] modelTransforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(modelTransforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = modelTransforms[mesh.ParentBone.Index] * worldMatrix;
            effect.View = camera.viewMatrix;
            effect.Projection = camera.projectionMatrix;
        }
        mesh.Draw();
    }
}
</pre>
<p>The DrawModel() method takes in a model and its world matrix.  If the model has multiple bones or many complex parts, this method then breaks them down to modelMeshes in order to be drawn with an effect.  BasicEffect draws the scene here, but if you have a custom effect then feel free to use that instead.  We have enabled the default lighting inside BasicEffect so there is shading on the model and not just an ambient light.  The effect takes the world matrix of the model, and then the camera’s view and projection matrices.  At this point, both the cone and the cube model should be set up and displayed correctly using the view and projection matrices from the camera.  Press ‘F5’ to ensure that everything is working properly – you should see the front face of the cube with a cone sticking out of the top.</p>
<p>If everything looks correct, we can move on and make the cube a little more interesting with movement and rotation.</p>
<p><strong>Finishing the Game Sample</strong></p>
<p>We’ll now finish off the game sample to go along with the Camera class by adding rotation and movement to the cube.  The cone will remain at the origin and serve as a point of reference, so we won’t need any fancy environments in order to know if the cube is moving.  We already have the cube’s world matrix set up, and all we have to do is change it in Update().</p>
<p>Type the following code in the Update() method of Game1.cs:</p>
<pre class="brush: csharp; title: ;">
protected override void Update(GameTime gameTime)
{
	KeyboardState keyBoardState = Keyboard.GetState();

	//Rotate Cube along its Up Vector
	if (keyBoardState.IsKeyDown(Keys.X))
	{
		cubeWorld = Matrix.CreateFromAxisAngle(Vector3.Up, .02f) * cubeWorld;
	}
	if (keyBoardState.IsKeyDown(Keys.Z))
	{
		cubeWorld = Matrix.CreateFromAxisAngle(Vector3.Up, -.02f) * cubeWorld;
	}

	//Move Cube Forward, Back, Left, and Right
	if (keyBoardState.IsKeyDown(Keys.Up))
	{
		cubeWorld *= Matrix.CreateTranslation(cubeWorld.Forward);
	}
	if (keyBoardState.IsKeyDown(Keys.Down))
	{
		cubeWorld *= Matrix.CreateTranslation(cubeWorld.Backward);
	}
	if (keyBoardState.IsKeyDown(Keys.Left))
	{
		cubeWorld *= Matrix.CreateTranslation(-cubeWorld.Right);
	}
	if (keyBoardState.IsKeyDown(Keys.Right))
	{
		cubeWorld *= Matrix.CreateTranslation(cubeWorld.Right);
	}
}
</pre>
<p>First, we use the ‘Z’ and ‘X’ keys to call Matrix.CreateFromAxisAngle().  This function rotates the cube along the standard up vector by .02 radians every frame.  Then we move the cube using the arrow keys.  Matrix.CreateTranslation() translates a world matrix by a vector.  Instead of using standard vectors like Vector3.Forward, the vectors are taken directly from the cube’s world matrix.  This way if we rotated the cube, all of its vectors rotated with it, and the cube moves whatever direction it’s facing rather than straight forward, back, left, and right.  Press ‘F5’ again, and you should be able to rotate the cube and move it around.</p>
<p><strong>The Free Camera</strong></p>
<p>Now that we’ve finished with the basic game sample, we can work on the camera’s code, beginning with a 6-degrees-of-freedom camera.  In Camera.cs, add the following variables and initialize them in ResetCamera():</p>
<pre class="brush: csharp; title: ;">
private float yaw, pitch, roll;
private float speed;
private Matrix cameraRotation;

public void ResetCamera()
{
    yaw = 0.0f;
    pitch = 0.0f;
    roll = 0.0f;

    speed = .3f;

	cameraRotation = Matrix.Identity;
}
</pre>
<p>cameraRotation is the matrix we’ll be using to rotate the camera.  Yaw, pitch, and roll are angles that will be passed in to cameraRotation, and speed is how fast the camera will move.  Next, add a private method named HandleInput(), and call it in the Update() method:</p>
<pre class="brush: csharp; title: ;">
public void Update()
{
    HandleInput();
	UpdateViewMatrix();
}

private void HandleInput()
{
	KeyboardState keyboardState = Keyboard.GetState();

	if (keyboardState.IsKeyDown(Keys.J))
	{
		yaw += .02f;
	}
	if (keyboardState.IsKeyDown(Keys.L))
	{
		yaw += -.02f;
	}
	if (keyboardState.IsKeyDown(Keys.I))
	{
		pitch += -.02f;
	}
	if (keyboardState.IsKeyDown(Keys.K))
	{
		pitch += .02f;
	}
	if (keyboardState.IsKeyDown(Keys.U))
	{
		roll += -.02f;
	}
	if (keyboardState.IsKeyDown(Keys.O))
	{
		roll += .02f;
	}

	if (keyboardState.IsKeyDown(Keys.W))
	{
		MoveCamera(cameraRotation.Forward);
	}
	if (keyboardState.IsKeyDown(Keys.S))
	{
		MoveCamera(-cameraRotation.Forward);
	}
	if (keyboardState.IsKeyDown(Keys.A))
	{
		MoveCamera(-cameraRotation.Right);
	}
	if (keyboardState.IsKeyDown(Keys.D))
	{
		MoveCamera(cameraRotation.Right);
	}
	if (keyboardState.IsKeyDown(Keys.E))
	{
		MoveCamera(cameraRotation.Up);
	}
	if (keyboardState.IsKeyDown(Keys.Q))
	{
		MoveCamera(-cameraRotation.Up);
	}
}
</pre>
<p>Finally, we put in another private method called MoveCamera():</p>
<pre class="brush: csharp; title: ;">
private void MoveCamera(Vector3 addedVector)
{
	position += speed * addedVector;
}
</pre>
<p>HandleInput() will take care of both the camera’s rotation and movement based on manual keyboard input (remember, this is just a sample, so you’re free to change the controls to whatever you like).  Currently, the camera’s yaw is controlled by ‘J’ and ‘L,’ pitch is controlled by ‘I’ and ‘K,’ and roll is<br />
controlled by ‘U’ and ‘O.’  Similarly, the camera’s movement is mapped to ‘E’ and ‘Q’ moving up and down, ‘W’ and ‘S’ moving forward and back, and ‘D’ and ‘A’ moving left and right.</p>
<p>The MoveCamera() method alters the camera’s position in any direction at the camera’s speed.  We use vectors from the rotation matrix instead of standard vectors like Vector3.Forward so if the camera is rotated at all, it will move in the direction that it’s facing.  If you run the project right now, you should be able to move the camera around using the WASD + EQ keys, but you won’t be able to rotate the camera and it will always look at the same point.  This is because cameraRotation isn’t affected by the yaw, pitch, and roll angles yet.  To fix that, add the following code to the UpdateViewMatrix() method before you calculate the view matrix:</p>
<pre class="brush: csharp; title: ;">
cameraRotation.Forward.Normalize();
cameraRotation.Up.Normalize();
cameraRotation.Right.Normalize();

cameraRotation *= Matrix.CreateFromAxisAngle(cameraRotation.Right, pitch);
cameraRotation *= Matrix.CreateFromAxisAngle(cameraRotation.Up, yaw);
cameraRotation *= Matrix.CreateFromAxisAngle(cameraRotation.Forward, roll);

yaw = 0.0f;
pitch = 0.0f;
roll = 0.0f;

target = position + cameraRotation.Forward;

viewMatrix = Matrix.CreateLookAt(position, target, cameraRotation.Up);
</pre>
<p>I make it a habit to normalize all the camera vectors that I’ll be using, and it’s really just a safeguard in case I accidentally edited it elsewhere.  The first three lines of code normalize three of cameraRotation’s vectors, as those are the vectors that the camera will rotate around.  The next three lines multiply cameraRotation by the Matrix.CreateFromAxisAngle() function, which rotates the matrix around any vector by a certain angle.  We rotate the matrix around its own vectors so that it works properly no matter how it’s rotated already.  After the matrix is rotated, the yaw, pitch, and roll values are set back to zero.  Finally, the target is changed to accommodate the rotation matrix.  It is set at the camera’s position, and then cameraRotation’s forward vector is added to it.  This ensures that the camera is always looking in the direction of the forward vector, no matter how it’s rotated.  Finally, we calculate the view matrix.  The only change we made in this line is the last parameter – now the up vector is based on how the camera is rotated and not off the standard Vector3.Up.  The view matrix needs an up vector to fully orient itself in 3D space, otherwise, the camera would have no way of knowing whether or not it’s upside-down.</p>
<p>Once this code is added, press ‘F5’ to run the program.  Hooray!  You should now have a free camera capable of moving in any direction, rotating in any direction, and independent of the cube!</p>
<p><strong>Expanding the Camera’s Horizons</strong></p>
<p>Now that we have a working free camera and the base of the Camera class, let’s make the class expandable so we can easily add new cameras in the future.  Later, it will be simple to add the chase and orbit cameras, and any other cameras that you might come up with.  To have multiple cameras within the same class, we’ll need an enum to keep track of which mode the camera is currently in.  Add this code to the top of the Camera class:</p>
<pre class="brush: csharp; title: ;">
public enum CameraMode
{
	free = 0,
	chase = 1,
	orbit = 2
}
public CameraMode currentCameraMode = CameraMode.free;
</pre>
<p>The currentCameraMode will keep track of which camera mode is active.  Right now, we only have the code for a free camera, so that is what we’ll set it to.</p>
<p>We also need to change the camera movement code in the HandleInput() method to make sure that it’s only run if the free camera is the current camera mode.  The reason for this is the chase and orbit cameras’ positions don’t have their own movement code, and instead use the movement of an outside object.  In HandleInput(), simply check if the free camera is currently active around the camera’s movement code:</p>
<pre class="brush: csharp; title: ;">
private void HandleInput()
{
	//Camera’s Rotation code

	if (currentCameraMode == CameraMode.free)
	{
		//Camera’s Movement code.
	}
}
</pre>
<p>Then in UpdateViewMatrix(), place the code you just added for the free camera inside this switch block, keeping the view matrix calculation outside of it:</p>
<pre class="brush: csharp; title: ;">
switch (currentCameraMode)
{
	case CameraMode.free:

		//Free-camera code goes here.

		break;

	case CameraMode.chase:

		break;

	case CameraMode.orbit:

		break;
}

viewMatrix = Matrix.CreateLookAt(position, target, cameraRotation.Up);
</pre>
<p>The goal is to keep all of the code simple, concise, and reusable, and as such the view matrix calculation should never change.  Only the parameters it takes in should change.</p>
<p><strong>The Chase Camera</strong></p>
<p>Now it’s time to add the chase camera’s code.  Add the following variables to the top of the Camera class and initialize them in the ResetCamera() method:</p>
<pre class="brush: csharp; title: ;">
private Vector3 desiredPosition;
private Vector3 desiredTarget;
private Vector3 offsetDistance;

public void ResetCamera()
{
	desiredPosition = position;
	desiredTarget = target;

	offsetDistance = new Vector3(0, 0, 50);
}
</pre>
<p>The desired position and target will be used in conjunction with the actual position and target so we can get smooth transitions.  A value that’s “desired” is what the actual values will constantly move to, but they don’t necessarily need to be equal to the desired value.  The offset distance is how far displaced the camera is from the target.  For both the chase and orbit cameras, the target won’t be defined by a vector in the rotation matrix, but rather by an outside object’s position – in this case, the target will be defined by the position of the cube.  We’re going to add a matrix parameter to the Camera’s Update() method, and pass that matrix into the UpdateViewMatrix() method.  In the game, we’ll pass the cube’s world matrix into camera.Update() in order to set that matrix as the one to chase.  First change the Camera’s Update() and UpdateViewMatrix() methods like so:</p>
<pre class="brush: csharp; title: ;">
public void Update(Matrix chasedObjectsWorld)
{
	UpdateViewMatrix(chasedObjectsWorld);
}

private void UpdateViewMatrix(Matrix chasedObjectsWorld)
{
}
</pre>
<p>Then in Game1.cs, change camera.Update() to camera.Update(cubeWorld).  Now we have a target to chase that isn’t dependent upon the camera’s code.  Finally, for the actual chase camera’s code, add the following to the chase camera section of the switch block inside UpdateViewMatrix():</p>
<pre class="brush: csharp; title: ;">
case CameraMode.chase:

	cameraRotation.Forward.Normalize();
	chasedObjectsWorld.Right.Normalize();
	chasedObjectsWorld.Up.Normalize();

	cameraRotation = Matrix.CreateFromAxisAngle(cameraRotation.Forward, roll);

	desiredTarget = chasedObjectsWorld.Translation;
	target = desiredTarget;
	target.X += yaw;
	target.Y += pitch;

	desiredPosition = Vector3.Transform(offsetDistance, chasedObjectsWorld);
	position = Vector3.SmoothStep(position, desiredPosition, .15f);

	yaw = MathHelper.SmoothStep(yaw, 0f, .1f);
	pitch = MathHelper.SmoothStep(pitch, 0f, .1f);
	roll = MathHelper.SmoothStep(roll, 0f, .2f);

	break;
</pre>
<p>In this chase camera, I’ve allowed for a limited amount of yaw, pitch, and roll.  This is to ensure that the camera always follows the target, but it will still have some degree of freedom on where to look.  The first thing we do is normalize the rotation matrix’s forward vector because we’ll be using that vector to roll around.  Notice that we don’t alter the rotation matrix with yaw and pitch like we did in the free camera.  That’s because this camera’s yaw and pitch will depend on the target (not the rotation matrix), and that’s where desiredTarget comes in.  Each frame, desiredTarget will be set to the position of whatever object we’re chasing (in this case the cube).  We then set the actual target equal to the desiredTarget, and we can change the target’s X and Y coordinates at will.  The yaw and pitch angles work well for this, as we can alter the target’s X to look a little left and right, and alter the target’s Y to look a little up and down.</p>
<p>Next we set the camera’s desiredPosition.  The desired position could simply be set by adding the offset distance to the target, but what if the object we’re chasing rotates?  Since we always want the camera positioned behind the object, desiredPosition needs to be transformed by the chased object’s world matrix.</p>
<p>Finally, we need to smooth the camera’s movement and transition the target vector back to the desired target.  This is done with the SmoothStep() functions, which take in the current value, a desired value, and the factor that the current value is changed by.  Using these methods, the position smoothly moves to desiredPosition, and the angles on which the camera rolls and pans on are constantly being moved back to zero.</p>
<p>At the top of Camera.cs, change currentCameraMode = CameraMode.free to currentCameraMode = CameraMode.chase.  Now that the camera is in chase mode, you can run the project to ensure the chase camera works properly.  You should be able to move and rotate the cube, and the camera should follow it smoothly.  You can also pan the camera up, down, left, and right using the IJKL keys.  In HandleInput(), you may want to increase the yaw and pitch values in order to make the camera panning more prominent, but you should be able to see the effect either way.</p>
<p>One fluke that you may notice after playing around with the chase camera is when you pan left or right and rotate the cube at the same time.  You’ll see that the cube seems to be moving back and forth across your screen.  The reason this happens has to do with how we define the target.  Right now only the target’s X and Y coordinates are being edited, so it behaves much like a flat plane.  When the camera rotates to the side of that flat plane, all of the points will appear to be in the center of the screen.  As the camera rotates around it, the points in the plane will look like they’re inverted.  Depending on the game, this may be a rather serious problem.  Fortunately, it comes with a very simple solution, which is to multiply certain vectors in the chased object’s world matrix by the rotation angles so the target rotates with the cube.  In UpdateViewMatrix(), replace these two lines:</p>
<pre class="brush: csharp; title: ;">
target.X += yaw;
target.Y += pitch;
</pre>
<p>…with these lines:</p>
<pre class="brush: csharp; title: ;">
target += chasedObjectsWorld.Right * yaw;
target += chasedObjectsWorld.Up * pitch;
</pre>
<p>Run the project again.  You should be able to pan to the side and rotate the cube at the same time, and the target will rotate along with it.</p>
<p><strong>The Orbit Camera</strong></p>
<p>It’s now time to put the orbit camera in place.  This will be especially easy to do since we already have all the necessary base code.  We don’t need any more variables, but change the currentCameraMode at the top of the class to CameraMode.orbit.  In UpdateViewMatrix(), inside the orbit section of the switch block, add the following code:</p>
<pre class="brush: csharp; title: ;">
case CameraMode.orbit:

cameraRotation.Forward.Normalize();

cameraRotation = Matrix.CreateRotationX(pitch) * Matrix.CreateRotationY(yaw) * Matrix.CreateFromAxisAngle(cameraRotation.Forward, roll);

desiredPosition = Vector3.Transform(offsetDistance, cameraRotation);
desiredPosition += chasedObjectsWorld.Translation;
position = desiredPosition;

target = chasedObjectsWorld.Translation;

roll = MathHelper.SmoothStep(roll, 0f, .2f);

break;
</pre>
<p>We start out by normalizing the rotation matrix’s forward vector, and then cameraRotation is calculated.  The camera rolls using the same code that we’ve done in the past, rotating the matrix over its forward vector.  What has changed is how the matrix takes in the yaw and pitch angles.  Instead of yawing and pitching over cameraRotation’s vectors, we yaw and pitch over the world axes.  By rotating over world axes instead of local axes, the orbiting effect is achieved.  Next we transform the camera’s position by the offset distance and rotation matrix, much like what happened in the chase camera.  At this point, the camera will orbit around the origin, but it won’t follow the cube if it moves.  This is why the cube’s position is added to desiredPosition, so it will follow the cube and orbit around it no matter where it is.  Since the target will always stay at the center of the cube, it is set to the cube’s position.  Finally, the roll is smoothly brought back to zero.</p>
<p>Unlimited roll is not allowed in this sample for two reasons:  1) it’s disorienting and doesn’t look good, and 2) it can cause some stability issues.  Because of floating-point precision, more roll than what we have right now will cause the camera to lose control and the game will become unplayable.  However, as long as the amount of roll is contained, the camera is perfectly stable.</p>
<p>That’s all you need for the orbit camera!  Run the game now and you should be able to move the cube and rotate around it.  Something you may notice about the orbit camera’s code is that this line:</p>
<pre class="brush: csharp; title: ;">
position = desiredPosition;
</pre>
<p>…seems redundant.  The reason I don’t simply transform the position is because you may want to add a SmoothStep() function to it like I did in the chase camera.  I opted to leave it out of this sample, but you’re free to add it to your own code.</p>
<p><strong>Touching Up</strong></p>
<p>Congratulations!  You made it through all the basic camera examples with (hopefully) little heartache.  All there is left is to add a simple method to allow for easy switching between cameras.  Add a public method named SwitchCameraMode() to Camera.cs:</p>
<pre class="brush: csharp; title: ;">
public void SwitchCameraMode()
{
	ResetCamera();

	currentCameraMode++;

	if ((int)currentCameraMode &gt; 2)
	{
		currentCameraMode = 0;
	}
}
</pre>
<p>It’s a pretty simple method that loops through the camera modes.  First, all of the camera’s default values are reset, then it cycles through the entire camera modes list.  If you happen to add more camera modes in the future, just change the ‘2’ in this line:</p>
<pre class="brush: csharp; title: ;">
if ((int)currentCameraMode &gt; 2)
</pre>
<p>…to the highest number in the enum at the top of the class.  This method will be called in the game class, so head over to Game1.cs and type this line in the top of the class:</p>
<pre class="brush: csharp; title: ;">
KeyboardState previousKeyBoardState = Keyboard.GetState();
</pre>
<p>Now simply add the following code to Update():</p>
<pre class="brush: csharp; title: ;">
protected override void Update(GameTime gameTime)
{
	if (keyBoardState.IsKeyDown(Keys.Space) &amp;&amp; previousKeyBoardState.IsKeyUp(Keys.Space))
	{
		camera.SwitchCameraMode();
	}

	//This line should be at the bottom of Update()
	//after all of the input code.
	previousKeyBoardState = keyBoardState;

}
</pre>
<p>That’s it!  You now have a simple, working sample with three distinct camera modes which you can change on-the-fly.</p>
<p><strong>The Next Step</strong></p>
<p>This tutorial contains simple examples of what you can do with 3D cameras.  Everything is reliable and designed to be easy to use, but it’s also somewhat primitive.  Using these examples as a launch pad, you can improve the cameras by adding more sophisticated functions to them.  For instance, most chase camera samples (including the one in XNA’s education catalog) use a physics-based spring system for smoothly updating the position.  We faked a spring by using the SmoothStep() functions, but if you need something more advanced, you might consider making one yourself.</p>
<p>You may also want to make different types of cameras.  These three examples are among the most common in games and can be adapted to fill many needs, but if your needs aren’t met, then you have the base code to easily make a different camera.</p>
<p>If you want to save fiddling with your camera for later and want to get started with the game right now, this sample is easy to integrate with your game.  All you have to do is add the camera class to your own game project, and initiate and update the camera in the game as I’ve shown above.  Right out of the box, you’ll have three different cameras to use for developing your game.</p>
<p><strong>Closing Words</strong></p>
<p>Throughout this tutorial, I’ve made an effort to keep everything simple and to explain all of the code in detail.  Again, my goal is to give people starting out with 3D an easy-to-understand introduction into 3D cameras.  This will hopefully curb some of the frustration that comes out of learning something new, and will allow you to focus on the rest of your game more quickly and easily.  Thanks for reading, and keep making games that are absolutely fine!</p>
<p><a href="http://www.sgtconker.com/Downloads/articles/SimpleCamerasTutorial.zip">Download Sample Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-simple-3d-camera-in-xna/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>IcoModel Beta</title>
		<link>http://www.sgtconker.com/2010/08/icomodel-beta/</link>
		<comments>http://www.sgtconker.com/2010/08/icomodel-beta/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 05:53:51 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Beta]]></category>
		<category><![CDATA[CodePlex]]></category>
		<category><![CDATA[IcoModel]]></category>
		<category><![CDATA[Sphere]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1592</guid>
		<description><![CDATA[A new interesting project popped-up on codeplex. Daniel Hoctor released the first beta version of IcoModel. The original announcement on the xna forums explains what IcoModel is all about:
What is IcoModel?
IcoModel is a free, open source terrain system that provides an easy way to create and manage dynamic terrain in the form of a globe. [...]]]></description>
			<content:encoded><![CDATA[<p>A new interesting project popped-up on codeplex. Daniel Hoctor released the first beta version of <a href="http://icomodel.codeplex.com/">IcoModel</a>. The original announcement on the xna forums explains what IcoModel is all about:</p>
<blockquote><p><strong>What is IcoModel?</strong><br />
IcoModel is a free, open source terrain system that provides an easy way to create and manage dynamic terrain in the form of a globe. The IcoModelProcessor has been designed specifically to work with geodesic spheres; the mesh is broken down into sectors--the pentagons and hexagons that make up the sphere--which the IcoModel class uses to manage the terrain.</p>
<p><strong>How does it work?</strong><br />
You simply load a non-textured, UV Mapped, geodesic sphere mesh via the IcoModelProcessor. Then you create an effect key that represents the different terrain types in your project. From that point on, you can assign any sector an effect key index, at any time. When you call IcoModel's draw function, each sector will be drawn according to its current effect key index.</p></blockquote>
<p>You can see a video of IcoModel at work below:</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/XRu_mb6wXVo?fs=1&amp;hl=en_US&amp;rel=0" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/XRu_mb6wXVo?fs=1&amp;hl=en_US&amp;rel=0" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p>P.S. Thanks to Mike (Bob Taco Ind) for the tip!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/08/icomodel-beta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article : Sun- and Lens Flare as a Post Process</title>
		<link>http://www.sgtconker.com/2010/04/article-sun-and-lens-flare-as-a-post-process/</link>
		<comments>http://www.sgtconker.com/2010/04/article-sun-and-lens-flare-as-a-post-process/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 12:12:01 +0000</pubDate>
		<dc:creator>NemoKrad</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[MVP Watch]]></category>
		<category><![CDATA[Post Processing]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Blacksun]]></category>
		<category><![CDATA[Charles Humphrey]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Lens flare]]></category>
		<category><![CDATA[Post Process]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1407</guid>
		<description><![CDATA[by ]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="<a href="http://xna-uk.net/blogs/randomchaos/">Charles Humphrey</a></h4>
<p><img class="alignright" src="http://sgtconker.com/wp-content/uploads/2010/04/sunpostprocess.png" alt="" width="264" height="206" /></p>
<p>Now this sample has come from my current XNA toy which is the Blacksun engine I am currently writing in XNA 3.1. It uses deferred lighting, instancing and a post processing framework that I found on a great site <a href="http://graphicsrunner.blogspot.com/2008/06/post-process-framework-sample.html">here</a>, all I had to do was make it engine ready.</p>
<p>If you want to have a look at the effect in the engine you can see it <a href="http://www.youtube.com/watch?v=DrhF2Bp-95I">here</a>.</p>
<p>This sample is just one of the elements from the post processing framework in the engine, there are none of the other goodies in this sample, just the Sun post process. This sample has also been created using the XNA 4.0 CTP, so I only had one render target to work with at the time. This means that you can't see the sun being culled behind objects in the scene as I can't create a depth map as well as the rendered scene, to be honest, I still don't have that bit of the shader 100% anyway <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><span id="more-1407"></span></p>
<p>So, what do you get in this sample, well, the sun shader and the lens flare effect all in one post process and done in XNA 4.0. It's a pretty simple effect really, taking the suns position in the world, then just finding its screen coordinates on the render target and render the sun flare texture, then render the texture again over a set of offset texture coordinates to give the lens flare effect.</p>
<p>Lets take a look at the code...</p>
<p><strong>Sun.fx</strong></p>
<p>We have a few variables we can pass to the shader to control this effect, the names I hope are quite self explanatory, well most of them</p>
<pre class="brush: csharp; title: ;">
float3 cameraPosition;

float SunSize = 1500;

float Density = 3;
float Exposure = -.1;
float Weight = .25;
float Weight2 = .125;
float Decay = .5;

float3 lightPosition;

float lightIntensity = 10.0f;
float3 Color = float3(1,1,1);

texture flare;
sampler Flare = sampler_state
{
    Texture = (flare);
    AddressU = CLAMP;
    AddressV = CLAMP;
};

sampler BackBuffer : register(s0);

//depth
texture depthMap;
sampler depthSampler = sampler_state
{
    Texture = (depthMap);
};

struct VertexShaderInput
{
    float3 Position : POSITION0;
    float2 texCoord : TEXCOORD0;
};

struct VertexShaderOutputToPS
{
    float2 texCoord : TEXCOORD0;
};
</pre>
<p>Those that I guess are not that obvious are Density to Decay and these relate the the lens flare part of the shader and control the number of texture samples to display, density of those samples etc..</p>
<p>So onto the lane flare function that is used in the shader to give the lens flare effect.</p>
<pre class="brush: csharp; title: ;">
float4 DoLenseFlare(float4 ScreenLightPosition,float2 texCoord,bool fwd)
{
    // Calculate vector from pixel to light source in screen space.
    float2 deltaTexCoord = (texCoord - ScreenLightPosition.xy);// Divide by number of samples and scale by control factor.
    deltaTexCoord *= 1.0f / 3 * Density;

    // Store initial sample.
    float3 color = 0;

    // Set up illumination decay factor.
    float illuminationDecay = 1.0f;

    for (int i = 0; i &amp;lt; 3 ; i++)
    {
        // Step sample location along ray.
        if(fwd)
            texCoord -= deltaTexCoord;
        else
            texCoord += deltaTexCoord;

        // Retrieve sample at new location.
        float3 sample = tex2D(Flare, texCoord);

        // Apply sample attenuation scale/decay factors.
        if(fwd)
            sample *= illuminationDecay * Weight;
        else
            sample *= illuminationDecay * Weight2;

        // Accumulate combined color.
        color += sample;

        // Update exponential decay factor.
        illuminationDecay *= Decay;
    }

    return float4(color,1);
}
</pre>
<p>I can take very little credit for this bit of the code, as I got it from GPU Game 3 Chapter 13 Volumetric Light Scattering as a Post Process, not exactly using it as it was intended, but is does the job I wanted here well enough <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So the pixel shader itself that pulls this all together looks like this</p>
<pre class="brush: csharp; title: ;">
float4 PixelShaderFunction(VertexShaderOutputToPS input) : COLOR0
{
    // Get the scene
    float4 col = tex2D(BackBuffer,input.texCoord);// Find the suns position in the world and map it to the screen space.
    float4 ScreenPosition = mul(lightPosition - cameraPosition,VP);
    float scale = ScreenPosition.z;
    ScreenPosition.xyz /= ScreenPosition.w;
    ScreenPosition.x = ScreenPosition.x/2.0f+0.5f;
    ScreenPosition.y = (-ScreenPosition.y/2.0f+0.5f);

    // get the depth from the depth map
    //float depthVal = 1- tex2D(depthSampler, input.texCoord).r;

    // Are we lokoing in the direction of the sun?
    if(ScreenPosition.w &gt; 0)
    {
        float2 coord;

        float size = SunSize / scale;

        float2 center = ScreenPosition.xy;

        coord = .5 - (input.texCoord - center) / size * .5;

        //if(depthVal &gt; ScreenPosition.z-.0003)
        col += (pow(tex2D(Flare,coord) * float4(Color,1),2) * lightIntensity) * 2;

        // Lens flare
        col += ((DoLenseFlare(ScreenPosition,input.texCoord,true) + DoLenseFlare(ScreenPosition,input.texCoord,false)) * float4(Color,1) * lightIntensity) * 5;
    }

    return col;
}
</pre>
<p>You will see in here that I have left in the code for detecting the depth of objects in the scene for sun culling and just commented it out, when you have a full release XNA 4.0 you will be able to create and pass in the depth map, but it’s not possible in the current CTP.</p>
<p>So what am I doing in the pixel shader, first off we grab the current scene’s color, I then get the position of the light in screen space by multiplying its position by the camera position and then doing the homogeneous divide (ScreenPosition.xyz / ScreenPosition.w) to get the position of the sun (see the Get2DCoords method below for my inspiration for this). Then, if we are looking in the direction of the sun (ScreenPosition.w &gt; 0) then we need to render the sun and or lens flare. I then calculate the size of the sun and find the tex coords required to get the texture from the Flare sampler and then add this with the sun color and raise it to the power of 2, this lightens the light bits and darkens the dark bits, this is then multiplied by the light intensity and the final values doubled again. Then we come to the lens flare, I call this twice: once for each direction of the flare (you will see in the clip there are two) and again tint this to the sun color and multiply by intensity.</p>
<p>Now please feel free to pick my dodgy math’s apart here I know I suck, but it is working and I have not thought much more abut it since writing it <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><strong>Game Code</strong></p>
<p>First thing we will do is set up a render target and and effect so we can apply our sun as a post process.</p>
<pre class="brush: csharp; title: ;">
RenderTarget2D rt;
Effect effect;
</pre>
<p>Also some way of representing the sun’s position, color intensity and size</p>
<pre class="brush: csharp; title: ;">
Vector3 sunPosition = new Vector3(100, 200, -1000);
Color sunColor = Color.White;
float sunIntensity = 1f;
float sunSunSize = 1500;
</pre>
<p>Now we have these variable lined up and ready to use we can initialize both the render target and the effect shader</p>
<pre class="brush: csharp; title: ;">
rt = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

effect = Content.Load&lt;Effect&gt;(&quot;Shaders/PostProcessing/Sun&quot;);
effect.Parameters[&quot;flare&quot;].SetValue(Content.Load&lt;Texture2D&gt;(&quot;Textures/PostProcessing/flare&quot;));
effect.Parameters[&quot;Color&quot;].SetValue(sunColor.ToVector3());
effect.Parameters[&quot;lightIntensity&quot;].SetValue(sunIntensity);
effect.Parameters[&quot;SunSize&quot;].SetValue(sunSunSize);
effect.Parameters[&quot;lightPosition&quot;].SetValue(sunPosition);
</pre>
<p>Now we need to make sure the shader/effect is updated with the required variables. So in our update method we set the following parameters</p>
<pre class="brush: csharp; title: ;">
effect.Parameters[&quot;VP&quot;].SetValue(camera.View * camera.Projection);
effect.Parameters[&quot;cameraPosition&quot;].SetValue(camera.Position);
//effect.Parameters[&quot;depthMap&quot;].SetValue(depthBuffer);
</pre>
<p>And now for the render, keep in mind that this is all done just for this sample, you will want to encapsulate all this in its own class deriving from DrawableGameComponent or in a post processing framework as shown in the link above.</p>
<pre class="brush: csharp; title: ;">
    GraphicsDevice.SetRenderTargets(rt);
    GraphicsDevice.Clear(&lt;Color.Black);
    base.Draw(gameTime);

    // Post Processing.
    GraphicsDevice.SetRenderTargets(null);

    GraphicsDevice.Textures[0] = rt;
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
    effect.Techniques[0].Passes[0].Apply();
    spriteBatch.Draw(rt, new Rectangle(0, 0, rt.Width, rt.Height), Color.White);
    spriteBatch.End();
</pre>
<p>So, we setup the render target, allow the scene to be drawn (nothing gets drawn in this sample), then we resolve the render target and then apply our effect to the newly captured render target.</p>
<p>As mentioned earlier I have a method I use to get screen coordinates from a 3D screen position, this method I am 99% sure I got (or at least the nuts and bolts of it) from Rocket Commander which was written by <a href="http://exdream.com/Games/Default.aspx?Game=RocketCommander&amp;Category=Open%20Source">Benjamin Nitsche</a></p>
<pre class="brush: csharp; title: ;">
public Vector2 Get2DCoords(Vector3 myPosition, Base3DCamera Camera)
{
    Matrix ViewProjectionMatrix = Camera.View * Camera.Projection;
    Vector4 result4 = Vector4.Transform(myPosition, ViewProjectionMatrix);

    if(result4.W &lt;= 0)
        return new Vector2(Camera.Viewport.Width, 0);

    Vector3 result = new Vector3(result4.X / result4.W, result4.Y / result4.W, result4.Z / result4.W);

    Vector2 retVal = new Vector2((int)Math.Round(+result.X * (Camera.Viewport.Width / 2)) + (Camera.Viewport.Width / 2), (int)Math.Round(-result.Y * (Camera.Viewport.Height / 2)) + (Camera.Viewport.Height / 2));

    return retVal;
}
</pre>
<p>As you can see it transforms the position by the ViewProjection matrix to then get the screen position if the result4.W &gt;= 0.</p>
<p><a href="http://www.sgtconker.com/Downloads/articles/RandomchaosSunPostProcess.zip">Download the sample project here</a><br />
Well that’s abut it, and this is my first post on Sgt Conker, hope it’s not my last one <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  Hope you find this useful, if not in it’s own right, then I hope it gives you some ideas for your own shaders…..</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/04/article-sun-and-lens-flare-as-a-post-process/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

