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组件显示不出来了,只有透 ...
随机推荐
- 从运行原理及使用场景看Apache和Nginx
用正确的工具,做正确的事情. 本文只作为了解Apache和Nginx知识的一个梳理,想详细了解的请阅读文末参考链接中的博文. Web服务器 Web服务器也称为WWW(WORLD WIDE WEB)服务 ...
- The Suspects(POJ 1611 并查集)
The Suspects Time Limit: 1000MS Memory Limit: 20000K Total Submissions: 30158 Accepted: 14665 De ...
- 对163k地方门户网站系统QQ互联功能修改
163k地方门户网站QQ互联申请时遇到的问题: "禁止开发商强制用户重新注册或绑定其他帐号" 原因是用户登录完QQ还需要注册帐号或者绑定原有帐号 163k地方门户网站的QQ互联登录 ...
- POJ 3675 Telescope
题意:给定一个不自交的多边形,要求和圆心在原点的圆的面积交. 思路:同POJ2986,是加强版 代码: #include<algorithm> #include<cstdio> ...
- Android的init过程详解(一)(转)
本文使用的软件版本 Android:4.2.2 Linux内核:3.1.10 本文及后续几篇文章将对Android的初始化(init)过程进行详细地.剥丝抽茧式地分析,并且在其中穿插了大量的知识,希望 ...
- Unix/Linux环境C编程入门教程(42) 终端控制篇
函数介绍 getopt(分析命令行参数) 相关函数 表头文件 #include<unistd.h> 定义函数 int getopt(int argc,char * const argv[ ...
- unix c 01
gcc编译器(代码的 预处理/汇编/编译/连接) C程序员一般写程序会定义 .c和.h两种文件 .c文件(源文件)中一般放代码的实现,.h文件(头文件)中放 各种声明和定义. gcc -E __. ...
- sql server 2008 在与 SQL Server 提示建立连接时出现与网络相关的或特定于实例的错误
原文地址:http://zhidao.baidu.com/link?url=Ndav32DO9zL5XnltqoqlhvKHbJv_n3Zwihhw4cwF9ffNq8hb8z7h7n3vJVfoeW ...
- IO模型总结
总结 幽默讲解 linux 的 Socket IO 模型(上)
- JavaScript面向对象之类的继承
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...