2015年9月25日金曜日

DXGIFactoryの生成または取得方法

生成または取得する方法がいくつかあるのでまとめておきます.

#include <Windows.h>
#include <tchar.h>
#include <wrl/client.h>
#include <d3d11_3.h>
#include <dxgi1_4.h>

#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")

using namespace Microsoft::WRL;
using namespace std;

int WINAPI wWinMain(
    HINSTANCE hInstance,
    HINSTANCE,
    LPWSTR lpCmdLine,
    int nCmdShow
)
{
    HRESULT hr = S_OK;

    // CreateDXGIFactoryによるDXGIFactoryの生成
    {
        ComPtr<idxgifactory> pFactory;
        hr = CreateDXGIFactory(
            IID_PPV_ARGS(pFactory.GetAddressOf())
        );
        if(FAILED(hr)) { return 0; }

        // インターフェースがサポートされていない,と失敗する
        // ComPtr<idxgifactory1> pFactory1;
        // hr = pFactory.As(&pFactory1);
        // if(FAILED(hr)) { return 0; }
    }

    // CreateDXGIFactory1によるDXGIFactory1の生成 (Windows 7以降)
    {
        ComPtr<idxgifactory1> pFactory1;
        hr = CreateDXGIFactory1(
            IID_PPV_ARGS(pFactory1.GetAddressOf())
        );
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory> pFactory;
        hr = pFactory1.As(&pFactory);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory3> pFactory3;
        hr = pFactory1.As(&pFactory3);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory4> pFactory4;
        hr = pFactory1.As(&pFactory4);
        if(FAILED(hr)) { return 0; }
    }

    // CreateDXGIFactory2によるDXGIFactory2の生成 (Windows 8.1以降)
    {
        ComPtr<idxgifactory2> pFactory2;
        ULONG creationFlag = 0;
#ifdef _DEBUG
        creationFlag |= DXGI_CREATE_FACTORY_DEBUG;
#endif

        hr = CreateDXGIFactory2(
            creationFlag,
            IID_PPV_ARGS(pFactory2.GetAddressOf())
        );
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory> pFactory;
        hr = pFactory2.As(&pFactory);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory1> pFactory1;
        hr = pFactory2.As(&pFactory1);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory3> pFactory3;
        hr = pFactory2.As(&pFactory3);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory4> pFactory4;
        hr = pFactory2.As(&pFactory4);
        if(FAILED(hr)) { return 0; }
    }

    // D3D機能レベルの一覧を用意
    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_12_1,
        D3D_FEATURE_LEVEL_12_0,
        D3D_FEATURE_LEVEL_11_1,
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
        D3D_FEATURE_LEVEL_9_3,
        D3D_FEATURE_LEVEL_9_2,
        D3D_FEATURE_LEVEL_9_1,
    };
    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_9_1;
    UINT deviceCreationFlag = 0;

    // D3D11デバイスおよびイメディエイトコンテキストの生成
    ComPtr<id3d11device> pDevice;
    ComPtr<id3d11devicecontext> pImmediateContext;
    hr = D3D11CreateDevice(
        nullptr,
        D3D_DRIVER_TYPE_HARDWARE,
        nullptr,
        deviceCreationFlag,
        featureLevels,
        _countof(featureLevels),
        D3D11_SDK_VERSION,
        pDevice.GetAddressOf(),
        &featureLevel,
        pImmediateContext.GetAddressOf()
    );
    if(FAILED(hr)) { return 0; }

    ComPtr<idxgidevice> pDXGIDevice;
    hr = pDevice.As(&pDXGIDevice);
    if(FAILED(hr)) { return 0; }

    // D3D11DeviceからDXGIDeviceを取得し,
    // DXGIDeviceからDXGIAdapterを取得し,
    // DXGIAdapterの親であるDXGIFactoryを取得する.
    // そこからIDXGIFactory1,2,3,4を取得する.
    {
        ComPtr<idxgiadapter> pDXGIAdapter;
        hr = pDXGIDevice->GetAdapter(
            pDXGIAdapter.GetAddressOf()
        );
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory> pFactory;
        hr = pDXGIAdapter->GetParent(
            IID_PPV_ARGS(pFactory.GetAddressOf())
        );
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory1> pFactory1;
        hr = pFactory.As(&pFactory1);
        if(FAILED(hr)) { return 0; }なn

        ComPtr<idxgifactory2> pFactory2;
        hr = pFactory.As(&pFactory2);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory3> pFactory3;
        hr = pFactory.As(&pFactory3);
        if(FAILED(hr)) { return 0; }

        ComPtr<idxgifactory4> pFactory4;
        hr = pFactory.As(&pFactory4);
        if(FAILED(hr)) { return 0; }
    }

    return 0;
}

CreateDXGIFactoryでDXGIFactoryを生成した場合,以降のIDXGIFactory1,2,3,4のインターフェースをサポートしたオブジェクトにはならないようです.

ところで,D3D11DeviceからDXGIDeviceを取得できるって,どこかに関係の説明があるんでしょうか?
MSDNにサンプルがあったのでこうできるというのは分かったんですが,その関係性が書いてあるドキュメントが見つけられないんですよね.

2015/09/26 追記

IDXGIDeviceのドキュメントが2つあって,
こちらには情報が載っていなくて,
こちらには載っていました.
何なんだろう.

IDXGIAdapter,IDXGIAdapter1,IDXGIAdapter2,IDXGIAdapter3のインターフェース

IDXGIAdapter

メソッド名説明
CheckInterfaceSupport Checks whether the system supports a device interface for a graphics component.
EnumOutputs Enumerate adapter (video card) outputs.
GetDesc Gets a DXGI 1.0 description of an adapter (or video card).

IDXGIAdapter1

メソッド名説明
GetDesc1 Gets a DXGI 1.1 description of an adapter (or video card).

IDXGIAdapter2

メソッド名説明
GetDesc2 Gets a DXGI 1.2 description of an adapter or video card. This description includes information about the granularity at which the GPU can be preempted from performing its current task.

IDXGIAdapter3

メソッド名説明
QueryVideoMemoryInfo This method informs the process of the current budget and process usage.
RegisterHardwareContentProtectionTeardownStatusEvent Registers to receive notification of hardware content protection teardown events.
RegisterVideoMemoryBudgetChangeNotificationEvent This method establishes a correlation between a CPU synchronization object and the budget change event.
SetVideoMemoryReservation This method sends the minimum required physical memory for an application, to the OS.
UnregisterHardwareContentProtectionTeardownStatus Unregisters an event to stop it from receiving notification of hardware content protection teardown events.
UnregisterVideoMemoryBudgetChangeNotification This method stops notifying a CPU synchronization object whenever a budget change occurs. An application may switch back to polling the information regularly.

IDXGIFactory,IDXGIFactory1,IDXGIFactory2,IDXGIFactory3,IDXGIFactory4のインターフェース

IDXGIFactory

メソッド名 説明
CreateSoftwareAdapter Create an adapter interface that represents a software adapter.
CreateSwapChain Creates a swap chain.
Note Starting with Direct3D 11.1, we recommend not to use CreateSwapChain anymore to create a swap chain. Instead, use CreateSwapChainForHwnd, CreateSwapChainForCoreWindow, or CreateSwapChainForComposition depending on how you want to create the swap chain.
EnumAdapters Enumerates the adapters (video cards).
GetWindowAssociation Get the window through which the user controls the transition to and from full screen.
MakeWindowAssociation Allows DXGI to monitor an application's message queue for the alt-enter key sequence (which causes the application to switch from windowed to full screen or vice versa).

IDXGIFactory1

メソッド名 説明
EnumAdapters1 Enumerates both adapters (video cards) with or without outputs.
IsCurrent Informs an application of the possible need to re-enumerate adapters.

IDXGIFactory2

メソッド名 説明
CreateSwapChainForComposition Creates a swap chain that you can use to send Direct3D content into the DirectComposition API or the Windows.UI.Xaml framework to compose in a window.
CreateSwapChainForCoreWindow Creates a swap chain that is associated with the CoreWindow object for the output window for the swap chain.
CreateSwapChainForHwnd Creates a swap chain that is associated with an HWND handle to the output window for the swap chain.
GetSharedResourceAdapterLuid Identifies the adapter on which a shared resource object was created.
IsWindowedStereoEnabled Determines whether to use stereo mode.
RegisterOcclusionStatusEvent Registers to receive notification of changes in occlusion status by using event signaling.
RegisterOcclusionStatusWindow Registers an application window to receive notification messages of changes of occlusion status.
RegisterStereoStatusEvent Registers to receive notification of changes in stereo status by using event signaling.
RegisterStereoStatusWindow Registers an application window to receive notification messages of changes of stereo status.
UnregisterOcclusionStatus Unregisters a window or an event to stop it from receiving notification when occlusion status changes.
UnregisterStereoStatus Unregisters a window or an event to stop it from receiving notification when stereo status changes.

IDXGIFactory3

メソッド名 説明
GetCreationFlags DXGIオブジェクトが生成された際のフラグを取得する.

IDXGIFactory4

メソッド名 説明
EnumAdapterByLuid 指定されたLUIDのIDXGIAdapterを出力する.
EnumWarpAdapter Provides an adapter which can be provided to D3D12CreateDevice to use the WARP renderer.

2015年9月24日木曜日

Googleによる新しい圧縮アルゴリズム Brotliを試してみた.

Google、新しい圧縮アルゴリズム「Brotli」公開 (マイナビニュース)

google/brotli (GitHub)

GitHubでコードが公開されていたので,さっそく試してみました.

このコードは,Windows 10上のVisual Studio 2015 Communityで試しています.

  • main.cpp
  • dec (brotliのdecフォルダをコピー)
  • enc (brotliのencフォルダをコピー)

decとencをコピーした上で,プロジェクトに全てのファイルを組み込みます.
この際に,decとencには一部同名のファイルがあるため,オブジェクトファイルが被らないように,
出力フォルダを分けておきます.

後は,次のようなコードで圧縮と解凍ができます.


// main.cpp
#include <iostream>
#include <string>
#include <memory>
#include <cstdio>
#include <cstdlib>
#include <enc/streams.h>
#include <enc/encode.h>
#include <dec/streams.h>
#include <dec/decode.h>

int main(int argc, char * argv[])
{
    FILE * fout = fopen("main.cpp.brotli", "wb");
    if(!fout) { return -1; }

    FILE * fin = fopen("main.cpp", "rb");
    if(!fin) { return -1; }

    fseek(fin, 0, SEEK_END);
    auto size = ftell(fin);
    fseek(fin, 0, SEEK_SET);

    {
        brotli::BrotliFileOut bfout(fout);
        brotli::BrotliFileIn bfin(fin, size);

        // 圧縮時の設定ができる
        brotli::BrotliParams params;

        // true of falseが返る
        if(brotli::BrotliCompress(params, &bfin, &bfout))
        {
            std::cout << "圧縮に成功しました." << std::endl;
        }
        else
        {
            std::cerr << "圧縮に失敗しました." << std::endl;
            return -1;
        }
    }

    fclose(fout);
    fclose(fin);

    fin = fopen("main.cpp.brotli", "rb");
    fseek(fin, 0, SEEK_END);
    auto compressed_size = ftell(fin);
    fseek(fin, 0, SEEK_SET);
    std::string buffer;

    {
        std::unique_ptr<char[]> buffer(new char[size + 1]);
        buffer[size] = '\0';

        // メモリ出力用の構造体
        BrotliMemOutput output;

        // 解凍関数呼び出し
        auto result = BrotliDecompress(
            BrotliFileInput(fin),
            BrotliInitMemOutput(
                reinterpret_cast<uint8_t *>(buffer.get()),
                size,
                &output
            )
        );

        switch(result)
        {
        case BROTLI_RESULT_ERROR:
            std::cerr << "何らかのエラーが発生しました." << std::endl;
            return -1;
        case BROTLI_RESULT_NEEDS_MORE_INPUT:
            std::cerr << "解凍に必要な入力が不足しています." << std::endl;
            return -1;
        case BROTLI_RESULT_NEEDS_MORE_OUTPUT:
            std::cerr << "解凍先のバッファが不足しています." << std::endl;
            return -1;
        case BROTLI_RESULT_SUCCESS:
            std::cout << "解凍に成功しました." << std::endl;
            break;
        default:
            std::cerr << "未知のエラーが発生しました." << std::endl;
            return -1;
        }

        std::cout << buffer.get() << std::endl;
    }

    fclose(fin);

    return system("pause");
}

軽く触ってみた感じで,圧縮と解凍でAPIに対称性が無い感じがする(片方は名前空間に入っていて,もう片方は入っていない,だったり,入出力用のストリームの構造であったり)ので,
そのうちAPIは変更されるんじゃないかなぁ,という気がします.

結果はこんな感じです.
圧縮方法 結果サイズ (バイト)
無圧縮 2,487
brotli 728
zip 1,054

BrotliParamsに設定する値がデフォルトでは一番圧縮率が高くなる(その分処理が重い)になっているので,
その辺変更すると多少変わるかもしれませんが,デフォルトだと単なるzip圧縮よりも圧縮されていますね.

2015年9月17日木曜日

ID3D11DeviceContext,ID3D11DeviceContext1,ID3D11DeviceContext2,ID3D11DeviceContext3のインターフェース

一か所にまとまっていて欲しかった.

ID3D11DeviceContext

メソッド名 説明
Begin Mark the beginning of a series of commands.
ClearDepthStencilView Clears the depth-stencil resource.
ClearRenderTargetView Set all the elements in a render target to one value.
ClearState Restore all default settings.
ClearUnorderedAccessViewUint Clears an unordered access resource with a float value.
ClearUnorderedAccessViewFloat Clears an unordered access resource with bit-precise values.
CopyResource Copy the entire contents of the source resource to the destination resource using the GPU.
CopyStructureCount Copies data from a buffer holding variable length data.
CopySubresourceRegion Copy a region from a source resource to a destination resource.
CSGetConstantBuffers Get the constant buffers used by the compute-shader stage.
CSGetSamplers Get an array of sampler state interfaces from the compute-shader stage.
CSGetShader Get the compute shader currently set on the device.
CSGetShaderResources Get the compute-shader resources.
CSGetUnorderedAccessViews Gets an array of views for an unordered resource.
CSSetConstantBuffers Sets the constant buffers used by the compute-shader stage.
CSSetSamplers Set an array of sampler states to the compute-shader stage.
CSSetShader Set a compute shader to the device.
CSSetShaderResources Bind an array of shader resources to the compute-shader stage.
CSSetUnorderedAccessViews Sets an array of views for an unordered resource.
Dispatch Execute a command list from a thread group.
DispatchIndirect Execute a command list over one or more thread groups.
Draw Draw non-indexed, non-instanced primitives.
DrawAuto Draw geometry of an unknown size.
DrawIndexed Draw indexed, non-instanced primitives.
DrawIndexedInstanced Draw indexed, instanced primitives.
DrawIndexedInstancedIndirect Draw indexed, instanced, GPU-generated primitives.
DrawInstanced Draw non-indexed, instanced primitives.
DrawInstancedIndirect Draw instanced, GPU-generated primitives.
DSGetConstantBuffers Get the constant buffers used by the domain-shader stage.
DSGetSamplers Get an array of sampler state interfaces from the domain-shader stage.
DSGetShader Get the domain shader currently set on the device.
DSGetShaderResources Get the domain-shader resources.
DSSetConstantBuffers Sets the constant buffers used by the domain-shader stage.
DSSetSamplers Set an array of sampler states to the domain-shader stage.
DSSetShader Set a domain shader to the device.
DSSetShaderResources Bind an array of shader resources to the domain-shader stage.
End Mark the end of a series of commands.
ExecuteCommandList Queues commands from a command list onto a device.
FinishCommandList Create a command list and record graphics commands into it.
Flush Sends queued-up commands in the command buffer to the GPU.
GenerateMips Generates mipmaps for the given shader resource.
GetContextFlags Gets the initialization flags associated with the current deferred context.
GetData Get data from the GPU asynchronously.
GetPredication Get the rendering predicate state.
GetResourceMinLOD Gets the minimum level-of-detail (LOD).
GetType Gets the type of device context.
GSGetConstantBuffers Get the constant buffers used by the geometry shader pipeline stage.
GSGetSamplers Get an array of sampler state interfaces from the geometry shader pipeline stage.
GSGetShader Get the geometry shader currently set on the device.
GSGetShaderResources Get the geometry shader resources.
GSSetConstantBuffers Sets the constant buffers used by the geometry shader pipeline stage.
GSSetSamplers Set an array of sampler states to the geometry shader pipeline stage.
GSSetShader Set a geometry shader to the device.
GSSetShaderResources Bind an array of shader resources to the geometry shader stage.
HSGetConstantBuffers Get the constant buffers used by the hull-shader stage.
HSGetSamplers Get an array of sampler state interfaces from the hull-shader stage.
HSGetShader Get the hull shader currently set on the device.
HSGetShaderResources Get the hull-shader resources.
HSSetConstantBuffers Set the constant buffers used by the hull-shader stage.
HSSetSamplers Set an array of sampler states to the hull-shader stage.
HSSetShader Set a hull shader to the device.
HSSetShaderResources Bind an array of shader resources to the hull-shader stage.
IAGetIndexBuffer Get a pointer to the index buffer that is bound to the input-assembler stage.
IAGetInputLayout Get a pointer to the input-layout object that is bound to the input-assembler stage.
IAGetPrimitiveTopology Get information about the primitive type, and data order that describes input data for the input assembler stage.
IAGetVertexBuffers Get the vertex buffers bound to the input-assembler stage.
IASetIndexBuffer Bind an index buffer to the input-assembler stage.
IASetInputLayout Bind an input-layout object to the input-assembler stage.
IASetPrimitiveTopology Bind information about the primitive type, and data order that describes input data for the input assembler stage.
IASetVertexBuffers Bind an array of vertex buffers to the input-assembler stage.
Map Gets a pointer to the data contained in a subresource, and denies the GPU access to that subresource.
OMGetBlendState Get the blend state of the output-merger stage.
OMGetDepthStencilState Gets the depth-stencil state of the output-merger stage.
OMGetRenderTargets Get pointers to the resources bound to the output-merger stage.
OMGetRenderTargetsAndUnorderedAccessViews Get pointers to the resources bound to the output-merger stage.
OMSetBlendState Set the blend state of the output-merger stage.
OMSetDepthStencilState Sets the depth-stencil state of the output-merger stage.
OMSetRenderTargets Bind one or more render targets atomically and the depth-stencil buffer to the output-merger stage.
OMSetRenderTargetsAndUnorderedAccessViews Binds resources to the output-merger stage.
PSGetConstantBuffers Get the constant buffers used by the pixel shader pipeline stage.
PSGetSamplers Get an array of sampler states from the pixel shader pipeline stage.
PSGetShader Get the pixel shader currently set on the device.
PSGetShaderResources Get the pixel shader resources.
PSSetConstantBuffers Sets the constant buffers used by the pixel shader pipeline stage.
PSSetSamplers Set an array of sampler states to the pixel shader pipeline stage.
PSSetShader Sets a pixel shader to the device.
PSSetShaderResources Bind an array of shader resources to the pixel shader stage.
RSGetScissorRects Copy a multisampled resource into a non-multisampled resource.
ResolveSubresource Get the array of scissor rectangles bound to the rasterizer stage.
RSGetState Get the rasterizer state from the rasterizer stage of the pipeline.
RSGetViewports Gets the array of viewports bound to the rasterizer stage.
RSSetScissorRects Bind an array of scissor rectangles to the rasterizer stage.
RSSetState Set the rasterizer state for the rasterizer stage of the pipeline.
RSSetViewports Bind an array of viewports to the rasterizer stage of the pipeline.
SetPredication Set a rendering predicate.
SetResourceMinLOD Sets the minimum level-of-detail (LOD) for a resource.
SOGetTargets Get the target output buffers for the stream-output stage of the pipeline.
SOSetTargets Set the target output buffers for the stream-output stage of the pipeline.
Unmap Invalidate the pointer to a resource and reenable the GPU's access to that resource.
UpdateSubresource The CPU copies data from memory to a subresource created in non-mappable memory.
VSGetConstantBuffers Get the constant buffers used by the vertex shader pipeline stage.
VSGetSamplers Get an array of sampler states from the vertex shader pipeline stage.
VSGetShader Get the vertex shader currently set on the device.
VSGetShaderResources Get the vertex shader resources.
VSSetConstantBuffers Sets the constant buffers used by the vertex shader pipeline stage.
VSSetSamplers Set an array of sampler states to the vertex shader pipeline stage.
VSSetShader Set a vertex shader to the device.
VSSetShaderResources Bind an array of shader resources to the vertex-shader stage.

ID3D11DeviceContext1

メソッド名 説明
ClearView Sets all the elements in a resource view to one value.
CopySubresourceRegion1 Copies a region from a source resource to a destination resource.
CSGetConstantBuffers1 Gets the constant buffers that the compute-shader stage uses.
CSSetConstantBuffers1 Sets the constant buffers that the compute-shader stage uses.
DiscardResource Discards a resource from the device context.
DiscardView Discards a resource view from the device context.
DiscardView1 Discards the specified elements in a resource view from the device context.
DSGetConstantBuffers1 Gets the constant buffers that the domain-shader stage uses.
DSSetConstantBuffers1 Sets the constant buffers that the domain-shader stage uses.
GSGetConstantBuffers1 Gets the constant buffers that the geometry shader pipeline stage uses.
GSSetConstantBuffers1 Sets the constant buffers that the geometry shader pipeline stage uses.
HSGetConstantBuffers1 Gets the constant buffers that the hull-shader stage uses.
HSSetConstantBuffers1 Sets the constant buffers that the hull-shader stage uses.
PSGetConstantBuffers1 Gets the constant buffers that the pixel shader pipeline stage uses.
PSSetConstantBuffers1 Sets the constant buffers that the pixel shader pipeline stage uses.
SwapDeviceContextState Activates the given context state object and changes the current device behavior to Direct3D 11, Direct3D 10.1, or Direct3D 10.
UpdateSubresource1 The CPU copies data from memory to a subresource created in non-mappable memory.
VSGetConstantBuffers1 Gets the constant buffers that the vertex shader pipeline stage uses.
VSSetConstantBuffers1 Sets the constant buffers that the vertex shader pipeline stage uses.

ID3D11DeviceContext2

メソッド名 説明
UpdateTiles Updates tiles by copying from app memory to the tiled resource.
BeginEventInt Allows applications to annotate the beginning of a range of graphics commands.
CopyTileMappings Copies mappings from a source tiled resource to a destination tiled resource.
CopyTiles Copies tiles from buffer to tiled resource or vice versa.
EndEvent Allows applications to annotate the end of a range of graphics commands.
IsAnnotationEnabled Allows apps to determine when either a capture or profiling request is enabled.
ResizeTilePool Resizes a tile pool.
SetMarkerInt Allows applications to annotate graphics commands.
TiledResourceBarrier Specifies a data access ordering constraint between multiple tiled resources. For more info about this constraint, see Remarks.
UpdateTileMappings Updates mappings of tile locations in tiled resources to memory locations in a tile pool.

ID3D11DeviceContext3

メソッド名 説明
Flush1 Sends queued-up commands in the command buffer to the graphics processing unit (GPU), with a specified context type and an optional event handle to create an event query.
GetHardwareProtectionState Gets whether hardware protection is enabled.
SetHardwareProtectionState Sets the hardware protection state.

2015年9月16日水曜日

ID3DDevice,ID3DDevice1,ID3DDevice2,ID3DDevice3のインターフェース

一か所にまとまっていて欲しかった.

ID3DDevice

メソッド名 説明
CheckCounter Get the type, name, units of measure, and a description of an existing counter.
CheckCounterInfo Get a counter's information.
CheckFeatureSupport Gets information about the features that are supported by the current graphics driver.
CheckFormatSupport Get the support of a given format on the installed video device.
CheckMultisampleQualityLevels Get the number of quality levels available during multisampling.
CreateBlendState Create a blend-state object that encapsules blend state for the output-merger stage.
CreateBuffer Creates a buffer (vertex buffer, index buffer, or shader-constant buffer).
CreateClassLinkage Creates class linkage libraries to enable dynamic shader linkage.
CreateComputeShader Create a compute shader.
CreateCounter Create a counter object for measuring GPU performance.
CreateDeferredContext Creates a deferred context, which can record command lists.
CreateDepthStencilState Create a depth-stencil state object that encapsulates depth-stencil test information for the output-merger stage.
CreateDepthStencilView Create a depth-stencil view for accessing resource data.
CreateDomainShader Create a domain shader .
CreateGeometryShader Create a geometry shader.
CreateGeometryShaderWithStreamOutput Creates a geometry shader that can write to streaming output buffers.
CreateHullShader Create a hull shader.
CreateInputLayout Create an input-layout object to describe the input-buffer data for the input-assembler stage.
CreatePixelShader Create a pixel shader.
CreatePredicate Creates a predicate.
CreateQuery This interface encapsulates methods for querying information from the GPU.
CreateRasterizerState Create a rasterizer state object that tells the rasterizer stage how to behave.
CreateRenderTargetView Creates a render-target view for accessing resource data.
CreateSamplerState Create a sampler-state object that encapsulates sampling information for a texture.
CreateShaderResourceView Create a shader-resource view for accessing data in a resource.
CreateTexture1D Creates an array of 1D textures.
CreateTexture2D Create an array of 2D textures.
CreateTexture3D Create a single 3D texture.
CreateUnorderedAccessView Creates a view for accessing an unordered access resource.
CreateVertexShader Create a vertex-shader object from a compiled shader.
GetCreationFlags Get the flags used during the call to create the device with D3D11CreateDevice.
GetDeviceRemovedReason Get the reason why the device was removed.
GetExceptionMode Get the exception-mode flags.
GetFeatureLevel Gets the feature level of the hardware device.
GetImmediateContext Gets an immediate context, which can play back command lists.
GetPrivateData Get application-defined data from a device.
OpenSharedResource Give a device access to a shared resource created on a different device.
SetExceptionMode Get the exception-mode flags.
SetPrivateData Set data to a device and associate that data with a guid.
SetPrivateDataInterface Associate an IUnknown-derived interface with this device child and associate that interface with an application-defined guid.

ID3DDevice1

メソッド名 説明
CreateBlendState1 Creates a blend-state object that encapsulates blend state for the output-merger stage and allows the configuration of logic operations.
CreateDeferredContext1 Creates a deferred context, which can record command lists.
CreateDeviceContextState Creates a context state object that holds all Microsoft Direct3D state and some Direct3D behavior.
CreateRasterizerState1 Creates a rasterizer state object that informs the rasterizer stage how to behave and forces the sample count while UAV rendering or rasterizing.
GetImmediateContext1 Gets an immediate context, which can play back command lists.
OpenSharedResource1 Gives a device access to a shared resource that is referenced by a handle and that was created on a different device. You must have previously created the resource as shared and specified that it uses NT handles (that is, you set the D3D11_RESOURCE_MISC_SHARED_NTHANDLE flag).
OpenSharedResourceByName Gives a device access to a shared resource that is referenced by name and that was created on a different device. You must have previously created the resource as shared and specified that it uses NT handles (that is, you set the D3D11_RESOURCE_MISC_SHARED_NTHANDLE flag).

ID3DDevice2

メソッド名 説明
CheckMultisampleQualityLevels1 Get the number of quality levels available during multisampling.
CreateDeferredContext2 Creates a deferred context, which can record command lists.
GetImmediateContext2 Gets an immediate context, which can play back command lists.
GetResourceTiling Gets info about how a tiled resource is broken into tiles.

ID3DDevice3

メソッド名 説明
CreateDeferredContext3 Creates a deferred context, which can record command lists.
CreateQuery1 Creates a query object for querying information from the graphics processing unit (GPU).
CreateRasterizerState2 Creates a rasterizer state object that informs the rasterizer stage how to behave and forces the sample count while UAV rendering or rasterizing.
CreateRenderTargetView1 Creates a render-target view for accessing resource data.
CreateShaderResourceView1 Creates a shader-resource view for accessing data in a resource.
CreateTexture2D1 Creates a 2D texture.
CreateTexture3D1 Creates a 3D texture.
CreateUnorderedAccessView1 Creates a view for accessing an unordered access resource.
GetImmediateContext3 Gets an immediate context, which can play back command lists.
ReadFromSubresource Copies data from a D3D11_USAGE_DEFAULT texture which was mapped using ID3D11DeviceContext3::Map while providing a NULL D3D11_MAPPED_SUBRESOURCE parameter.
WriteToSubresource Copies data into a D3D11_USAGE_DEFAULT texture which was mapped using ID3D11DeviceContext3::Map while providing a NULL D3D11_MAPPED_SUBRESOURCE parameter.

2015年9月3日木曜日

「ゲームを動かす数学・物理」の感想

以前紹介した「ゲームを動かす技術と発想」を書かれた堂前さんが,
「ゲームを動かす数学・物理」という本を出版されました.

内容としては,ゲーム開発で用いる,ということを前提とした数学や物理に関する解説で,
例がゲーム開発で実際に遭遇するような内容になっているため,ゲーム開発をするのであれば,
参考になると思います.

抽象的な説明ではなく,具体的な例を通しての説明が多く,図も多くて分かりやすい内容になっています.
あくまでも基礎的な内容なので,その辺りは理解している,という人には物足りない内容になっているかもしれません.
しかし,そのことを他の人に説明したりする際には使える内容だと思うので,理解している,という人も買って損はないと思います.

また,いくつもあるコラムも,実際のトラブルだったりゲーム開発に関係する内容だったりがあり,読んでいて面白いです.

最近は,大学からゲーム開発会社に就職する人も増えていますが,大学でゲーム開発に関係することをあまり学んでいなかった,
という人であれば,この本は足掛かりとして役立つと思います.

新人教育を担当することになった人には,新人に教える際のネタとして参考になると思います.

数学が苦手だと思っているゲーム開発者も読んでみると良いかもしれません.

以下は,各章を読んだ上での目次よりは詳しめ位の内容と感想です.

第1章 整数

メモリがバイト,そしてビットから構成されているという話から始まり,2進数,16進数,2の補数,とコンピュータが整数値を扱う上での基礎知識が解説されています.

数学ガールという本に,「例示は理解の試金石」,という言葉が良く登場します.例を通すことで,理解が深まります.
この章では,コンピュータが扱う整数値がビット単位でどうなっているのか,
図や表を使っての具体的な例がいくつもあり,抽象的な説明をされるよりも分かりやすいと思います.

また,第1章11節には,符号付き整数と符合無し整数の変数に,正の整数値と負の整数値を代入した場合どうなるか,ということが詳しく説明しています.
この例は,コンピュータが扱うのはあくまでもビットであり,その結果が正の整数値なのか負の整数値なのかは解釈次第だ,ということを理解するきっかけになるでしょう.

第2章 小数

コンピュータで小数を表すための仕組みとして,固定小数と浮動小数の仕組みが紹介されています.

固定小数,浮動小数どちらについても,具体的な値とビット列の図を用いながら,どういう仕組みで小数を表現しているのか,四則演算はどうなるのか,などの解説があります.
また,第2章6節では浮動小数での桁落ちと情報落ちという2種類の誤差についての説明も,ビット列による説明が分かりやすいです.
最後の第2章7節にある整数から浮動小数への変換時にデータが変わってしまう場合がある,という例は是非知っておくべきでしょう.

第3章 演算

この章では,基本的な四則演算,論理演算,ビットシフトについて解説しています.
論理演算やビットシフトについては,ゲームではお馴染みのフラグ管理での例があり,単純にどういう演算なのかを説明されるだけよりも頭に残る内容になっていると思います.

第4章 2次元

この章では,2次元座標と2次元ベクトルについて解説しています.

ここで重要なのが,「座標」と「ベクトル」をちゃんと区別している,ということです.
座標もベクトルも同じものとしてしまっている解説などもありますが,この本ではちゃんと区別しています.

このことを理解していないために数式を間違っていた,ということがあった気がするんですが,具体的な内容が思い出せないのが悔しいところです.

第5章 角度


この章では,角度から始まり,三角関数(角度から辺の比を返す関数),プログラムで三角関数を使う場合に気を付けるべき弧度法,三角関数の逆関数(辺の比から角度を返す関数),
ベクトルの内積について解説しています.

コラムになっている角度の正規化という話は,3Dを扱うならどこかでぶつかる可能性がある問題なので,是非目を通したい内容になっています.

また,三角関数の逆関数の使い道について,その関数が返す値の範囲にも言及し,非常に細かくどういうことに使えるのか,説明しています.
こちらも知っていて損は無い内容です.

最後のベクトルの内積についても,ゲーム開発で実際にどういう場合に使われるのか,どういう注意点があるのか,と具体的な話があります.
単なる内積の説明をされるよりもずっと興味を持てる気がします.

さらっと書いていて読み飛ばしそうですが,Visual StudioでM_PI(円周率を表すマクロ)を利用するには,_USE_MATH_DEFINESを定義しておく必要があることもしっかりと書いています.
意外とこのマクロが使えなくてビルドが通らない,というトラップにひっかかる人はいる気がします.

第6章 時間

この章は,ゲームにおける時間,フレームの概念の解説に始まり,処理時間が掛かりすぎた場合,つまり処理落ちに対してどう対処するのか,
ということで,いくつかの対策方法について細かく解説し,そのメリットデメリットが述べられています.

コラムには,サウンドの処理落ちについて語られています.実際,目には見えないけれど,サウンドのズレというのは意外と気づくものです.
音が鳴ることが予想できるモーションに合わせて音を鳴らしていると,処理落ちしたときにズレに気づいたりします.
何とか対策できないか,と言われることもありますが,そういう時はたいてい根本的に処理を軽くするしかなかったりします.

処理落ち対策として紹介されているもののなかで,自分は前フレームとの時間の差分を利用した方法をよく利用していますが,
差分を考慮済みの値に更に差分を考慮した計算をする,など注意しないと結局おかしなことになったりします.

そういえば,ネットワークを利用するゲームだと,光は遅い,なんて話もありますね.光は1秒間に地球を七周半するので,
地球の裏側にデータを送信しようとすると,60FPSなら8フレームほど,30FPSなら4フレームほどの時間がかかってしまいます.
光は物理的に一番速いので,本当に世界中で通信をしようとすると大変だというか,リアルタイム性は実現不可能だということですね.

この章に書いてある内容は,今時の3Dのゲームを作る上では必須の知識ですね.

第7章 運動


この章では,速度,加速度,等加速度運動やゲーム内でのメートルや秒などの単位についての解説があり,
摩擦,重力や跳ね返りなどにも言及しています.

特に,ジャンプに関しては,レベルデザインなども考慮した場合に,加速度や初速などをどう扱うか,
細かく解説してあるので,そういった動きを扱うのであれば目を通しておきたい内容になっています.

第8章 3次元


この章では,3次元ベクトルとその演算,平面,外積について解説しています.
特に,カメラが映す範囲(視錐台)に入っているかの計算をする例を通して,立体を構成する平面,その平面からの距離,平面の表側裏側を判定するための法線,その法線を求めるための方法としての外積,それぞれの計算方法について詳しく説明しています.

第9章 マトリクス


この章では,行列とその演算,ベクトルや座標との関係が解説されています.

行列関係はややこしいこともあってか,基本的な演算と,3Dで良く使う平行移動,回転,拡縮を表す行列や,逆行列の説明以外は使い方を説明してはいるけれど,詳細には踏み込んでいません.

ただ,最近はゲームエンジンなどでそういった演算については用意してあり,自前で行列の計算を実装する必要はあまりないので,何に使うかさえ知っていれば大抵は良いのかな,という気もします.

第10章 衝突


この章では,衝突判定に必要な処理と,高速化のための工夫について解説しています.

このあたりは数式と例だけよりも実装も見た方が良い,ということなのか,結構実装による説明が充実しています.

第11章 乱数

最後は,乱数について解説しています.ここでは,乱数の生成方法よりも,乱数の扱い方が中心になっています.

ゲームで乱数を使う場合,その再現性が問題になることがあります.本ではレースゲームのリプレイでAIが乱数で
動いていたら,という例で説明しています.

実際,新人がゲームを作る際に乱数を使おうとしたりするんですが,デバッグのし辛さなんかを考慮していなかったりするので,
どういう時に乱数が使えて,どういう場合には使わない方が良いか,使う場合には何を注意したら良いのか,というのは
しっかりと知っておくと良いと思います.