Render Targets, Devices, and Resources
渲染目标,设备和资源
渲染目标就是我们程序准备画图的地方。一般来说,渲染目标是一个窗口,也可以是一个内存中的位图(bitmap),例如GDI做的backbuffer。Direct2D中的渲染目标是由ID2D1RenderTarget接口代表的。
设备是一个抽象概念,代表实际执行显示pixels的对象。硬件设备就是GPU,软件设备就是CPU,这就是所谓硬渲染和软渲染的来由。程序并不创建设备。而是,当程序创建渲染目标的时候,设备隐式创建,每个渲染目标都是和特定的设备关联的,硬件或者是软件。
资源是一个对象,程序利用这样的资源来画图。下面是一些Direct2D资源的例子:
- Brush. Controls how lines and regions are painted. Brush types include solid-color brushes and gradiant brushes.
- Stroke style. Controls the appearance of a line—for example, dashed or solid.
- Geometry. Represents a collection of lines and curves.
- Mesh. A shape formed out of triangles. Mesh data can be consumed directly by the GPU, unlike geometry data, which must be converted before rendering.
渲染目标也可以认为是一种资源。
资源可以分为依赖设备的(device-dependent)和不依赖设备的(device-independent)。
依赖资源的:某些资源可以由硬件加速。资源通常也是和某一特定设备关联的,硬件(GPU)或软件(CPU)。例如Brushes和meshes。如果设备变得不可用了,那么子玉就必须重新为新的设备创建。
不依赖资源的:保留在CPU内存中,而不需要管使用什么设备。当设备改变的时候,不必要重新创建。例如:Strock styles和geometries。
Direct2D的所有资源是由ID2D1Resource衍生的接口代表的。例如:brushes是由ID2D1Brush接口提供。
The Direct2D Factory Object
使用Direct2D的第一步就是创建一个Direct2D工厂对象的实例。
The Direct2D factory creates the following types of objects:
- Render targets.
- Device-independent resources, such as stroke styles and geometries.
Device-dependent resources, 例如: brushes and bitmaps, 是由渲染目标对象创建的。
To create the Direct2D factory object, call the D2D1CreateFactory function.
ID2D1Factory *pFactory = NULL;
HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
我们应该创建the Direct2D factory object ,在第一个WM_PAINT 消息前,一般在WM_CREATE消息中创建。
case WM_CREATE:
if (FAILED(D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory)))
{
return -1; // Fail CreateWindowEx.
}
return 0;
Creating Direct2D Resources
创建资源,如:
- A render target that is associated with the application window.
- A solid-color brush to paint the circle.
每个资源都是由COM接口代表的:
- The ID2D1HwndRenderTarget interface represents the render target.
- The ID2D1SolidColorBrush interface represents the brush.
ID2D1HwndRenderTarget *pRenderTarget;
ID2D1SolidColorBrush *pBrush;
The following code creates these two resources.
HRESULT MainWindow::CreateGraphicsResources()
{
HRESULT hr = S_OK;
if (pRenderTarget == NULL)
{
RECT rc;
GetClientRect(m_hwnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
hr = pFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(m_hwnd, size),
&pRenderTarget);
if (SUCCEEDED(hr))
{
const D2D1_COLOR_F color = D2D1::ColorF(1.0f, 1.0f, 0);
hr = pRenderTarget->CreateSolidColorBrush(color, &pBrush);
if (SUCCEEDED(hr))
{
CalculateLayout();
}
}
}
return hr;
}
--MSND