ゲームフレームワーク的なものを作る。(4)〜文字列描画〜

今回はID3DXFontを使った文字列描画を行います。
前回「ゲームフレームワーク的なものを作る。(3)〜Graphicsクラス〜 - while( c++ );」のGraphicsクラスに、

  • ID3DXFontの生成関数
  • 文字列描画関数
  • std::shared_ptr< ID3DXFont >

を追加します。

/**
 *  Graphicsクラス
 */
class Graphics
{
private:
    /**
     *  単純なフォントを生成
     */
    ID3DXFont* CreateSimpleFont( int size, const std::string& font_name );

public:
    /**
     *  文字列の描画
     */
    void DrawString( int x, int y, const std::string& str, D3DCOLOR color );

private:
    std::shared_ptr< ID3DXFont > font;              ///<    文字列描画担当
};
関数の実装
/**
 *  コンストラクタ
 *
 *  @param  window  既存ウィンドウのweak_ptr
 */
Graphics::Graphics( const WindowWeakPtr& window )
    : window( window )
    , direct3d( CreateDirect3D(), com_deleter() )
    , device( CreateDirect3DDevice(), com_deleter() )
    , font( CreateSimpleFont( 16, "MS ゴシック" ), com_deleter() )
{
}

/**
 *  単純なフォントを生成
 *
 *  @param  size        フォントサイズ(高さ)
 *  @param  font_name   フォント名
 */
ID3DXFont* Graphics::CreateSimpleFont( int size, const std::string& font_name )
{
    ID3DXFont* font = nullptr;
    HRESULT hr = D3DXCreateFont( device.get(),
        size, 0, 0, 0, FALSE,
        SHIFTJIS_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, 
        font_name.c_str(),
        &font
        );
    if( FAILED( hr ) )throw std::runtime_error( "D3DXCreateFont" );
    return font;
}

/**
 *  文字列の描画
 */
void Graphics::DrawString( int x, int y, const std::string& str, D3DCOLOR color )
{
    if( WindowPtr w = window.lock() )
    {
        SIZE size = w->GetClientSize();
        RECT rect = { x, y, size.cx, size.cy };
        font->DrawText( nullptr, str.c_str(), -1, &rect, 0, color );
    }
}
使い方

std::stringstreamで描画する文字列を作成し、描画関数に渡します。

/**
 *  ゲーム1フレームの処理を行う
 */
void Game::Run()
{
    //シーンの実行
    ;

    //バックバッファをクリアし、シーンのレンダリングを開始する
    //レンダリング終了後、画面を更新する
    graphics.Clear();
    if( graphics.BeginScene() )
    {
        //シーンの描画
        ;

        //デバッグ情報
        std::stringstream ss;
        ss  << "hoge" << std::endl
            << "ほげほげ" << std::endl
            ;
        graphics.DrawString( 0, 0, ss.str(), D3DCOLOR_XRGB( 0xff, 0xcc, 0x99 ) );

        graphics.EndScene();
    }
    graphics.Update();
}

サンプル

次回は、windowsのPOINT構造体、SIZE構造体、RECT構造体をクラス化したPointクラス、Sizeクラス、Rectクラス、0.0〜1.0の実数で色成分を扱うためのColorクラスを作る予定です。