⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 d3dapp.cs

📁 Game Engine Desing Direct X and C#.rar
💻 CS
📖 第 1 页 / 共 4 页
字号:
//-----------------------------------------------------------------------------
// File: D3DApp.cs
//
// Desc: Application class for the Direct3D samples framework library.
//
// Copyright (c) 2001-2002 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D=Microsoft.DirectX.Direct3D;

#region Enums for D3D Applications
/// <summary>
/// Messages that can be used when displaying an error
/// </summary>
public enum ApplicationMessage 
{ 
	None, 
	ApplicationMustExit, 
	WarnSwitchToRef
};

#endregion

#region Various SampleExceptions
/// <summary>
/// The default sample exception type
/// </summary>
public class SampleException : System.ApplicationException
{


    /// <summary>
    /// Return information about the exception
    /// </summary>
	public override string Message { 
		get 
		{ 
			string strMsg = string.Empty;

			strMsg = "Generic application error. Enable\n";
			strMsg += "debug output for detailed information.";

			return strMsg;
		} 
	}
}


/// <summary>
/// Exception informing user no compatible devices were found
/// </summary>
public class NoCompatibleDevicesException : SampleException
{
    
    
    /// <summary>
    /// Return information about the exception
    /// </summary>
    public override string Message
	{
		get
		{
			string strMsg = string.Empty;
			strMsg = "This sample cannot run in a desktop\n";
			strMsg += "window with the current display settings.\n";
			strMsg += "Please change your desktop settings to a\n";
			strMsg += "16- or 32-bit display mode and re-run this\n";
			strMsg += "sample.";

			return strMsg;
		}
	}
}


/// <summary>
/// An exception for when the ReferenceDevice is null
/// </summary>
public class NullReferenceDeviceException : SampleException
{
    /// <summary>
    /// Return information about the exception
    /// </summary>
    public override string Message
	{
		get
		{
			string strMsg = string.Empty;
			strMsg = "Warning: Nothing will be rendered.\n";
			strMsg += "The reference rendering device was selected, but your\n";
			strMsg += "computer only has a reduced-functionality reference device\n";
			strMsg += "installed.  Install the DirectX SDK to get the full\n";
			strMsg += "reference device.\n";

			return strMsg;
		}
	}
}

/// <summary>
/// An exception for when reset fails
/// </summary>
public class ResetFailedException : SampleException
{
    /// <summary>
    /// Return information about the exception
    /// </summary>
    public override string Message
	{
		get
		{
			string strMsg = string.Empty;
			strMsg = "Could not reset the Direct3D device.";

			return strMsg;
		}
	}
}

/// <summary>
/// The exception thrown when media couldn't be found
/// </summary>
public class MediaNotFoundException : SampleException
{
	private string mediaFile;
	public MediaNotFoundException(string filename) : base()
	{
		mediaFile = filename;
	}
	public MediaNotFoundException() : base()
	{
		mediaFile = string.Empty;
	}
    /// <summary>
    /// Return information about the exception
    /// </summary>
    public override string Message
	{
		get
		{
			string strMsg = string.Empty;
			strMsg = "Could not load required media.";
			if (mediaFile.Length > 0)
				strMsg += string.Format("\r\nFile: {0}", mediaFile);

			return strMsg;
		}
	}
}

#endregion

/// <summary>
/// The base class for all the graphics (D3D) samples, it derives from windows forms
/// </summary>
public class GraphicsSample : System.Windows.Forms.Form
{
	#region Menu Information
	// The menu items that *all* samples will need
	protected System.Windows.Forms.MainMenu mnuMain;
	protected System.Windows.Forms.MenuItem mnuFile;
	private System.Windows.Forms.MenuItem mnuGo;
	private System.Windows.Forms.MenuItem mnuSingle;
	private System.Windows.Forms.MenuItem mnuBreak1;
	private System.Windows.Forms.MenuItem mnuChange;
	private System.Windows.Forms.MenuItem mnuBreak2;
	protected System.Windows.Forms.MenuItem mnuExit;
	#endregion

    // The window we will render too
    private System.Windows.Forms.Control ourRenderTarget;
    // Should we use the default windows
    protected bool isUsingMenus = true;
	public bool m_bTerminate = false;

	// We need to keep track of our enumeration settings
	protected D3DEnumeration enumerationSettings = new D3DEnumeration();
	protected D3DSettings graphicsSettings = new D3DSettings();
	private bool isMaximized = false; // Are we maximized?
	private bool isHandlingSizeChanges = true; // Are we handling size changes?

	private float lastTime = 0.0f; // The last time
	private int frames  = 0; // Number of rames since our last update
	private int appPausedCount = 0; // How many times has the app been paused (and when can it resume)?

	// Internal variables for the state of the app
	protected bool windowed;
	protected bool active;
	protected bool ready;
	protected bool hasFocus;

	// Internal variables used for timing
	protected bool frameMoving;
	protected bool singleStep;
	// Main objects used for creating and rendering the 3D scene
	protected PresentParameters presentParams = new PresentParameters();         // Parameters for CreateDevice/Reset
	protected Device device; // The rendering device
	protected RenderStates renderState;
	protected SamplerStates sampleState;
	protected TextureStates textureStates;
	private Caps graphicsCaps;           // Caps for the device
	protected Caps Caps { get { return graphicsCaps; } }
	private CreateFlags behavior;     // Indicate sw or hw vertex processing
	protected BehaviorFlags BehaviorFlags { get { return new BehaviorFlags(behavior); } }
    protected System.Windows.Forms.Control RenderTarget { get { return ourRenderTarget; } set { ourRenderTarget = value; } }

	// Variables for timing
	protected float appTime;             // Current time in seconds
	protected float elapsedTime;      // Time elapsed since last frame
	protected float framePerSecond;              // Instanteous frame rate
	protected string deviceStats;// String to hold D3D device stats
	protected string frameStats; // String to hold frame stats

	private bool deviceLost = false;

	// Overridable variables for the app
	private int minDepthBits;    // Minimum number of bits needed in depth buffer
	protected int MinDepthBits { get { return minDepthBits; } set { minDepthBits = value;  enumerationSettings.AppMinDepthBits = value;} }
	private int minStencilBits;  // Minimum number of bits needed in stencil buffer
	protected int MinStencilBits { get { return minStencilBits; } set { minStencilBits = value;  enumerationSettings.AppMinStencilBits = value;} }
	protected bool showCursorWhenFullscreen; // Whether to show cursor when fullscreen
	protected bool clipCursorWhenFullscreen; // Whether to limit cursor pos when fullscreen
	protected bool startFullscreen; // Whether to start up the app in fullscreen mode

    private System.Drawing.Size storedSize;

	// Overridable functions for the 3D scene created by the app
	protected virtual bool ConfirmDevice(Caps caps, VertexProcessingType vertexProcessingType, Format format) { return true; }
	protected virtual void OneTimeSceneInitialization() { /* Do Nothing */ }
	protected virtual void InitializeDeviceObjects() { /* Do Nothing */ }
	protected virtual void RestoreDeviceObjects(System.Object sender, System.EventArgs e) { /* Do Nothing */ }
	protected virtual void FrameMove() { /* Do Nothing */ }
	protected virtual void Render() { /* Do Nothing */ }
	protected virtual void InvalidateDeviceObjects(System.Object sender, System.EventArgs e) { /* Do Nothing */ }
	protected virtual void DeleteDeviceObjects(System.Object sender, System.EventArgs e) { /* Do Nothing */ }





    /// <summary>
    /// Constructor
    /// </summary>
	public GraphicsSample()
	{
		device = null;
		active = false;
		ready = false;
		hasFocus = false;
		behavior = 0;

        ourRenderTarget = this;
		frameMoving = true;
		singleStep = false;
		framePerSecond = 0.0f;
		deviceStats = null;
		frameStats  = null;

		this.Text = "Game Engine Sample";
		this.ClientSize = new System.Drawing.Size(800,600);
		this.KeyPreview = true;

		minDepthBits    = 16;
		minStencilBits  = 0;
		showCursorWhenFullscreen = false;
		startFullscreen = false;

		// When clipCursorWhenFullscreen is TRUE, the cursor is limited to
		// the device window when the app goes fullscreen.  This prevents users
		// from accidentally clicking outside the app window on a multimon system.
		// This flag is turned off by default for debug builds, since it makes 
		// multimon debugging difficult.
		#if (DEBUG)
			clipCursorWhenFullscreen = false;
		#else
			clipCursorWhenFullscreen = true;
		#endif
		InitializeComponent();
	}




    /// <summary>
    /// Picks the best graphics device, and initializes it
    /// </summary>
    /// <returns>true if a good device was found, false otherwise</returns>
	public bool CreateGraphicsSample()
	{
		enumerationSettings.ConfirmDeviceCallback = new D3DEnumeration.ConfirmDeviceCallbackType(this.ConfirmDevice);
		enumerationSettings.Enumerate();

		if (ourRenderTarget.Cursor == null)
		{
			// Set up a default cursor
			ourRenderTarget.Cursor = System.Windows.Forms.Cursors.Default;
		}
        // if our render target is the main window and we haven't said 
        // ignore the menus, add our menu
        if ((ourRenderTarget == this) && (isUsingMenus))
		    this.Menu = mnuMain;

		try
		{
			ChooseInitialSettings();

			// Initialize the application timer
			DXUtil.Timer( TIMER.START );
			// Initialize the 3D environment for the app
			InitializeEnvironment();
			// Initialize the app's custom scene stuff
			OneTimeSceneInitialization();
		}
		catch (SampleException d3de)
		{
			HandleSampleException( d3de, ApplicationMessage.ApplicationMustExit );
			return false;
		}
		catch 
		{
            HandleSampleException( new SampleException(), ApplicationMessage.ApplicationMustExit );
            return false;
		}

		// The app is ready to go
		ready = true;

		return true;
	}



    /// <summary>
    /// Sets up graphicsSettings with best available windowed mode, subject to 
    /// the doesRequireHardware and doesRequireReference constraints.  
    /// </summary>
    /// <param name="doesRequireHardware">Does the device require hardware support</param>
    /// <param name="doesRequireReference">Does the device require the ref device</param>
    /// <returns>true if a mode is found, false otherwise</returns>
	public bool FindBestWindowedMode(bool doesRequireHardware, bool doesRequireReference)
	{
		// Get display mode of primary adapter (which is assumed to be where the window 
		// will appear)
		DisplayMode primaryDesktopDisplayMode = Manager.Adapters[0].CurrentDisplayMode;

		GraphicsAdapterInfo bestAdapterInfo = null;
		GraphicsDeviceInfo bestDeviceInfo = null;
		DeviceCombo bestDeviceCombo = null;

		foreach (GraphicsAdapterInfo adapterInfo in enumerationSettings.AdapterInfoList)
		{
			foreach (GraphicsDeviceInfo deviceInfo in adapterInfo.DeviceInfoList)
			{
				if (doesRequireHardware && deviceInfo.DevType != DeviceType.Hardware)
					continue;
				if (doesRequireReference && deviceInfo.DevType != DeviceType.Reference)
					continue;
				foreach (DeviceCombo deviceCombo in deviceInfo.DeviceComboList)
				{
					bool adapterMatchesBackBuffer = (deviceCombo.BackBufferFormat == deviceCombo.AdapterFormat);
					if (!deviceCombo.IsWindowed)
						continue;
					if (deviceCombo.AdapterFormat != primaryDesktopDisplayMode.Format)
						continue;
					// If we haven't found a compatible DeviceCombo yet, or if this set
					// is better (because it's a HAL, and/or because formats match better),
					// save it
					if (bestDeviceCombo == null || 
						bestDeviceCombo.DevType != DeviceType.Hardware && deviceInfo.DevType == DeviceType.Hardware ||
						deviceCombo.DevType == DeviceType.Hardware && adapterMatchesBackBuffer )
					{
						bestAdapterInfo = adapterInfo;
						bestDeviceInfo = deviceInfo;
						bestDeviceCombo = deviceCombo;
						if (deviceInfo.DevType == DeviceType.Hardware && adapterMatchesBackBuffer)
						{
							// This windowed device combo looks great -- take it
							goto EndWindowedDeviceComboSearch;
						}
						// Otherwise keep looking for a better windowed device combo
					}
				}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -