忍者ブログ

Memeplexes

プログラミング、3DCGとその他いろいろについて

XNA爆発チュートリアル その8.5 爆発オブジェクトの導入

XNA爆発チュートリアル その8のつづきです。

前回では3Dの爆発をフェードアウトさせたものの、
時間がたつとまた爆炎が描画されるようになってしまいます。
これではいつまでたっても爆発が画面から消えません。

この問題を解決するために、C#のコードのほうを
少々いじります。
爆発を表すクラス(まあ正確には構造体ですが)を作り、それに寿命を管理させるのです。
寿命が尽きたら新しい、別のインスタンスを使えばいいわけです。
そうすれば寿命が尽きた爆発は決して描画されません。

この構造体を利用すれば、ついでにHLSL側の全体の寿命を表す
マジックナンバー”2”も消してしまえるでしょう。
一石二鳥というわけです。

さらにせっかくですからHLSL側とC#側の変数名のミスマッチも解消します。

ExplosionRenderer.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;


public class ExplosionRenderer : Microsoft.Xna.Framework.DrawableGameComponent
{
    private Effect effect;
    private VertexDeclaration vertexDeclaration;
    private VertexVelocity[] vertices;

    private ContentManager content;
    private static System.Random random = new System.Random();

    private Matrix view;
    private Matrix projection;

    private Explosion explosion;


    public ExplosionRenderer(Game game)
        : base(game)
    {
        content = new ContentManager(game.Services);
    }


    public override void Initialize()
    {
        vertices = new VertexVelocity[30];

        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i].Velocity = randomVector3()/10;
        }

        base.Initialize();
    }

    Vector3 randomVector3()
    {
        return new Vector3(
            (float)(random.NextDouble() * 2 - 1),
            (float)(random.NextDouble() * 2 - 1),
            (float)(random.NextDouble() * 2 - 1)
            );
    }

    protected override void LoadGraphicsContent(bool loadAllContent)
    {
        if (loadAllContent)
        {
            effect = content.Load<Effect>("Content/ExplosionShader");
            effect.Parameters["ExplosionTexture"].SetValue(
                content.Load<Texture2D>("Content/explosion")
                );

            vertexDeclaration = new VertexDeclaration(
                GraphicsDevice,
                VertexVelocity.VertexElements
                );
        }
    }


    protected override void UnloadGraphicsContent(bool unloadAllContent)
    {
        if (unloadAllContent) { content.Unload(); }
    }

    public override void Update(GameTime gameTime)
    {
        explosion.Update(gameTime);

        if (explosion.Life < 0)
        {
            explosion = new Explosion(2);
        }
    }

    public override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        GraphicsDevice.RenderState.PointSize = 50;
        GraphicsDevice.RenderState.PointSpriteEnable = true;

        GraphicsDevice.RenderState.AlphaBlendEnable = true;
        GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
        GraphicsDevice.RenderState.DestinationBlend = Blend.One;
        GraphicsDevice.RenderState.DepthBufferWriteEnable = false;

        GraphicsDevice.VertexDeclaration = vertexDeclaration;

        effect.Parameters["View"].SetValue(view);
        effect.Parameters["Projection"].SetValue(projection);

        drawExplosion(explosion);

        GraphicsDevice.RenderState.AlphaBlendEnable = false;
        GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
    }

    private void drawExplosion(Explosion explosion)
    {
        effect.Parameters["Age"].SetValue(explosion.Age);
        effect.Parameters["StartLife"].SetValue(explosion.StartLife);

        effect.Begin();

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Begin();

            GraphicsDevice.DrawUserPrimitives<VertexVelocity>(
                PrimitiveType.PointList,
                vertices,
                0,
                vertices.Length
                );

            pass.End();
        }

        effect.End();
    }

    public void SetCamera(Matrix view, Matrix projection)
    {
        this.view = view;
        this.projection = projection;
    }
}

爆発の寿命が尽きたら直ちにライフ2秒にして初期化するようにしました。
実行したら2秒ごとに爆発していく様子が見られるでしょう。

次は爆発を表す構造体です。
クラスではなくて構造体なのはこの方がたぶん
パフォーマンス上有利なのではないかという理由です。

構造体で作った変数はヒープではなくスタック上におかれるため、
ガベージコレクションが発動しないので、
パフォーマンスのボトルネックにはならないはずです。(たぶん)

ふつうパフォーマンスを考慮したコードは、
可読性が低下するため避けるべきなのですが、
classをstructにするくらいは問題ないでしょう。

Explosion.cs
using Microsoft.Xna.Framework;

struct Explosion
{
    private float life;
    private float startLife;

    public float Life { get { return life; } }
    public float StartLife { get { return startLife; } }
    public float Age { get { return startLife - life; } }

    public Explosion(float life)
    {
        this.life = life;
        this.startLife = life;
    }

    public void Update(GameTime gameTime)
    {
        life -= (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
}


お次はHLSLで書いたエフェクトファイルです。
前回のマジックナンバー”2”をグローバル変数StartLifeで置き換え、
C#側から設定するようにしました。
また、変数名をC#側と同じになるようにそろえました。(Time → Age)

ExplosionShader.fx
float4x4 View;
float4x4 Projection;

float Age;
float StartLife;

texture ExplosionTexture;

sampler explosionSampler = sampler_state
{
	Texture = <ExplosionTexture>;
};

struct ExplosionVertexShaderOutput
{
	float4 Position : POSITION;
	float4 Color : COLOR;
};

float4 ComputeColor(float normalizedAge)
{
	float4 color = 1;
	color.a *= normalizedAge * (1 - normalizedAge) * (1 - normalizedAge) * 6.7;
	return color;
}

ExplosionVertexShaderOutput ExplosionVertexShader(float4 velocity:COLOR)
{
	ExplosionVertexShaderOutput output;
	float4 worldPosition = float4(velocity.xyz * Age, 1);
	output.Position = mul(worldPosition, mul(View, Projection));
	output.Color = ComputeColor(Age / StartLife);
	return output;
}

float4 ExplosionPixelShader(
	float2 textureCoordinate:TEXCOORD,
	float4 color:COLOR
	):COLOR
{
	return tex2D(explosionSampler, textureCoordinate) * color;
}

technique ExplosionShaderTechnique
{
	pass P0
	{
		VertexShader = compile vs_2_0 ExplosionVertexShader();
		PixelShader = compile ps_2_0 ExplosionPixelShader();
	}
}



変更は以上です。
これでプログラムを実行すると2秒ごとに爆発が
「ぶわっ」っと広がっていくのがわかると思います。

フェードアウトした爆発は、もはや決して再び描画されることはありません。
さらに一歩前進しましたね。


拍手[0回]

PR