SlimDX和WPF的合作应用
1.首先定义一个DX操作类
- using System;
- using SlimDX;
- using SlimDX.Direct3D9;
- using System.Windows.Interop;
- using System.Windows.Media;
- public class DX
- {
- private enum DirectXStatus
- {
- Available,
- Unavailable_RemoteSession,
- Unavailable_LowTier,
- Unavailable_MissingDirectX,
- Unavailable_Unknown
- };
- public static Device Device { get; private set; }
- public static bool Available { get { return DX.Device != null; } }// = false;
- private static DX _dx;
- private static DirectXStatus _status = DirectXStatus.Unavailable_Unknown;
- private static string _statusMessage = "";
- [System.Runtime.InteropServices.DllImport("user32")]
- private static extern int GetSystemMetrics(int smIndex);
- private const int SM_REMOTESESSION = 0x1000;
- // device settings
- private const Format _adapterFormat = Format.X8R8G8B8;
- private const Format _backbufferFormat = Format.A8R8G8B8;
- private const Format _depthStencilFormat = Format.D16;
- private static CreateFlags _createFlags = CreateFlags.Multithreaded | CreateFlags.FpuPreserve;
- private Direct3D _d3d;
- private DX()
- {
- initD3D();
- if (_d3d != null)
- initDevice();
- //if (!DX.Available)
- // MessageBox.Show("DirectX硬件加速不可用!\n\n" + _statusMessage, "", MessageBoxButton.OK, MessageBoxImage.Warning);
- }
- ~DX()
- {
- if (DX.Device != null)
- if (!DX.Device.Disposed)
- DX.Device.Dispose();
- if (_d3d != null)
- if (!_d3d.Disposed)
- _d3d.Dispose();
- }
- public static void Init()
- {
- if (_dx == null)
- _dx = new DX();
- }
- private void initD3D()
- {
- if (_d3d != null)
- return;
- _status = DirectXStatus.Unavailable_Unknown;
- //// assume that we can't run at all under terminal services
- if (GetSystemMetrics(SM_REMOTESESSION) != )
- {
- _status = DirectXStatus.Unavailable_RemoteSession;
- return;
- }
- int renderingTier = (RenderCapability.Tier >> );
- if (renderingTier < )
- {
- _status = DirectXStatus.Unavailable_LowTier;
- _statusMessage = "low tier";
- return;//注意:发现某些集成显卡,在这里出去!!
- }
- try
- {
- _d3d = new Direct3DEx();
- }
- catch
- {
- try
- {
- _d3d = new Direct3D();
- }
- catch (Direct3DX9NotFoundException dfe)
- {
- _status = DirectXStatus.Unavailable_MissingDirectX;
- _statusMessage = "Direct3DX9 Not Found\n" + dfe.Message;
- return;
- }
- catch (Exception e)
- {
- _status = DirectXStatus.Unavailable_Unknown;
- _statusMessage = e.Message;
- return;
- }
- }
- bool ok;
- Result result;
- ok = _d3d.CheckDeviceType(, DeviceType.Hardware, _adapterFormat, _backbufferFormat, true, out result);
- if (!ok)
- {
- //Debug.WriteLine("*** failed to CheckDeviceType");
- //MessageBox.Show("Failed to CheckDeviceType");
- return;
- }
- ok = _d3d.CheckDepthStencilMatch(, DeviceType.Hardware, _adapterFormat, _backbufferFormat, _depthStencilFormat, out result);
- if (!ok)
- {
- //Debug.WriteLine("*** failed to CheckDepthStencilMatch");
- _statusMessage = "Failed to CheckDepthStencilMatch";
- return;
- }
- Capabilities deviceCaps = _d3d.GetDeviceCaps(, DeviceType.Hardware);
- if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != )
- _createFlags |= CreateFlags.HardwareVertexProcessing;
- else
- _createFlags |= CreateFlags.SoftwareVertexProcessing;
- _status = DirectXStatus.Available;
- }
- private void initDevice()
- {
- if (_status != DirectXStatus.Available)
- return;
- HwndSource hwnd = new HwndSource(, , , , , , , "SlimDX_Wnd", IntPtr.Zero);
- PresentParameters pp = new PresentParameters();
- //pp.SwapEffect = SwapEffect.Copy;
- //pp.DeviceWindowHandle = hwnd.Handle;
- pp.Windowed = true;
- pp.PresentFlags = PresentFlags.Video;
- pp.SwapEffect = SwapEffect.Discard;
- //pp.BackBufferCount = 1;
- //pp.BackBufferWidth = 320;
- //pp.BackBufferHeight = 240;
- //pp.BackBufferFormat = _backbufferFormat;
- //pp.AutoDepthStencilFormat = _depthStencilFormat;
- try
- {
- DeviceType deviceType = DeviceType.Hardware;
- if (_d3d is Direct3DEx)
- DX.Device = new DeviceEx((Direct3DEx)_d3d, , deviceType, hwnd.Handle, _createFlags, pp);
- else
- DX.Device = new Device(_d3d, , deviceType, hwnd.Handle, _createFlags, pp);
- }
- catch (Exception ex)
- {
- //Debug.WriteLine("Exception in Direct3DReset " + ex.StackTrace);
- //Debug.WriteLine("Exception in Direct3DReset " + ex.Message);
- }
- }
- }
2.定义准备显卡硬件,和释放显卡硬件方法
定义一些变量
- /// <summary>
- /// 离屏表面
- /// </summary>
- private Surface _offscrn;
- /// <summary>
- /// 交换链
- /// </summary>
- private SwapChain _swapChain;
- private D3DImage _d3dImage = null;
- /// <summary>
- /// 准备DirectX显卡硬件
- /// </summary>
- private bool prepareHardware(VideoFormat videoFormat, int videoWidth, int videoHeight)//, VideoFormat videoFormat)
- {
- if (!DX.Available)
- return true;
- try
- {
- SlimDX.Direct3D9.Format format = SlimDX.Direct3D9.Format.A8R8G8B8;
- if (videoFormat == VideoFormat.Yuv420)
- format = (SlimDX.Direct3D9.Format)0x32315659;
- if (_offscrn != null)
- if (videoWidth == _offscrn.Description.Width && videoHeight == _offscrn.Description.Height && _offscrn.Description.Format == format)
- return true;
- releaseHardware();
- _offscrn = Surface.CreateOffscreenPlain(DX.Device, videoWidth, videoHeight, format, Pool.Default);
- PresentParameters pp = new PresentParameters();
- pp.Windowed = true;
- pp.PresentFlags = PresentFlags.Video;
- pp.SwapEffect = SwapEffect.Discard;
- pp.BackBufferCount = ;
- pp.BackBufferWidth = videoWidth;
- pp.BackBufferHeight = videoHeight;
- _swapChain = new SwapChain(DX.Device, pp);
- return true;
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 释放DirectX显卡硬件
- /// </summary>
- private void releaseHardware()
- {
- if (!DX.Available)
- return;
- if (_offscrn != null)
- if (!_offscrn.Disposed)
- _offscrn.Dispose();
- _offscrn = null;
- if (_swapChain != null)
- if (!_swapChain.Disposed)
- _swapChain.Dispose();
- _swapChain = null;
- }
3.
- private void drawFrame(VideoFormat videoFormat, int width, int height, IntPtr Y, IntPtr U, IntPtr V)
- {
- if (!prepareHardware(videoFormat, width, height))
- return;
- if (_swapChain == null)
- return;
- DataRectangle dr = _offscrn.LockRectangle(LockFlags.None);//在离屏表面上锁定一个矩形
- drawYuv420(width, height, Y, U, V, dr.Data.DataPointer, dr.Pitch);//DataPointer 内部指针指向当前流的存储备份; Pitch 两个连续的行之间的数据的字节数
- _offscrn.UnlockRectangle();//解锁矩形
- using (Surface bb = _swapChain.GetBackBuffer())//从交换链中检索一个后台缓冲区
- {
- System.Drawing.Rectangle rect = new System.Drawing.Rectangle(, , bb.Description.Width, bb.Description.Height);
- _swapChain.Device.StretchRectangle(_offscrn, rect, bb, rect, TextureFilter.None);//将后台缓冲区的内容交换到前台缓冲区
- _swapChain.Device.Present();//呈现后台缓冲区序列中下一个后台缓冲区的内容
- _d3dImage.Lock();
- _d3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, bb.ComPointer);
- _d3dImage.AddDirtyRect(new Int32Rect(, , _d3dImage.PixelWidth, _d3dImage.PixelHeight));
- _d3dImage.Unlock();
- }
- }
- private void drawYuv420(int width, int height, IntPtr Y, IntPtr U, IntPtr V, IntPtr dest, int pitch)
- {
- IntPtr py = dest;
- IntPtr pv = py + (pitch * height);
- IntPtr pu = pv + ((pitch * height) / );
- int w2 = width / , pitch2 = pitch / ;
- for (int y = ; y < height; y++)
- {
- CopyMemory(py, Y + y * width, (uint)width);
- py += pitch;
- if ((y & ) != )
- continue;
- int offset = y / * w2;
- CopyMemory(pu, U + offset, (uint)w2);
- CopyMemory(pv, V + offset, (uint)w2);
- pu += pitch2;
- pv += pitch2;
- }
- }
- [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
- private static extern void CopyMemory(IntPtr Destination, IntPtr Source, uint Length);
SlimDX和WPF的合作应用的更多相关文章
- WPF特点
前言:为什么要学习WPF呢?因为随着现阶段硬件技术的升级以及客户对体验的要求越来越高,传统的GDI和USERS(或者是GDI+.USERS)已经不能满足这个需求,因此,WPF技术应运而生. WPF的特 ...
- WPF开发中Designer和码农之间的合作
想要用WPF做出一流的软件界面, 必须要Designer和码农通力合作.理想的情况是平时并行开发,Designer用Expression套件(包括Design和Blend)来设计界面,码农开发Mode ...
- 年度巨献-WPF项目开发过程中WPF小知识点汇总(原创+摘抄)
WPF中Style的使用 Styel在英文中解释为”样式“,在Web开发中,css为层叠样式表,自从.net3.0推出WPF以来,WPF也有样式一说,通过设置样式,使其WPF控件外观更加美化同时减少了 ...
- WPF 3D 知识点大全以及实例
引言 现在物联网概念这么火,如果监控的信息能够实时在手机的客服端中以3D形式展示给我们,那种体验大家可以发挥自己的想象. 那生活中我们还有很多地方用到这些,如上图所示的Kinect 在医疗上的应用,当 ...
- 第一个WPF应用程序
WPF 全称为 Windows Presentation Foundation. 核心特性: WPF使用一种新的XAML(Extensible Application Markup Language) ...
- 2012开源项目计划-WPF企业级应用整合平台
2012开源项目计划-WPF企业级应用整合平台 开篇 2012年,提前祝大家新年快乐,为了加快2012年的开发计划,特打算年前和大家分享一下2012年的开发计划和年后具体的实施计划,希望有兴趣或者有志 ...
- 一、什么是WPF?
一.什么是WPF? Windows Presentation Foundation(以前的代号为“Avalon”)是 Microsoft 用于 Windows 的统一显示子系统,它通过 WinFX 公 ...
- wpf做的可扩展记事本
记得有个winform利用反射做的可扩展笔记本,闲来无事,便用wpf也搞了个可扩展记事本,可用接口动态扩展功能,较简单,以便参考: 目录结构如下: MainWindow.xaml为主功能界面,Func ...
- vs2012用wpf制作透明窗口中报错的解决方案
在开发wpf项目时,需要调用外部com组件,同时需要制作透明窗口,于是问题出现了,当我们在设置 AllowsTransparency="True"后,com组件显示不出来了,只有透 ...
随机推荐
- 火狐Firefox 浏览器 onblur() 并且alert()时文本被选中问题
说明:镜像是组成在线实验课程的基础环境,教师设计的实验绑定一个或多个镜像,就组成了一讲独立的在线实验课程. 镜像名称: 火狐Firefox 浏览器 onblur() 并且alert()时文本被 ...
- Symfony2 Doctrine从现有Database生成Entity(转载自http://blog.it985.com/6809.html)
在我的以前一章Symfony之十分钟入门说了怎样生成数据库,然后设计实体Entity,再同步数据库的表结构,一般我们的顺序都是这样:生成数据库->设计实体Entity->同步数据库表结构. ...
- js获取IP地址的方法小结
s代码获取IP地址的三种方法,在js中取得客户端的IP地址. 原文地址:http://www.jbxue.com/article/11338.html 1,js取得IP地址的方法一 <scrip ...
- 关于Django模板渲染一个很重要的用途
一般情况下我们在模板利用django的for标签循环生成html代码时,可以同时生成形如: "{% url 'dormitory:hygiene_detail' pk={{ id }} %} ...
- Xshell4连接Linux后 win快捷键锁屏
今天在使用Xshell连接CentOS后 使用Vim编辑器编辑完后 习惯性的按了Ctrl+S 然后按什么都不起作用 只能重新连接 通过查资料得知 Ctrl + S 是Linux 锁屏的快捷键 要解除锁 ...
- Powershell 快捷键
Powershell的快捷键和cmd,linux中的shell,都比较像. ALT+F7 清除命令的历史记录PgUp PgDn 显示当前会话的第一个命令和最后一个命令Enter 执行当前命令End 将 ...
- uva10245-The Closest Pair Problem(平面上的点分治)
解析:平面上的点分治,先递归得到左右子区间的最小值d,再处理改区间,肯定不会考虑哪些距离已经大于d的点对,对y坐标归并排序,然后从小到大开始枚举更新d,对于某个点,x轴方向只用考虑[x-d,x+d]( ...
- 【POJ3006】Dirichlet's Theorem on Arithmetic Progressions(素数筛法)
简单的暴力筛法就可. #include <iostream> #include <cstring> #include <cmath> #include <cc ...
- Hive 3、Hive 的安装配置(本地derby模式)
这种方式是最简单的存储方式,只需要在hive-site.xml做如下配置便可; $ vim hive-site.xml <configuration> <property> ...
- [转]Binarized Neural Networks_ Training Neural Networks with Weights and Activations Constrained to +1 or −1
原文: 二值神经网络(Binary Neural Network,BNN) 在我刚刚过去的研究生毕设中,我在ImageNet数据集上验证了图像特征二值化后仍然具有很强的表达能力,可以在检索中达到较好的 ...