This commit is contained in:
ejcoumans
2007-06-13 05:00:42 +00:00
parent 705e6df404
commit ee8322ae6b
273 changed files with 23899 additions and 1359 deletions

View File

@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace XnaDevRu.Demos
{
/// <summary>
/// First person camera component for the demos, rotated by mouse.
/// </summary>
public class Camera : GameComponent
{
private Matrix _view;
private Matrix _projection;
private Vector3 _position = new Vector3(130, 50, 30);
private Vector2 _angles = Vector2.Zero;
private int _widthOver2;
private int _heightOver2;
private float _fieldOfView = Microsoft.Xna.Framework.MathHelper.PiOver4;
private float _aspectRatio;
private float _nearPlaneDistance = 0.1f;
private float _farPlaneDistance = 1000.0f;
private MouseState _prevMouseState = new MouseState();
/// <summary>
/// Initializes new camera component.
/// </summary>
/// <param name="game">Game to which attach this camera.</param>
public Camera(Game game)
: base(game)
{
_widthOver2 = game.Window.ClientBounds.Width / 2;
_heightOver2 = game.Window.ClientBounds.Height / 2;
_aspectRatio = (float)game.Window.ClientBounds.Width / (float)game.Window.ClientBounds.Height;
UpdateProjection();
Mouse.SetPosition(_widthOver2, _heightOver2);
}
/// <summary>
/// Gets camera view matrix.
/// </summary>
public Matrix View { get { return _view; } }
/// <summary>
/// Gets or sets camera projection matrix.
/// </summary>
public Matrix Projection { get { return _projection; } set { _projection = value; } }
/// <summary>
/// Gets camera view matrix multiplied by projection matrix.
/// </summary>
public Matrix ViewProjection { get { return _view * _projection; } }
/// <summary>
/// Gets or sets camera position.
/// </summary>
public Vector3 Position { get { return _position; } set { _position = value; } }
/// <summary>
/// Gets or sets camera field of view.
/// </summary>
public float FieldOfView { get { return _fieldOfView; } set { _fieldOfView = value; UpdateProjection(); } }
/// <summary>
/// Gets or sets camera aspect ratio.
/// </summary>
public float AspectRatio { get { return _aspectRatio; } set { _aspectRatio = value; UpdateProjection(); } }
/// <summary>
/// Gets or sets camera near plane distance.
/// </summary>
public float NearPlaneDistance { get { return _nearPlaneDistance; } set { _nearPlaneDistance = value; UpdateProjection(); } }
/// <summary>
/// Gets or sets camera far plane distance.
/// </summary>
public float FarPlaneDistance { get { return _farPlaneDistance; } set { _farPlaneDistance = value; UpdateProjection(); } }
/// <summary>
/// Gets or sets camera's target.
/// </summary>
public Vector3 Target
{
get
{
Matrix cameraRotation = Matrix.CreateRotationX(_angles.X) * Matrix.CreateRotationY(_angles.Y);
return _position + Vector3.Transform(Vector3.Forward, cameraRotation);
}
set
{
Vector3 forward = Vector3.Normalize(_position - value);
Vector3 right = Vector3.Normalize(Vector3.Cross(forward, Vector3.Up));
Vector3 up = Vector3.Normalize(Vector3.Cross(right, forward));
Matrix test = Matrix.Identity;
test.Forward = forward;
test.Right = right;
test.Up = up;
_angles.X = -(float)Math.Asin(test.M32);
_angles.Y = -(float)Math.Asin(test.M13);
}
}
/// <summary>
/// Updates camera with input and updates view matrix.
/// </summary>
/// <param name="gameTime"></param>
public override void Update(GameTime gameTime)
{
if (Enabled)
{
ProcessInput((float)gameTime.ElapsedGameTime.Milliseconds / 30.0f);
UpdateView();
base.Update(gameTime);
}
}
private void ProcessInput(float amountOfMovement)
{
Vector3 moveVector = new Vector3();
KeyboardState keys = Keyboard.GetState();
if (keys.IsKeyDown(Keys.D))
moveVector.X += amountOfMovement;
if (keys.IsKeyDown(Keys.A))
moveVector.X -= amountOfMovement;
if (keys.IsKeyDown(Keys.S))
moveVector.Z += amountOfMovement;
if (keys.IsKeyDown(Keys.W))
moveVector.Z -= amountOfMovement;
Matrix cameraRotation = Matrix.CreateRotationX(_angles.X) * Matrix.CreateRotationY(_angles.Y);
_position += Vector3.Transform(moveVector, cameraRotation);
MouseState currentMouseState = Mouse.GetState();
if (currentMouseState.RightButton == ButtonState.Pressed && _prevMouseState.RightButton == ButtonState.Released)
{
Mouse.SetPosition(_widthOver2, _heightOver2);
}
else if (currentMouseState.RightButton == ButtonState.Pressed)
{
if (currentMouseState.X != _widthOver2)
_angles.Y -= amountOfMovement / 80.0f * (currentMouseState.X - _widthOver2);
if (currentMouseState.Y != _heightOver2)
_angles.X -= amountOfMovement / 80.0f * (currentMouseState.Y - _heightOver2);
if (_angles.X > 1.4) _angles.X = 1.4f;
if (_angles.X < -1.4) _angles.X = -1.4f;
if (_angles.Y > Math.PI) _angles.Y -= 2 * (float)Math.PI;
if (_angles.Y < -Math.PI) _angles.Y += 2 * (float)Math.PI;
Mouse.SetPosition(_widthOver2, _heightOver2);
}
_prevMouseState = currentMouseState;
}
private void UpdateProjection()
{
_projection = Matrix.CreatePerspectiveFieldOfView(_fieldOfView, _aspectRatio, _nearPlaneDistance, _farPlaneDistance);
}
private void UpdateView()
{
Matrix cameraRotation = Matrix.CreateRotationX(_angles.X) * Matrix.CreateRotationY(_angles.Y);
Vector3 targetPos = _position + Vector3.Transform(Vector3.Forward, cameraRotation);
Vector3 upVector = Vector3.Transform(Vector3.Up, cameraRotation);
_view = Matrix.CreateLookAt(_position, targetPos, upVector);
}
}
}

View File

@@ -0,0 +1,167 @@
//////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2007, Eric Lebetsamer (http://tehone.com) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights to //
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of //
// the Software, and to permit persons to whom the Software is furnished to do so, //
// subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in all copies //
// or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, //
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR //
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE //
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, //
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
//////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace XnaDevRu.Demos
{
/// <summary>
/// This is a <see cref="DrawableGameComponent"/> that is used to calculate and display the current framerate (FPS, FramesPerSecond) of the game.
/// </summary>
public class Framerate : DrawableGameComponent
{
private double _fps = 0;
private float _elapsedRealTime = 0;
private string _gameWindowTitle;
private ushort _updateFrequency = 1000;
private float _updateFrequencyRatio;
/// <summary>
/// The CurrentFramerate property represents the current frames per second (FPS) for the game.
/// </summary>
/// <value>The CurrentFramerate property gets the <see cref="_fps"/> data member.</value>
public double CurrentFramerate
{
get
{
return _fps;
}
}
/// <summary>
/// The UpdateFrequency property represents, in milliseconds, how often we are updating the <see cref="_fps"/> count.
/// </summary>
/// <value>The UpdateFrequency property gets/sets the <see cref="_updateFrequency"/> data member.</value>
/// <remarks>
/// This is used to set how often we are calculating the frames per second count.
/// <para>The default value is <b><c>1000</c></b>.</para>
/// </remarks>
/// <exception cref="System.ArgumentOutOfRangeException">This exception will be thrown when the <b><c>value</c></b> is set less then <b><c>100</c></b> or when <b><c>value</c></b> is not divisible by <b><c>100</c></b>.</exception>
public ushort UpdateFrequency
{
get
{
return _updateFrequency;
}
set
{
if(value % 100 != 0 || value < 100)
throw new ArgumentOutOfRangeException("UpdateFrequency", value, "The UpdateFrequency for the Framerate must is based on milliseconds and must be must be a positive number that is greater then or equal to 100, and the number must be divisable by 100.");
_updateFrequency = value;
// Figure out the new ratio, this way we are reporting the correct frames per second even when we are not calculating ever second.
_updateFrequencyRatio = 1000 / (float)_updateFrequency;
}
}
/// <summary>
/// The main constructor for the class.
/// </summary>
/// <param name="game">The <see cref="Microsoft.Xna.Framework.Game" /> instance for this <see cref="DrawableGameComponent"/> to use.</param>
/// <remarks>Sets the <see cref="_gameWindowTitle"/> data member to the value of <see cref="Microsoft.Xna.Framework.GameWindow.Title"/>.</remarks>
public Framerate(Game game) : base(game)
{
// Save the original game window title
_gameWindowTitle = game.Window.Title;
// We are basing the ratio on 1 second (1000 milliseconds)
_updateFrequencyRatio = 1000 / (float)_updateFrequency;
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (!this.Enabled)
return;
// The total real time in milliseconds since the last Update().
float elapsed = (float)gameTime.ElapsedRealTime.TotalMilliseconds;
// Adds the Update() elapsed real time to the cumulative elapsed real time.
_elapsedRealTime += elapsed;
// If the elapsed time is greater than our update frequency then: calculate the framerate, and reduce the elapsed real time count.
if(_elapsedRealTime > _updateFrequency)
{
_fps = (_updateFrequency / elapsed) * _updateFrequencyRatio; // calculate the framerate
_elapsedRealTime -= _updateFrequency; // adjust the elapsedRealTime
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
if (!this.Visible || !this.Enabled)
return;
this.Game.Window.Title = _gameWindowTitle + " FPS: " + _fps.ToString("F");
}
/// <summary>
/// This method is the <see cref="System.EventHandler"/> for the <see cref="Microsoft.Xna.Framework.GameComponent.EnabledChanged"/> event.
/// </summary>
/// <param name="sender">The events sender</param>
/// <param name="args">The events arguments.</param>
protected override void OnEnabledChanged(object sender, EventArgs args)
{
if(!this.Enabled)
this.Game.Window.Title = _gameWindowTitle;
base.OnEnabledChanged(sender, args);
}
/// <summary>
/// This method is the <see cref="System.EventHandler"/> for the <see cref="Microsoft.Xna.Framework.GameComponent.EnabledChanged"/> event.
/// </summary>
/// <param name="sender">The events sender</param>
/// <param name="args">The events arguments.</param>
protected override void OnVisibleChanged(object sender, EventArgs args)
{
if (!this.Visible)
this.Game.Window.Title = _gameWindowTitle;
base.OnVisibleChanged(sender, args);
}
}
}

View File

@@ -0,0 +1,31 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XnaDevRu.Demos")]
[assembly: AssemblyProduct("XnaDevRu.Demos")]
[assembly: AssemblyDescription("XNADev.ru Common Demo Code")]
[assembly: AssemblyCompany("XNADev.ru")]
[assembly: AssemblyCopyright("Copyright © 2007 XNADev.ru")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("73b76cdc-ea3d-46b1-895e-0b906d173b40")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.149.21894")]

View File

@@ -0,0 +1,86 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{C54AF66D-0C55-4A84-9E7C-FC6346C78681}</ProjectGuid>
<ProjectTypeGuids>{9F340DF3-2AED-4330-AC16-78AC2D9B4738};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>XnaDevRu.Demos</RootNamespace>
<AssemblyName>XnaDevRu.Demos</AssemblyName>
<XnaFrameworkVersion>v1.0</XnaFrameworkVersion>
<XnaPlatform>Windows</XnaPlatform>
<XNAGlobalContentPipelineAssemblies>Microsoft.Xna.Framework.Content.Pipeline.EffectImporter.dll;Microsoft.Xna.Framework.Content.Pipeline.FBXImporter.dll;Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.dll;Microsoft.Xna.Framework.Content.Pipeline.XImporter.dll</XNAGlobalContentPipelineAssemblies>
<XNAProjectContentPipelineAssemblies>
</XNAProjectContentPipelineAssemblies>
<SignAssembly>false</SignAssembly>
<AssemblyOriginatorKeyFile>Demos.snk</AssemblyOriginatorKeyFile>
<DelaySign>true</DelaySign>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\..\Build\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<UseVSHostingProcess>false</UseVSHostingProcess>
<PlatformTarget>x86</PlatformTarget>
<DocumentationFile>..\..\..\..\Build\x86\Debug\XnaDevRu.Demos.XML</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\..\..\Build\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<UseVSHostingProcess>false</UseVSHostingProcess>
<PlatformTarget>x86</PlatformTarget>
<DocumentationFile>..\..\..\..\Build\x86\Release\XnaDevRu.Demos.XML</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Xna.Framework">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Xna.Framework.Game">
<Private>False</Private>
</Reference>
<Reference Include="mscorlib">
<Private>False</Private>
</Reference>
<Reference Include="System">
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Camera.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>Camera</Name>
</Compile>
<Compile Include="Framerate.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>Framerate</Name>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Demos.snk">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>Demos</Name>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\XNA\Game Studio Express\v1.0\Microsoft.Xna.ContentPipeline.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\XNA\Game Studio Express\v1.0\Microsoft.Xna.Common.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual C# Express 2005
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XnaDevRu.Demos", "Source\XnaDevRu.Demos\XnaDevRu.Demos.csproj", "{C54AF66D-0C55-4A84-9E7C-FC6346C78681}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C54AF66D-0C55-4A84-9E7C-FC6346C78681}.Debug|x86.ActiveCfg = Debug|x86
{C54AF66D-0C55-4A84-9E7C-FC6346C78681}.Debug|x86.Build.0 = Debug|x86
{C54AF66D-0C55-4A84-9E7C-FC6346C78681}.Release|x86.ActiveCfg = Release|x86
{C54AF66D-0C55-4A84-9E7C-FC6346C78681}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal