忍者ブログ

Memeplexes

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

[PR]

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。


XNA4.0 複数のメッシュを一度のDrawで描画(ハードウェア・インスタンシング)

以前のこの記事のプログラムを、XNA4.0用に書きかえてみました。
たくさんの同じモデルを表示するときに役に立つ、ハードウェアインスタンシングです。

HardwareInstancing.fx
struct VertexPositionColor
{
	float4 Position : POSITION0;
	float4 Color : COLOR;
};

VertexPositionColor MyVertexShader(
	VertexPositionColor input,
	float3 position : POSITION1
	)
{
	input.Position.xyz += position;
	return input;
}

float4 MyPixelShader(float4 color : COLOR) : COLOR0
{
	return color;
}

technique HardwareInstancing
{
	pass Pass1
	{
		VertexShader = compile vs_3_0 MyVertexShader();
		PixelShader = compile ps_3_0 MyPixelShader();
	}
}




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



class MyGame : Game
{
    VertexPositionColor[] vertices = new VertexPositionColor[]{
        new VertexPositionColor(new Vector3(-0.1f, 0.1f, 0), Color.Blue),
        new VertexPositionColor(new Vector3(0.1f, 0.1f, 0), Color.White),
        new VertexPositionColor(new Vector3(0.1f, -0.1f, 0), Color.Red)
    };

    Vector3[] instances = new Vector3[] {
        new Vector3(),
        new Vector3(0.1f, 0.1f, 0),
        new Vector3(0.2f, 0.2f, 0)
    };


    //Graphics Device Objects
    Effect effect;
    VertexBuffer triangleVertexBuffer;
    IndexBuffer indexBuffer;
    DynamicVertexBuffer instanceVertexBuffer;

    public MyGame()
    {
        new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void LoadContent()
    {
        effect = Content.Load<Effect>("HardwareInstancing");

        triangleVertexBuffer = new VertexBuffer(
            GraphicsDevice,
            VertexPositionColor.VertexDeclaration,
            vertices.Length,
            BufferUsage.WriteOnly
            );
        triangleVertexBuffer.SetData<VertexPositionColor>(vertices);


        var index = new int[] { 0, 1, 2 };
        indexBuffer = new IndexBuffer(
            GraphicsDevice,
            IndexElementSize.ThirtyTwoBits,
            index.Length, 
            BufferUsage.WriteOnly
            );
        indexBuffer.SetData<int>(index);


        instanceVertexBuffer = new DynamicVertexBuffer(
            GraphicsDevice, 
            new VertexDeclaration(
                new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 1)
            ),
            instances.Length,
            BufferUsage.WriteOnly);

        instanceVertexBuffer.SetData(instances);
    }

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

        GraphicsDevice.SetVertexBuffers(
            new VertexBufferBinding(triangleVertexBuffer, 0, 0),
            new VertexBufferBinding(instanceVertexBuffer, 0, 1)
            );
        GraphicsDevice.Indices = indexBuffer;

        instanceVertexBuffer.SetData(instances, 0, instances.Length, SetDataOptions.Discard);

        foreach (var pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            GraphicsDevice.DrawInstancedPrimitives(
                PrimitiveType.TriangleList,
                0,
                0,
                vertices.Length, 
                0,
                vertices.Length / 3,
                instances.Length
                );
        }
    }
}

xna4.0HardwareInstancing.jpg

拍手[1回]

PR

XNAアプリケーションが0x4000001fを出して終了する問題(The program '~~: Managed (v4.0.30319)' has exited with code 1073741855 (0x4000001f).)

XNAアプリケーションをVisual Studio 2012で作っていた所、不可解な問題に直面しました。
いきなりアプリケーションが終了するのです。
しかも例外が発生していないようです。
F5を押して動かしているのに例外の場所に飛ばないのです。

出力をみてみると、

The program '[12012] ~~.vshost.exe: Managed (v4.0.30319)' has exited with code 1073741855 (0x4000001f).

とあります。

わけがわかりません。
検索してみたところWin32 x86エミュレーションサブシステムで使われる何かの例外のステータスコードのようですが…

結局2010で同じコードを書いたら動きました。
何だったのでしょう…??

拍手[1回]


XNAで物理シミュレーション(JigLibX) その3

「その1」ではJigLibXのシステムを初期化しました。
「その2」では箱を描画しました。
今回、「その3」では、箱を動かします。

箱を動かすのはちょっとやっかいです。
あらたなクラスBoxActorを作ります。


プログラム

BasicWorldGame.cs
using Microsoft.Xna.Framework;
using JigLibX.Physics;
using JigLibX.Collision;

public class BasicWorldGame : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;

    PhysicsSystem world;
    BoxActor fallingBox;
    BoxActor immovableBox;

    BoxRenderer boxRenderer;

    public BasicWorldGame()
    {
        graphics = new GraphicsDeviceManager(this);
        InitializePhysics();
    }

    private void InitializePhysics()
    {
        world = new PhysicsSystem { };
        world.CollisionSystem = new CollisionSystemSAP();

        fallingBox = new BoxActor(new Vector3(0, 20, 0), new Vector3(1, 1, 1));
        immovableBox = new BoxActor(new Vector3(0, -5, 0), new Vector3(5, 5, 5));
        immovableBox.Body.Immovable = true;

        world.AddBody(fallingBox.Body);
        world.AddBody(immovableBox.Body);
    }


    protected override void LoadContent()
    {
        boxRenderer = new BoxRenderer(GraphicsDevice);
    }

    protected override void UnloadContent()
    {
        boxRenderer.Dispose();
    }

    protected override void Update(GameTime gameTime)
    {
        world.Integrate(1f / 60);
        base.Update(gameTime);
    }

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

        boxRenderer.SetCamera(
            Matrix.CreateLookAt(
                new Vector3(5, 5, 40),
                new Vector3(),
                Vector3.Up
                ),
            Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45),
                GraphicsDevice.Viewport.AspectRatio,
                0.1f,
                1000f
                )
            );
        drawBox(fallingBox);
        drawBox(immovableBox);

        base.Draw(gameTime);
    }

    private void drawBox(BoxActor box)
    {
        boxRenderer.Draw(box.GetWorldTransform());
    }
}
BoxActor.cs
using Microsoft.Xna.Framework;
using JigLibX.Physics;
using JigLibX.Collision;
using JigLibX.Geometry;
using JigLibX.Math;

public class BoxActor 
{
    private Vector3 scale;

    public Body Body { get; private set; }
    private CollisionSkin skin;

    public BoxActor(Vector3 position, Vector3 scale)
    {
        this.scale = scale;

        this.Body = new Body();
        this.skin = new CollisionSkin(this.Body);

        this.Body.CollisionSkin = this.skin;

        this.skin.AddPrimitive(
            new Box(Vector3.Zero, Matrix.Identity, scale),
            new MaterialProperties(
                0.8f, // elasticity
                0.8f, // static roughness
                0.7f  // dynamic roughness
            ));

        SetMass(1.0f);
        this.Body.MoveTo(position, Matrix.Identity);
    }

    private void SetMass(float mass)
    {
        PrimitiveProperties primitiveProperties = new PrimitiveProperties(
            PrimitiveProperties.MassDistributionEnum.Solid,
            PrimitiveProperties.MassTypeEnum.Mass,
            mass
            );

        float junk;
        Vector3 centerOfMass;
        Matrix inertiaTensor, inertiaTensorCenterOfMass;

        this.skin.GetMassProperties(
            primitiveProperties,
            out junk, 
            out centerOfMass,
            out inertiaTensor,
            out inertiaTensorCenterOfMass
            );

        this.Body.BodyInertia = inertiaTensorCenterOfMass;
        this.Body.Mass = mass;
        this.skin.ApplyLocalTransform(new Transform(-centerOfMass, Matrix.Identity));
    }

    public Matrix GetWorldTransform()
    {
        return Matrix.CreateScale(scale)
            * skin.GetPrimitiveLocal(0).Transform.Orientation
            * Body.Orientation
            * Matrix.CreateTranslation(Body.Position);
    }
}


JigLibXDemo03.jpg


このシミュレーションには大きな箱と小さな箱が登場します。
大きな箱は空中に固定されていて、どんなことをしても動きません。

一方小さな箱は自由に動きます。
重力の影響を受けて下へ落下します。
落下していき最後は大きな箱に衝突しバウンスするのです。








拍手[0回]


XNAで物理シミュレーション(JigLibX) その2

今回は箱を描画するだけです。
よくわかっている人は飛ばしてください。

Xna部分の変更だけでJigLibX部分には変更ありません。

プログラム

BasicWorldGame.cs
using Microsoft.Xna.Framework;
using JigLibX.Physics;
using JigLibX.Collision;

public class BasicWorldGame : Game
{
    GraphicsDeviceManager graphics;
    PhysicsSystem world;
    BoxRenderer boxRenderer;

    public BasicWorldGame()
    {
        graphics = new GraphicsDeviceManager(this);
        InitializePhysics();
    }

    private void InitializePhysics()
    {
        world = new PhysicsSystem();
        world.CollisionSystem = new CollisionSystemSAP();
    }

    protected override void LoadContent()
    {
        boxRenderer = new BoxRenderer(GraphicsDevice);
    }

    protected override void UnloadContent()
    {
        boxRenderer.Dispose();
    }

    protected override void Update(GameTime gameTime)
    {
        world.Integrate(1 / 60f);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
        boxRenderer.SetCamera(
            Matrix.CreateLookAt(
                new Vector3(2, 1, 5),
                new Vector3(),
                Vector3.Up
                ),
            Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45),
                GraphicsDevice.Viewport.AspectRatio,
                0.1f, 1000
                )
            );
        boxRenderer.Draw(Matrix.Identity);
        base.Draw(gameTime);
    }
}

BoxRenderer.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

class BoxRenderer:System.IDisposable
{
    public GraphicsDevice GraphicsDevice { get; private set; }
    VertexBuffer vertexBuffer;
    BasicEffect basicEffect;

    public BoxRenderer(GraphicsDevice graphicsDevice)
    {
        GraphicsDevice = graphicsDevice;
        basicEffect = new BasicEffect(GraphicsDevice) { VertexColorEnabled = true};

        Vector3[] positions = new []
        {
            new Vector3(1, 1, 1),
            new Vector3(1, -1, 1),
            new Vector3(-1, -1,1),
            new Vector3(-1, 1, 1),

            new Vector3(1, 1, -1),
            new Vector3(1, -1, -1),
            new Vector3(-1, -1,-1),
            new Vector3(-1, 1, -1),
        };
        VertexPositionColor[] vertices = new[]
        {
            new VertexPositionColor(positions[0], Color.Blue),
            new VertexPositionColor(positions[1], Color.Blue),
            new VertexPositionColor(positions[2], Color.Blue),

            new VertexPositionColor(positions[3], Color.Blue),
            new VertexPositionColor(positions[0], Color.Blue),
            new VertexPositionColor(positions[2], Color.Blue),

            
            new VertexPositionColor(positions[3], Color.Red),
            new VertexPositionColor(positions[2], Color.Red),
            new VertexPositionColor(positions[7], Color.Red),

            new VertexPositionColor(positions[7], Color.Red),
            new VertexPositionColor(positions[2], Color.Red),
            new VertexPositionColor(positions[6], Color.Red),
            

            new VertexPositionColor(positions[0], Color.Green),
            new VertexPositionColor(positions[3], Color.Green),
            new VertexPositionColor(positions[7], Color.Green),

            new VertexPositionColor(positions[0], Color.Green),
            new VertexPositionColor(positions[7], Color.Green),
            new VertexPositionColor(positions[4], Color.Green),


            new VertexPositionColor(positions[4], Color.Cyan),
            new VertexPositionColor(positions[6], Color.Cyan),
            new VertexPositionColor(positions[5], Color.Cyan),

            new VertexPositionColor(positions[4], Color.Cyan),
            new VertexPositionColor(positions[7], Color.Cyan),
            new VertexPositionColor(positions[6], Color.Cyan),


            new VertexPositionColor(positions[5], Color.Magenta),
            new VertexPositionColor(positions[2], Color.Magenta),
            new VertexPositionColor(positions[1], Color.Magenta),

            new VertexPositionColor(positions[5], Color.Magenta),
            new VertexPositionColor(positions[6], Color.Magenta),
            new VertexPositionColor(positions[2], Color.Magenta),


            new VertexPositionColor(positions[0], Color.Yellow),
            new VertexPositionColor(positions[5], Color.Yellow),
            new VertexPositionColor(positions[1], Color.Yellow),

            new VertexPositionColor(positions[0], Color.Yellow),
            new VertexPositionColor(positions[4], Color.Yellow),
            new VertexPositionColor(positions[5], Color.Yellow),
        };

        vertexBuffer = new VertexBuffer(
            graphicsDevice,
            typeof(VertexPositionColor),
            vertices.Length,
            BufferUsage.WriteOnly
            );
        vertexBuffer.SetData<VertexPositionColor>(vertices);
    }

    public void SetCamera(Matrix view, Matrix projection)
    {
        basicEffect.View = view;
        basicEffect.Projection = projection;
    }

    public void Draw(Matrix world)
    {
        basicEffect.World = Matrix.CreateScale(1 / 2f) * world;
        basicEffect.CurrentTechnique.Passes[0].Apply();


        GraphicsDevice.SetVertexBuffer(vertexBuffer);
        GraphicsDevice.DrawPrimitives(
            PrimitiveType.TriangleList,
            0, 
            vertexBuffer.VertexCount / 3
            );
    }

    public void Dispose()
    {
        basicEffect.Dispose();
        vertexBuffer.Dispose();
    }
}


このプログラムは斜め上から見た箱を描きます。

JigLibXDemo02.jpg


まだシミュレーターと結びつけていないので、動きません。











拍手[0回]


XNAで物理シミュレーション(JigLibX) その1

物理シミュレーターJigLibX

このブログでは今までの所描画(それも基礎的な)ばかり扱っていました。
「見た目」ばかりで「動き」はほとんど無視です。

ここでは物理シミュレーションでよりリアルな動きを目指します。

物理シミュレーションといっても難しいことをする必要はありません。
ライブラリがいくつかあるからです。
私はODE(C/C++用ライブラリ)をC++/CLIでラップしてしばらく使っていました。
が、最近JigLibXというものを知りました。

JigLibX

これはC#で書かれています。
これの良いところは、ちょこっと修正すればSilverlightからも使えるところです。
オリジナルのソースにはunsafeとかがたくさんあってSilverlightから使えないようですが。
しかしunsafeを取り除いてSilverlightから使えるようにしたバージョンがあります

SilverlightのXNAはオリジナルのXNAよりややこしいので、簡単のため、ここではオリジナルのXNAを使うことにします。
でもこれから書くことはSilverlightのXNAに転用可能です。
安心して下さい。

まず次のページを参考にします。

Basic World

このページはJIgLibXで物理シミュレーションする方法を簡単に開設してくれています。
ここではそれをやや変更しながら紹介していきたいと思います。


物理システムと衝突システムの初期化とアップデート

まず一つ一つやっていきましょう。
次のようなコードを書きます。

using Microsoft.Xna.Framework;
using JigLibX.Physics;
using JigLibX.Collision;

public class BasicWorldGame : Game
{
    GraphicsDeviceManager graphics;
    PhysicsSystem world;

    public BasicWorldGame()
    {
        graphics = new GraphicsDeviceManager(this);
        InitializePhysics();
    }

    private void InitializePhysics()
    {
        world = new PhysicsSystem();
        world.CollisionSystem = new CollisionSystemSAP();
    }

    protected override void Update(GameTime gameTime)
    {
        world.Integrate(1 / 60f);

        base.Update(gameTime);
    }

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

        base.Draw(gameTime);
    }
}



このプログラムは初期化とアップデートするだけで何もしません。
(ですから実行画面は省きます)

コンストラクタ内で物理計算に必要なオブジェクトを初期化し、Updateメソッド内で物理計算をすすめるメソッドを呼んでいます。
(本来は初期化後に箱や球体を物理システムに追加して、箱がバウンスするさまを楽しめるのですが)


PhysicsSystemクラス

public class PhysicsSystem
{
    public PhysicsSystem();

    public CollisionSystem CollisionSystem { get; set; }
...
    public void Integrate(float dt);
...
}




PhysicsSystemクラスはシミュレーターで動かす物体を管理します。
今回は物体を追加しません。
今回はPhysicsSystem.CollisionSystemプロパティで衝突システムをセットしています。

衝突システムとはシミュレートする物体間の衝突を検知するシステムだと思われます。
(物体の動きをシミュレートするには、どの物体とどうぶつかったかを検出する必要があります)
次のような種類があります。

クラス名 解説
CollisionSystemBrute すべての物体を、全ての他の物体に対して衝突をチェックします。一見遅そうですが、小さなシーンではこれは速度が出て、CollisionSystemGridより速いでしょう。
CollisionSystemGrid 世界をあるサイズのグリッドに分割したCollisionSystemです。物体が均等に散らばっていると、チェックの回数が減ります(速度が出ます)。
CollisionSystemSAP sweep-and-pruneアルゴリズムを使ったCollisionSystemです。




PhysicsSystem.Integrate()メソッドはシミュレーションを行うメソッドです。
Integrateとは積分のことでしょう。
シミュレーションを動かす作業は積分だと考えることができます。
つまり力から速度を出し、速度から位置を出すわけですね。

Integrateの引数dtは、進める速度です。
XnaではUpdateは1秒間に60回呼ばれるので、dt = 1 / 60fでいいでしょう。










拍手[1回]