C#でツールを作る その15 -HLSLを使ってみる-

今ではシェーダも一般的になっているようなので、私もちょっと遊んでみようと思います。

とりあえず、最低限必要なものを。

Effectオブジェクトの作成と破棄

private Effect effect = null;
String err;     //コンパイルエラー時の情報を取得
effect = Effect.FromFile(
    device,
    エフェクトファイル名,
    null,
    ShaderFlags.None,
    null,
    out err
    );
if (effect != null)
{
    effect.Dispose();
    effect = null;
}

Techniqueの取得と設定

private EffectHandle tech = null;
tech = effect.GetTechnique( テクニック名 );
effect.Technique = tech;

Effect変数の取得と設定

private EffectHandle handle = null;
handle = effect.GetParameter( null, "WorldViewProjection" );   //WorldViewProjectionはエフェクトファイル内の変数
Matrix WorldViewProjection = ...;
effect.SetValue( handle, WorldViewProjection );
//effect.SetValue( "WorldViewProjection", WorldViewProjection );
  • EffectHandleは文字列を渡すことも可能

描画

  • エフェクトを開始するとパス数が返ってくるので、その回数分ループで描画
int n = effect.Begin( FX.None );
for( int pass = 0; pass < n; pass ++ )
{
    effect.BeginPass( pass );

    描画;
    
    effect.EndPass();
}
effect.End();

fxファイル

//-----------------------------------------------------------
//global
//-----------------------------------------------------------
float4x4 WorldViewProjection;  //ワールド*ビュー*プロジェクション行列


//-----------------------------------------------------------
//struct
//-----------------------------------------------------------
struct VertexInput
{
    float4 pos : POSITION;
};

struct VertexOutput
{
    float4 pos : POSITION;
    float4 color : COLOR0;
};

struct PixelOutput
{
    float4 color : COLOR0;
};


//-----------------------------------------------------------
//vertex shader
//-----------------------------------------------------------

VertexOutput TestVertexShader( VertexInput input )
{
    VertexOutput output;
	
    //座標変換
    output.pos = mul( input.pos, WorldViewProjection );
	
    //ライティング
    float4 diffuse = { 0.0f, 0.0f, 0.0f };
    output.color = diffuse;
	
    return output;
}



//-----------------------------------------------------------
//pixel shader
//-----------------------------------------------------------

PixelOutput TestPixelShader( VertexOutput input )
{
    Pixeloutput output;
    output.color = input.color;
    return output;
}


//-----------------------------------------------------------
//technique
//-----------------------------------------------------------
technique test
{
    pass P0
    {
        VertexShader = compile vs_2_0 TestVertexShader();
        PixelShader = compile ps_2_0 TestPixelShader();
    }
}