1.首先定义一个DX操作类

  1. using System;
  2. using SlimDX;
  3. using SlimDX.Direct3D9;
  4. using System.Windows.Interop;
  5. using System.Windows.Media;
  6.  
  7. public class DX
  8. {
  9. private enum DirectXStatus
  10. {
  11. Available,
  12. Unavailable_RemoteSession,
  13. Unavailable_LowTier,
  14. Unavailable_MissingDirectX,
  15. Unavailable_Unknown
  16. };
  17.  
  18. public static Device Device { get; private set; }
  19. public static bool Available { get { return DX.Device != null; } }// = false;
  20.  
  21. private static DX _dx;
  22. private static DirectXStatus _status = DirectXStatus.Unavailable_Unknown;
  23. private static string _statusMessage = "";
  24.  
  25. [System.Runtime.InteropServices.DllImport("user32")]
  26. private static extern int GetSystemMetrics(int smIndex);
  27. private const int SM_REMOTESESSION = 0x1000;
  28.  
  29. // device settings
  30. private const Format _adapterFormat = Format.X8R8G8B8;
  31. private const Format _backbufferFormat = Format.A8R8G8B8;
  32. private const Format _depthStencilFormat = Format.D16;
  33. private static CreateFlags _createFlags = CreateFlags.Multithreaded | CreateFlags.FpuPreserve;
  34.  
  35. private Direct3D _d3d;
  36.  
  37. private DX()
  38. {
  39. initD3D();
  40. if (_d3d != null)
  41. initDevice();
  42. //if (!DX.Available)
  43. // MessageBox.Show("DirectX硬件加速不可用!\n\n" + _statusMessage, "", MessageBoxButton.OK, MessageBoxImage.Warning);
  44. }
  45.  
  46. ~DX()
  47. {
  48. if (DX.Device != null)
  49. if (!DX.Device.Disposed)
  50. DX.Device.Dispose();
  51. if (_d3d != null)
  52. if (!_d3d.Disposed)
  53. _d3d.Dispose();
  54. }
  55.  
  56. public static void Init()
  57. {
  58. if (_dx == null)
  59. _dx = new DX();
  60. }
  61.  
  62. private void initD3D()
  63. {
  64. if (_d3d != null)
  65. return;
  66.  
  67. _status = DirectXStatus.Unavailable_Unknown;
  68.  
  69. //// assume that we can't run at all under terminal services
  70. if (GetSystemMetrics(SM_REMOTESESSION) != )
  71. {
  72. _status = DirectXStatus.Unavailable_RemoteSession;
  73. return;
  74. }
  75.  
  76. int renderingTier = (RenderCapability.Tier >> );
  77. if (renderingTier < )
  78. {
  79. _status = DirectXStatus.Unavailable_LowTier;
  80. _statusMessage = "low tier";
  81. return;//注意:发现某些集成显卡,在这里出去!!
  82. }
  83.  
  84. try
  85. {
  86. _d3d = new Direct3DEx();
  87. }
  88. catch
  89. {
  90. try
  91. {
  92. _d3d = new Direct3D();
  93. }
  94. catch (Direct3DX9NotFoundException dfe)
  95. {
  96. _status = DirectXStatus.Unavailable_MissingDirectX;
  97. _statusMessage = "Direct3DX9 Not Found\n" + dfe.Message;
  98. return;
  99. }
  100. catch (Exception e)
  101. {
  102. _status = DirectXStatus.Unavailable_Unknown;
  103. _statusMessage = e.Message;
  104. return;
  105. }
  106. }
  107.  
  108. bool ok;
  109. Result result;
  110.  
  111. ok = _d3d.CheckDeviceType(, DeviceType.Hardware, _adapterFormat, _backbufferFormat, true, out result);
  112. if (!ok)
  113. {
  114. //Debug.WriteLine("*** failed to CheckDeviceType");
  115. //MessageBox.Show("Failed to CheckDeviceType");
  116. return;
  117. }
  118.  
  119. ok = _d3d.CheckDepthStencilMatch(, DeviceType.Hardware, _adapterFormat, _backbufferFormat, _depthStencilFormat, out result);
  120. if (!ok)
  121. {
  122. //Debug.WriteLine("*** failed to CheckDepthStencilMatch");
  123. _statusMessage = "Failed to CheckDepthStencilMatch";
  124. return;
  125. }
  126.  
  127. Capabilities deviceCaps = _d3d.GetDeviceCaps(, DeviceType.Hardware);
  128. if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != )
  129. _createFlags |= CreateFlags.HardwareVertexProcessing;
  130. else
  131. _createFlags |= CreateFlags.SoftwareVertexProcessing;
  132.  
  133. _status = DirectXStatus.Available;
  134. }
  135.  
  136. private void initDevice()
  137. {
  138. if (_status != DirectXStatus.Available)
  139. return;
  140.  
  141. HwndSource hwnd = new HwndSource(, , , , , , , "SlimDX_Wnd", IntPtr.Zero);
  142. PresentParameters pp = new PresentParameters();
  143. //pp.SwapEffect = SwapEffect.Copy;
  144. //pp.DeviceWindowHandle = hwnd.Handle;
  145. pp.Windowed = true;
  146. pp.PresentFlags = PresentFlags.Video;
  147. pp.SwapEffect = SwapEffect.Discard;
  148. //pp.BackBufferCount = 1;
  149. //pp.BackBufferWidth = 320;
  150. //pp.BackBufferHeight = 240;
  151. //pp.BackBufferFormat = _backbufferFormat;
  152. //pp.AutoDepthStencilFormat = _depthStencilFormat;
  153. try
  154. {
  155. DeviceType deviceType = DeviceType.Hardware;
  156. if (_d3d is Direct3DEx)
  157. DX.Device = new DeviceEx((Direct3DEx)_d3d, , deviceType, hwnd.Handle, _createFlags, pp);
  158. else
  159. DX.Device = new Device(_d3d, , deviceType, hwnd.Handle, _createFlags, pp);
  160. }
  161. catch (Exception ex)
  162. {
  163. //Debug.WriteLine("Exception in Direct3DReset " + ex.StackTrace);
  164. //Debug.WriteLine("Exception in Direct3DReset " + ex.Message);
  165. }
  166. }
  167. }

2.定义准备显卡硬件,和释放显卡硬件方法

定义一些变量

  1.    /// <summary>
  2. /// 离屏表面
  3. /// </summary>
  4. private Surface _offscrn;
  5. /// <summary>
  6. /// 交换链
  7. /// </summary>
  8. private SwapChain _swapChain;
  9. private D3DImage _d3dImage = null;
  1.      /// <summary>
  2. /// 准备DirectX显卡硬件
  3. /// </summary>
  4. private bool prepareHardware(VideoFormat videoFormat, int videoWidth, int videoHeight)//, VideoFormat videoFormat)
  5. {
  6. if (!DX.Available)
  7. return true;
  8.  
  9. try
  10. {
  11. SlimDX.Direct3D9.Format format = SlimDX.Direct3D9.Format.A8R8G8B8;
  12. if (videoFormat == VideoFormat.Yuv420)
  13. format = (SlimDX.Direct3D9.Format)0x32315659;
  14. if (_offscrn != null)
  15. if (videoWidth == _offscrn.Description.Width && videoHeight == _offscrn.Description.Height && _offscrn.Description.Format == format)
  16. return true;
  17.  
  18. releaseHardware();
  19. _offscrn = Surface.CreateOffscreenPlain(DX.Device, videoWidth, videoHeight, format, Pool.Default);
  20. PresentParameters pp = new PresentParameters();
  21. pp.Windowed = true;
  22. pp.PresentFlags = PresentFlags.Video;
  23. pp.SwapEffect = SwapEffect.Discard;
  24. pp.BackBufferCount = ;
  25. pp.BackBufferWidth = videoWidth;
  26. pp.BackBufferHeight = videoHeight;
  27. _swapChain = new SwapChain(DX.Device, pp);
  28. return true;
  29. }
  30. catch
  31. {
  32. return false;
  33. }
  34. }
  35. /// <summary>
  36. /// 释放DirectX显卡硬件
  37. /// </summary>
  38. private void releaseHardware()
  39. {
  40. if (!DX.Available)
  41. return;
  42. if (_offscrn != null)
  43. if (!_offscrn.Disposed)
  44. _offscrn.Dispose();
  45. _offscrn = null;
  46. if (_swapChain != null)
  47. if (!_swapChain.Disposed)
  48. _swapChain.Dispose();
  49. _swapChain = null;
  50. }

3.

  1. private void drawFrame(VideoFormat videoFormat, int width, int height, IntPtr Y, IntPtr U, IntPtr V)
  2. {
  3. if (!prepareHardware(videoFormat, width, height))
  4. return;
  5. if (_swapChain == null)
  6. return;
  7.  
  8. DataRectangle dr = _offscrn.LockRectangle(LockFlags.None);//在离屏表面上锁定一个矩形
  9. drawYuv420(width, height, Y, U, V, dr.Data.DataPointer, dr.Pitch);//DataPointer 内部指针指向当前流的存储备份; Pitch 两个连续的行之间的数据的字节数
  10. _offscrn.UnlockRectangle();//解锁矩形
  11. using (Surface bb = _swapChain.GetBackBuffer())//从交换链中检索一个后台缓冲区
  12. {
  13. System.Drawing.Rectangle rect = new System.Drawing.Rectangle(, , bb.Description.Width, bb.Description.Height);
  14. _swapChain.Device.StretchRectangle(_offscrn, rect, bb, rect, TextureFilter.None);//将后台缓冲区的内容交换到前台缓冲区
  15. _swapChain.Device.Present();//呈现后台缓冲区序列中下一个后台缓冲区的内容
  16.  
  17. _d3dImage.Lock();
  18. _d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, bb.ComPointer);
  19. _d3dImage.AddDirtyRect(new Int32Rect(, , _d3dImage.PixelWidth, _d3dImage.PixelHeight));
  20. _d3dImage.Unlock();
  21. }
  22. }
  23.  
  24. private void drawYuv420(int width, int height, IntPtr Y, IntPtr U, IntPtr V, IntPtr dest, int pitch)
  25. {
  26. IntPtr py = dest;
  27. IntPtr pv = py + (pitch * height);
  28. IntPtr pu = pv + ((pitch * height) / );
  29. int w2 = width / , pitch2 = pitch / ;
  30. for (int y = ; y < height; y++)
  31. {
  32. CopyMemory(py, Y + y * width, (uint)width);
  33. py += pitch;
  34. if ((y & ) != )
  35. continue;
  36. int offset = y / * w2;
  37. CopyMemory(pu, U + offset, (uint)w2);
  38. CopyMemory(pv, V + offset, (uint)w2);
  39. pu += pitch2;
  40. pv += pitch2;
  41. }
  42. }
  43. [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
  44. private static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length);

SlimDX和WPF的合作应用的更多相关文章

  1. WPF特点

    前言:为什么要学习WPF呢?因为随着现阶段硬件技术的升级以及客户对体验的要求越来越高,传统的GDI和USERS(或者是GDI+.USERS)已经不能满足这个需求,因此,WPF技术应运而生. WPF的特 ...

  2. WPF开发中Designer和码农之间的合作

    想要用WPF做出一流的软件界面, 必须要Designer和码农通力合作.理想的情况是平时并行开发,Designer用Expression套件(包括Design和Blend)来设计界面,码农开发Mode ...

  3. 年度巨献-WPF项目开发过程中WPF小知识点汇总(原创+摘抄)

    WPF中Style的使用 Styel在英文中解释为”样式“,在Web开发中,css为层叠样式表,自从.net3.0推出WPF以来,WPF也有样式一说,通过设置样式,使其WPF控件外观更加美化同时减少了 ...

  4. WPF 3D 知识点大全以及实例

    引言 现在物联网概念这么火,如果监控的信息能够实时在手机的客服端中以3D形式展示给我们,那种体验大家可以发挥自己的想象. 那生活中我们还有很多地方用到这些,如上图所示的Kinect 在医疗上的应用,当 ...

  5. 第一个WPF应用程序

    WPF 全称为 Windows Presentation Foundation. 核心特性: WPF使用一种新的XAML(Extensible Application Markup Language) ...

  6. 2012开源项目计划-WPF企业级应用整合平台

    2012开源项目计划-WPF企业级应用整合平台 开篇 2012年,提前祝大家新年快乐,为了加快2012年的开发计划,特打算年前和大家分享一下2012年的开发计划和年后具体的实施计划,希望有兴趣或者有志 ...

  7. 一、什么是WPF?

    一.什么是WPF? Windows Presentation Foundation(以前的代号为“Avalon”)是 Microsoft 用于 Windows 的统一显示子系统,它通过 WinFX 公 ...

  8. wpf做的可扩展记事本

    记得有个winform利用反射做的可扩展笔记本,闲来无事,便用wpf也搞了个可扩展记事本,可用接口动态扩展功能,较简单,以便参考: 目录结构如下: MainWindow.xaml为主功能界面,Func ...

  9. vs2012用wpf制作透明窗口中报错的解决方案

    在开发wpf项目时,需要调用外部com组件,同时需要制作透明窗口,于是问题出现了,当我们在设置 AllowsTransparency="True"后,com组件显示不出来了,只有透 ...

随机推荐

  1. 火狐Firefox 浏览器 onblur() 并且alert()时文本被选中问题

    说明:镜像是组成在线实验课程的基础环境,教师设计的实验绑定一个或多个镜像,就组成了一讲独立的在线实验课程. 镜像名称:     火狐Firefox 浏览器 onblur() 并且alert()时文本被 ...

  2. Symfony2 Doctrine从现有Database生成Entity(转载自http://blog.it985.com/6809.html)

    在我的以前一章Symfony之十分钟入门说了怎样生成数据库,然后设计实体Entity,再同步数据库的表结构,一般我们的顺序都是这样:生成数据库->设计实体Entity->同步数据库表结构. ...

  3. js获取IP地址的方法小结

    s代码获取IP地址的三种方法,在js中取得客户端的IP地址. 原文地址:http://www.jbxue.com/article/11338.html 1,js取得IP地址的方法一 <scrip ...

  4. 关于Django模板渲染一个很重要的用途

    一般情况下我们在模板利用django的for标签循环生成html代码时,可以同时生成形如: "{% url 'dormitory:hygiene_detail' pk={{ id }} %} ...

  5. Xshell4连接Linux后 win快捷键锁屏

    今天在使用Xshell连接CentOS后 使用Vim编辑器编辑完后 习惯性的按了Ctrl+S 然后按什么都不起作用 只能重新连接 通过查资料得知 Ctrl + S 是Linux 锁屏的快捷键 要解除锁 ...

  6. Powershell 快捷键

    Powershell的快捷键和cmd,linux中的shell,都比较像. ALT+F7 清除命令的历史记录PgUp PgDn 显示当前会话的第一个命令和最后一个命令Enter 执行当前命令End 将 ...

  7. uva10245-The Closest Pair Problem(平面上的点分治)

    解析:平面上的点分治,先递归得到左右子区间的最小值d,再处理改区间,肯定不会考虑哪些距离已经大于d的点对,对y坐标归并排序,然后从小到大开始枚举更新d,对于某个点,x轴方向只用考虑[x-d,x+d]( ...

  8. 【POJ3006】Dirichlet's Theorem on Arithmetic Progressions(素数筛法)

    简单的暴力筛法就可. #include <iostream> #include <cstring> #include <cmath> #include <cc ...

  9. Hive 3、Hive 的安装配置(本地derby模式)

    这种方式是最简单的存储方式,只需要在hive-site.xml做如下配置便可; $ vim hive-site.xml <configuration>   <property> ...

  10. [转]Binarized Neural Networks_ Training Neural Networks with Weights and Activations Constrained to +1 or −1

    原文: 二值神经网络(Binary Neural Network,BNN) 在我刚刚过去的研究生毕设中,我在ImageNet数据集上验证了图像特征二值化后仍然具有很强的表达能力,可以在检索中达到较好的 ...