Version: Unity 6.0 (6000.0)
言語 : 日本語
シェーダーで深度バッファへの書き込みを無効にする
シェーダーのブレンドモードの設定

シェーダーでのステンシルバッファの確認または書き込み

ステンシルバッファには、フレームバッファ内の各ピクセルの 8 ビットの整数値が格納されています。指定したピクセルに対してフラグメントシェーダーを実行する前に、GPU はステンシルバッファの現在の値を特定のリファレンス値と比較することができます。これをステンシルテストと呼びます。ステンシルテストに合格すると、GPU は深度テストを実行します。ステンシルテストが失敗した場合、GPU はそのピクセルの残りの処理をスキップします。つまり、ステンシルバッファをマスクとして使い、どのピクセルを描画し、どのピクセルを破棄するかを GPU に伝えることができます。

ステンシルバッファは、ポータルやミラーなどの特殊効果に使用するのが一般的です。さらに、ステンシルバッファは、ハードシャドウや 空間領域構成法 (CSG) をレンダリングする際に使用されることもあります。

Stencil コマンドを使用して 2 つの異なる設定ができます。ステンシルテストの設定と GPU がステンシルバッファに書き込む内容の設定です。2 つの設定は同じコマンドで行うことができますが、最も一般的な使用例は、1 つのシェーダーオブジェクトを作成して画面の領域をマスクし、他のシェーダーオブジェクトが描画できないようにすることです。そのためには、最初のシェーダーオブジェクトが常にステンシルテストに合格してステンシルバッファに書き込むように設定し、他はステンシルテストを実行してステンシルバッファに書き込まないように設定する必要があります。

RefReadMaskComp パラメーターを使用して、ステンシルテストを設定します。RefWriteMaskPassFailZFail パラメーターを使用して、ステンシルの書き込み操作を設定します。

このコマンドは、レンダー状態の変更を行います。Pass ブロックで使用すると、そのパスのレンダー状態を設定することができます。また、SubShader ブロックで使用すると、そのサブシェーダー内のすべてのパスのレンダー状態を設定することができます。

ステンシルテストの式は以下の通りです。

(ref & readMask) comparisonFunction (stencilBufferValue & readMask)

Shader "Examples/CommandExample"
{
    SubShader
    {
         // The rest of the code that defines the SubShader goes here.

        Pass
        {    
             // All pixels in this Pass will pass the stencil test and write a value of 2 to the stencil buffer
             // You would typically do this if you wanted to prevent subsequent shaders from drawing to this area of the render target or restrict them to render to this area only
             Stencil
             {
                 Ref 2
                 Comp Always
                 Pass Replace
             }            

             // The rest of the code that defines the Pass goes here.
        }
    }
}

このサンプルコードでは、SubShader ブロックでこのコマンドを使用するための構文を示しています。

Shader "Examples/CommandExample"
{
    SubShader
    {
             // All pixels in this SubShader pass the stencil test only if the current value of the stencil buffer is less than 2
             // You would typically do this if you wanted to only draw to areas of the render target that were not "masked out"
             Stencil
             {
                 Ref 2
                 Comp Less
             }  

         // The rest of the code that defines the SubShader goes here.        

        Pass
        {    
              // The rest of the code that defines the Pass goes here.
        }
    }
}

追加リソース

シェーダーで深度バッファへの書き込みを無効にする
シェーダーのブレンドモードの設定