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的合作应用的更多相关文章

  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. 微信JS-SDK 接口调用与 php 遇到的坑

    问题:config:invalid signature一直爆这个错误 解决: 看我把这些坑都总结了一下:要命的invalid signature. https://segmentfault.com/q ...

  2. 用python随机生成数据,再插入到postgresql中

    用python随机生成学生姓名,三科成绩和班级数据,再插入到postgresql中. 模块用psycopg2 random import random import psycopg2 fname=[' ...

  3. 函数:递归是神马 - 零基础入门学习Python022

    函数:递归是神马 让编程改变世界 Change the world by program 我们这节课的主题叫递归是神马,将通过小甲鱼带感的讲解,来告诉大家神马是递归!如果说优秀的程序员是伯乐,那么把递 ...

  4. 异步编程设计模式 - IronPythonDebugger

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsof ...

  5. C51变量的存储

    一.全局变量和局部变量 全局变量和局部变量的区别在于作用域的不同.此外还有静态全局变量和静态局部变量. 全局变量作用域为全局,在一个源文件中定义,其他的源文件也可以应用.在其他的源文件中使用exter ...

  6. JavaEE连接池泄漏问题检测Oracle数据库

    1.项目环境 项目是典型的轻量级JavaEE项目,使用SSH框架构建,数据源使用DBCP管理,和Spring进行了整合. 项目数据库使用Oracle数据库. 项目DBCP配置内容如下 ###### D ...

  7. windows 守护进程

    use Win32::Process::Info; while (1==1){ use Sys::Hostname; use HTTP::Date qw(time2iso str2time time2 ...

  8. IO模型总结

    总结 幽默讲解 linux 的 Socket IO 模型(上)

  9. ubuntu 14.04 下试用Sublime Text 3

    很多源代码都没有IDE支持的,尤其是开源的源代码.从github上下载的,很多也不用IDE.包括我自己公司的代码,基本都是脚本,也不用IDE.通常情况下,都是用notepad++.UE之类的文本编辑器 ...

  10. operator模块

    # -*- coding: utf-8 -*- # ==================== #File: python #Author: python #Date: 2014 #========== ...