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

📄 oldd3dapp.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
public enum AppMsgType 
{ 
	None, 
	ErrorAppMustExit, 
	WarnSwitchToRef
};

#endregion

public class GraphicsException : System.Exception
{
	private ErrorCode resultCode = ErrorCode.Generic;
	public enum ErrorCode
	{
		Generic,
		NoDirect3D,
		NoWindow,
		NoCompatibleDevices,
		NoWindowableDevices,
		NoHardwareDevice,
		HalNotCompatible,
		NoWindowedHal,
		NoDesktopHal,
		NoHalThisMode,
		MediaNotFound,
		ResizeFailed,
		NullRefDevice,
	}
	public GraphicsException(){}
	public GraphicsException(ErrorCode code)
	{
		resultCode = code;
	}
	public override string Message { 
		get 
		{ 
			string strMsg = null;

			switch( resultCode )
			{
				case ErrorCode.NoDirect3D:
					strMsg = "Could not initialize Direct3D. You may\n";
					strMsg += "want to check that the latest version of\n";
					strMsg += "DirectX is correctly installed on your\n";
					strMsg += "system.  Also make sure that this program\n";
					strMsg += "was compiled with header files that match\n";
					strMsg += "the installed DirectX DLLs.";
					break;

				case ErrorCode.NoCompatibleDevices:
					strMsg = "Could not find any compatible Direct3D\ndevices.";
					break;

				case ErrorCode.NoWindowableDevices:
					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.";
					break;

				case ErrorCode.NoHardwareDevice:
					strMsg = "No hariare-accelerated Direct3D devices\n";
					strMsg += "were found.";
					break;

				case ErrorCode.HalNotCompatible:
					strMsg = "This sample requires functionality that is\n";
					strMsg += "not available on your Direct3D hariare\n";
					strMsg += "accelerator.";
					break;

				case ErrorCode.NoWindowedHal:
					strMsg = "Your Direct3D hariare accelerator cannot\n";
					strMsg += "render into a window.\n";
					strMsg += "Press F2 while the app is running to see a\n";
					strMsg += "list of available devices and modes.";
					break;

				case ErrorCode.NoDesktopHal:
					strMsg = "Your Direct3D hariare accelerator cannot\n";
					strMsg += "render into a window with the current\n";
					strMsg += "desktop display settings.\n";
					strMsg += "Press F2 while the app is running to see a\n";
					strMsg += "list of available devices and modes.";
					break;

				case ErrorCode.NoHalThisMode:
					strMsg = "This sample requires functionality that is\n";
					strMsg += "not available on your Direct3D hariare\n";
					strMsg += "accelerator with the current desktop display\n";
					strMsg += "settings.\n";
					strMsg += "Press F2 while the app is running to see a\n";
					strMsg += "list of available devices and modes.";
					break;

				case ErrorCode.MediaNotFound:
					strMsg = "Could not load required media.";
					break;

				case ErrorCode.ResizeFailed:
					strMsg = "Could not reset the Direct3D device.";
					break;

				case ErrorCode.NullRefDevice:
					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";
					break;

				case (ErrorCode)Direct3D.ErrorCode.OutOfVidMemory:
					strMsg = "Not enough video memory.";
					break;

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

			}
			return strMsg;
		} 
	}
}
public class GraphicsSample : System.Windows.Forms.Form, IDisposable
{
	// Menu information
	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;
	private System.Windows.Forms.MenuItem mnuExit;

	//-----------------------------------------------------------------------------
	// Global access to the app (needed for the global WndProc())
	//-----------------------------------------------------------------------------
	public static GraphicsSample ourSample = null;
	public bool m_bTerminate = false;

	protected D3DEnumeration enumerationSettings = new D3DEnumeration();
	protected D3DSettings graphicsSettings = new D3DSettings();
	private bool isDisposed = false;

	private float lastTime = 0.0f;
	private uint frames  = 0;
	private uint appPausedCount = 0;

	// 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 D3D graphicsObject;              // The main D3D object
	protected Device device;        // The D3D 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 SurfaceDescription backBufferDesc;   // Surface desc of the backbuffer
	public SurfaceDescription backBuffer { get { return backBufferDesc; } }
	private CreateFlags behavior;     // Indicate sw or hw vertex processing
	protected BehaviorFlags BehaviorFlags { get { return new BehaviorFlags(behavior); } }
	protected System.Drawing.Rectangle windowBoundsRect;    // Saved window bounds for mode switches
	protected System.Drawing.Rectangle clientRect;    // Saved client area size for mode switches

	// 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
	protected string windowTitle;    // Title for the app's window
	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

	// Overridable functions for the 3D scene created by the app
	protected virtual bool ConfirmDevice(Caps caps, VertexProcessingType vertexProcessingType, Format fmt) { return true; }
	protected virtual void OneTimeSceneInit()                         { /* Do Nothing */ }
	protected virtual void InitDeviceObjects()                        { /* 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 */ }
	protected virtual void FinalCleanup()                       { /* Do Nothing */ }





	//-----------------------------------------------------------------------------
	// Name: GraphicsSample()
	// Desc: Constructor
	//-----------------------------------------------------------------------------
	public GraphicsSample()
	{
		ourSample = this;

		graphicsObject              = null;
		device        = null;
		active           = false;
		ready            = false;
		hasFocus		= false;
		behavior     = 0;

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

		this.Text    = "D3D9 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();
	}




	//-----------------------------------------------------------------------------
	// Name: CreateD3DApp()
	// Desc:
	//-----------------------------------------------------------------------------
	public bool CreateD3DApp()
	{
		// Create the Direct3D object
		graphicsObject = new D3D();
		if( graphicsObject == null )
		{
			DisplayErrorMsg( new GraphicsException(GraphicsException.ErrorCode.NoDirect3D), AppMsgType.ErrorAppMustExit );
			return false;
		}

		enumerationSettings.D3D = graphicsObject;
		enumerationSettings.ConfirmDeviceCallback = new D3DEnumeration.ConfirmDeviceCallbackType(this.ConfirmDevice);
		enumerationSettings.Enumerate();

		if (this.Cursor == null)
		{
			// Set up a default cursor
			this.Cursor = System.Windows.Forms.Cursors.Default;
		}
		// Unless a substitute hWnd has been specified, create a window to
		// render into
		this.Menu = mnuMain;

		// Save window properties
		windowBoundsRect = new System.Drawing.Rectangle(this.Location, this.Size);
		clientRect = this.ClientRectangle;

		ChooseInitialD3DSettings();

		// Initialize the application timer
		DXUtil.Timer( TIMER.START );

		try
		{
			// Initialize the 3D environment for the app
			Initialize3DEnvironment();
			// Initialize the app's custom scene stuff
			OneTimeSceneInit();
		}
		catch (GraphicsException d3de)
		{
			DisplayErrorMsg( d3de, AppMsgType.ErrorAppMustExit );
			return false;
		}
		catch
		{
			return false;
		}

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

		return true;
	}



	// Sets up graphicsSettings with best available windowed mode, subject to 
	// the bRequireHAL and bRequireREF constraints.  Returns false if no such
	// mode can be found.
	public bool FindBestWindowedMode(bool bRequireHAL, bool bRequireREF)
	{
		// Get display mode of primary adapter (which is assumed to be where the window 
		// will appear)
		DisplayMode primaryDesktopDisplayMode = graphicsObject.Adapters[0].DisplayMode;

		D3DAdapterInfo bestAdapterInfo = null;
		D3DDeviceInfo bestDeviceInfo = null;
		D3DDeviceCombo bestDeviceCombo = null;

		foreach (D3DAdapterInfo adapterInfo in enumerationSettings.AdapterInfoList)
		{
			foreach (D3DDeviceInfo deviceInfo in adapterInfo.DeviceInfoList)
			{
				if (bRequireHAL && deviceInfo.DevType != DeviceType.Hardware)
					continue;
				if (bRequireREF && deviceInfo.DevType != DeviceType.Reference)
					continue;
				foreach (D3DDeviceCombo deviceCombo in deviceInfo.DeviceComboList)
				{
					bool bAdapterMatchesBB = (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 && bAdapterMatchesBB )
					{
						bestAdapterInfo = adapterInfo;
						bestDeviceInfo = deviceInfo;
						bestDeviceCombo = deviceCombo;
						if (deviceInfo.DevType == DeviceType.Hardware && bAdapterMatchesBB)
						{
							// This windowed device combo looks great -- take it
							goto EndWindowedDeviceComboSearch;
						}
						// Otherwise keep looking for a better windowed device combo
					}
				}
			}
		}
	EndWindowedDeviceComboSearch:
		if (bestDeviceCombo == null )
			return false;

		graphicsSettings.Windowed_AdapterInfo = bestAdapterInfo;
		graphicsSettings.Windowed_DeviceInfo = bestDeviceInfo;
		graphicsSettings.Windowed_DeviceCombo = bestDeviceCombo;
		graphicsSettings.IsWindowed = true;
		graphicsSettings.Windowed_DisplayMode = primaryDesktopDisplayMode;
		graphicsSettings.Windowed_Width = clientRect.Right - clientRect.Left;
		graphicsSettings.Windowed_Height = clientRect.Bottom - clientRect.Top;
		if (enumerationSettings.AppUsesDepthBuffer)
			graphicsSettings.Windowed_DepthStencilBufferFormat = (Format)bestDeviceCombo.DepthStencilFormatList[0];
		graphicsSettings.Windowed_MultisampleType = (MultiSampleType)bestDeviceCombo.MultiSampleTypeList[0];
		graphicsSettings.Windowed_MultisampleQuality = 0;
		graphicsSettings.Windowed_VertexProcessingType = (VertexProcessingType)bestDeviceCombo.VertexProcessingTypeList[0];
		graphicsSettings.Windowed_PresentInterval = (PresentInterval)bestDeviceCombo.PresentIntervalList[0];
		return true;
	}




	// Sets up graphicsSettings with best available fullscreen mode, subject to 

⌨️ 快捷键说明

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