忍者ブログ

Memeplexes

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

[PR]

×

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


IronScheme その3 四則演算といろいろ

1 + 1 = ?

前回はHello Worldをしました。
今回は四則演算をしましょう。

ではまず最も簡単な足し算、1 + 1をやってみましょう!
(0 + 0のほうが簡単でしょうか?
いやでもあまり面白い結果にはなりませんもんね)

(import (rnrs) (ironscheme clr))

(clr-static-call System.Console WriteLine (+ 1 1))
(clr-static-call System.Console ReadLine)

結果は
2
です。

(+ 1 1)に着目してください。
IronSchemeでは1 + 1という書き方はダメです。
関数というかなにか命令のようなものは常に先頭に来なければなりません。
めんどくさいと思う方もいらっしゃるでしょうが、統一されてて美しいという見方もできます。

以下、引き算、掛け算、わり算も似た様な調子です。


引き算、掛け算、わり算

めんどくさいので、一気にやります。
(import (rnrs) (ironscheme clr))

(clr-static-call System.Console WriteLine "(- 6 2) = {0}" (- 6 2))
(clr-static-call System.Console WriteLine "(* 6 2) = {0}" (* 6 2))
(clr-static-call System.Console WriteLine "(/ 6 2) = {0}" (/ 6 2))
(clr-static-call System.Console ReadLine)

この結果は、
(- 6 2) = 4
(* 6 2) = 12
(/ 6 2) = 3

です。


分数、商、余り

上では述べませんでしたが、/を使うと分数になります。

(import (rnrs) (ironscheme clr))

(clr-static-call System.Console WriteLine "(/ 7 2) = {0}" (/ 7 2))
(clr-static-call System.Console ReadLine)
この結果は
(/ 7 2) = 7/2

です。3.5や3ではないことに注意してください。

では3が欲しい時にはどうすればいいのでしょうか?
あるいは余りがほしい時には?

3を得るためには、quotientを使います。
余りはmoduloremainderを使います。
が、それぞれ働きが微妙に違います。
C#の%に相当するのはmoduloのようです。
remainderの結果の符号は割られる数の符号と同じになります。
これら3つのプロシージャをを使うためには(rnrs r5rs (6))をインポートする必要があります。

(import (rnrs r5rs (6)) (ironscheme clr))

(clr-static-call System.Console WriteLine "(quotient 7 2) = {0}" (quotient 7 2))
(clr-static-call System.Console WriteLine "(modulo 7 2) = {0}" (modulo 7 2))
(clr-static-call System.Console WriteLine "(modulo 7 -2) = {0}" (modulo 7 -2))
(clr-static-call System.Console WriteLine "(modulo -7 2) = {0}" (modulo -7 2))
(clr-static-call System.Console WriteLine "(modulo -7 -2) = {0}" (modulo -7 -2))
(clr-static-call System.Console WriteLine "(remainder 7 2) = {0}" (remainder 7 2))
(clr-static-call System.Console WriteLine "(remainder 7 -2) = {0}" (remainder 7 -2))
(clr-static-call System.Console WriteLine "(remainder -7 2) = {0}" (remainder -7 2))
(clr-static-call System.Console WriteLine "(remainder -7 -2) = {0}" (remainder -7 -2))
(clr-static-call System.Console ReadLine)

結果はこうなります:

(quotient 7 2) = 3
(modulo 7 2) = 1
(modulo 7 -2) = -1
(modulo -7 2) = 1
(modulo -7 -2) = -1
(remainder 7 2) = 1
(remainder 7 -2) = 1
(remainder -7 2) = -1
(remainder -7 -2) = -1













拍手[0回]

PR

IronScheme その2 コンパイル

コンパイル

前回はIronSchemeをインストールしました。
今回はプログラムをコンパイルしてみましょう。

前回現れた2つのファイル、そのうちひとつがコンパイラとして使えます。

IronScheme.exe

です。
これはそのまま実行しても使いにくいです。
ですからこれの本体である

"C:/Program Files\IronScheme/IronScheme.Console.exe"

を、ソースコードのあるディレクトリで実行しましょう。
つまりコマンドプロンプトを実行し、カレントディレクトリを、ソースコードのあるディレクトリまで移動し、そこからIronScheme.exeを呼ぶのです。
かんたんですね!

(簡単ではないと思った方へ。
まじめに説明します。すみません。

手順として一番お手軽なのは、次のような内容が書かれたrun.batファイルを、ソースコードのあるディレクトリ(実際の所、作業しやすそうだと思ったらどんなディレクトリでも構いません)に作ることです。

"C:\Program Files\IronScheme\IronScheme.Console.exe"

具体的には、好きなディレクトリを開いた状態で空白を右クリック-> [新規作成] -> [テキスト文書]。
名前はrun.batにしてください。
最後の拡張子.txtは消します(警告が来ますが、無視です)。
そしてアイコンを右クリックして[編集]。
メモ帳が開きますから、その中に"C:\Program Files\IronScheme\IronScheme.Console.exe"を貼り付けて(""も含め)、[ファイル]→[保存]します。
あとはこうしてできたrun.batのアイコンをダブルクリックすればインタープリターが起動します。


IronScheme.exeを実行すると、IronSchemeのインタープリターがスタートします。
これでコンパイルの準備は完了です。
(かわっていますが、インタープリターからコンパイルするようです。ややこしいですね)

IronScheme.Console.exe.jpg

あらたに"helloworld.scm"という名前のファイルを作ります。
これがIronSchemeのソースコードファイルです。

"helloworld.scm"
(import (ironscheme clr))

(clr-static-call System.Console WriteLine "Hello World!")

これを保存します。
そしてさきほどのインタープリターに次のように書くのです。
>(compile "helloworld.scm" #t)


エンターを押すと、無事ソースコードのあるディレクトリの中にhelloworld.exeが作られます。
と、もうひとつ、helloworld.exe.configも作られます。

helloworld.exeを実行してもすぐ終わってしまう?
ならhelloworld.scmを次のように書き換えましょう。
(import (ironscheme clr))

(clr-static-call System.Console WriteLine "Hello World!")
(clr-static-call System.Console ReadLine)

これでReadLineがプログラムを止めます。
実行結果をちゃんと見ることが出来ます。

C#で言うとこうなります:
class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Hello World!");
        System.Console.ReadLine();
    }
}



コードの意味

LispやSchemeは基本的に大量のカッコからなっています。
カッコでその中身を実行するのです。
カッコの中身は関数だったり特殊形式と呼ばれるものだったりします。
ともかく、何かを行うものがカッコの中にあるのです。

(関数名 引数1 引数2...)

ですから今回は、次のような関数?を使ったことになります:

import
clr-static-call

importは既存のライブラリを使うためのものです。
(ironschemeはIronSchemeのライブラリを表す何かでしょう。
インストールしたディレクトリを見ると、IronSchemeディレクトリの中にCLRファイルがあります。
上手く対応しているのですね。)

clr-static-callはCLRのstaticなメソッドを呼ぶマクロです。

おもしろいのはWriteLineが関数なのではなくclr-static-callが関数(というかマクロ)なのだということですね。
(WriteLine System.Console "Hello World!")ではありません。
(System.Console WriteLine "Hello World")でもありません。
面白いというか・・・めんどくさそうです。


Schemeっぽい書き方

上では.netのライブラリを使いましたが、もう少しオリジナルのSchemeっぽい書き方をすることも出来ます。

(import (rnrs))

(display "Hello World!")
(newline)

あるいはConsole.ReadLine()に相当するものを付け加えると:・
(import (rnrs))

(display "Hello World!")
(newline)
(get-line (current-input-port))


rnrsは"Revised N Report on the Algorithmic Language Scheme"の略です。
現在nは6で、R6RSです。
便利なライブラリが詰まっているようです。
display

(display obj)

で、objを表示します。
Console.Write(obj)に相当するようです。

newlineは新しい行を書きます。
Console.WriteLine()(引数なし)と同じですね。

get-line

(get-line textual-input-port)で、textual-input-portという入力ポートから、行を読み込みます。
textual-input-portを(current-input-port)にすれば標準出力から文字の行を読み込むのです。

(current-iput-port)はデフォルトの入力ポートを返します。
普通は標準出力です。
しかし後から動的にに変わることもあります。


拍手[1回]


IronScheme その1 インストール

IronScheme

かの有名なLispに再び手をだそうとしたのですが、よくわからなかったのでIronSchemeに手を出してみることにします。
IronSchemeは名前から分かる通り、Schemeという言語の.net版です。
そしてSchemeはLispの親戚です。
というわけで、これをマスターすればLispをマスターしたといっても過言ではないでしょう!(?)


インストール

IronPythonはここから手に入ります。

現時点ではリンク先のIronScheme-1.0-RC6-NET4-setup.exeがそれですね。

これを実行してたくさんのボタンをポチポチクリックしていくと、スタートメニューにIronSchemeフォルダができていることがわかります。
中にはIronSchemeとUinstallの2つのアイコンが。
めでたしめでたし。


拍手[0回]


Silverlight5からXnaを使う その5 2つのDrawingSurface

DrawingSurfaceはここまで、1つだけでした。
DrawingSurfaceはXNAで3DCGを表示するコントロールです。
一つの画面に一つの3DCGが表示されるのです。

ここではそうではなく、2つの画面に3DCGを表示する準備をしてみましょう。


ここには2つのDrawingSurfaceがあります。
それぞれ背景を赤と青に塗っています。
そしてちょっとした情報を表示しています。

どうやら2つのDrawingSurfaceが使うGraphicsDeviceは共通で、スレッドも同じようです。

なお、ここでやることはViewportでも同じようなことができますが、どうやら実装レベルでは異なっているようです。


プログラム

MainPage.xaml
<UserControl x:Class="SilverlightXna06.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="2*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock x:Name="textBlock" Grid.RowSpan="2"></TextBlock>
        <DrawingSurface Draw="DrawingSurface1_Draw"/>
        <DrawingSurface Draw="DrawingSurface2_Draw" Grid.Row="1" />
        <sdk:Label Foreground="White" Name="label1"/>
        <sdk:Label Foreground="White" Name="label2" Grid.Row="1"/>
    </Grid>
</UserControl>

MainPage.xaml.cs

using System.Windows.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Windows.Graphics;

namespace SilverlightXna06
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            textBlock.Text = GpuError.Message;
        }

        GraphicsDevice GraphicsDevice
        {
            get { return GraphicsDeviceManager.Current.GraphicsDevice; }
        }

        private void DrawingSurface1_Draw(object sender, DrawEventArgs e)
        {
            GraphicsDevice.Clear(new Color(1f, 0, 0));
            outputLog(label1);
            e.InvalidateSurface();
        }

        private void DrawingSurface2_Draw(object sender, DrawEventArgs e)
        {
            GraphicsDevice.Clear(new Color(0, 0, 1f));
            outputLog(label2);
            e.InvalidateSurface();
        }

        private void outputLog(Label label)
        {
            var gpu = GraphicsDevice;
            var threadID = System.Threading.Thread.CurrentThread.ManagedThreadId;
            var viewport = gpu.Viewport;
            Dispatcher.BeginInvoke(delegate
            {
                label.Content = string.Format(
                    "gpu:{0}, thread:{1}, viewport.Bounds:{2}",
                    gpu.GetHashCode(),
                    threadID,
                    viewport.Bounds
                    );
            });
        }
    }
}


GpuError.cs
using System.Windows.Graphics;

namespace SilverlightXna06
{
    public class GpuError
    {
        public static bool ErrorExists
        {
            get
            {
                return GraphicsDeviceManager.Current.RenderMode != RenderMode.Hardware;
            }
        }

        public static string Message
        {
            get
            {
                if (!ErrorExists)
                { return ""; }

                string message;

                switch (GraphicsDeviceManager.Current.RenderModeReason)
                {
                    case RenderModeReason.Not3DCapable:
                        message = "あなたのグラフィックスハードウェアはこのページを表示出来ません";
                        break;
                    case RenderModeReason.GPUAccelerationDisabled:
                        message = "ハードウェアグラフィックスアクセラレーションがこのwebページでは有効にされていません。\n\n" +
                            "webサイトのオーナーに通知してください";
                        break;
                    case RenderModeReason.TemporarilyUnavailable:
                        message = "あなたのグラフィックスハードウェアは一時的に使用不可能になっています。\n\n" +
                            "webページをリロードするかブラウザを再起動してください。";
                        break;
                    case RenderModeReason.SecurityBlocked:
                        message =
                          "webサイトが3Dグラフィックスを表示できるようにするには、システム構成を変える必要があります。\n\n" +
                          "  1. ここを右クリックします。\n" +
                          "  2. [Silverlight]を選択します\n" +
                          "     ([Microsoft Silverlight の構成ダイヤログ]が表示されます)\n" +
                          "  3. [アクセス許可]タブを選択します\n" +
                          "  4. このサイトをリストの中から見つけ、その3Dグラフィックスアクセス許可を[拒否]から[許可]に変えます\n" +
                          "  5. [OK]をクリックします\n" +
                          "  6. ページをリロードします";
                        break;
                    default:
                        message = "不明なエラー";
                        break;
                }

                return "3D表示がブロックされました!\n\n\n" + message;
            }
        }
    }
}










拍手[0回]


Silverlight5からXnaを使う その4 物理シミュレーション

前回の記事では普通のXnaで物理シミュレーションを行いました。
JigLibXというライブラリを使ったのです。

今回はSilverlightでやってみます。
やってみました。




「new box」というボタンを押してください。
空中に箱が突如として現れ落下していきます。
消す方法はありません(!!)。
あんまり出し過ぎたらパソコンが重くなる前にページをリロードしてください。


プログラム

今回のプログラムは主に5つのファイルからなります。

ファイル名 解説
BoxActor.cs 物理的に動く箱を表すクラス。
BoxRenderer.cs 箱を描画するクラス。
GpuError.cs Gpuに関連したエラー解説文の生成クラス。
MainPage.xaml メインページのXamlです。
MainPage.xaml.cs メインページのクラスです。ほとんどの操作はここで行います。

一部は前回とかぶりますが、念のため全部書いておきます。

BoxActor.cs
using Microsoft.Xna.Framework;
using JigLibX.Physics;
using JigLibX.Collision;
using JigLibX.Geometry;
using JigLibX.Math;


namespace SilverlightXna04
{
    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);
        }
    }
}

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

namespace SilverlightXna04
{
    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),
            };
            Color[] colors = new[]
            {
                new Color(0, 0, 1f),
                new Color(1f, 0, 0),
                new Color(0, 1f, 0),
                new Color(0, 1f, 1f),
                new Color(1f, 0, 1f),
                new Color(1f, 1f, 0),
            };

            VertexPositionColor[] vertices = new[]
            {
            new VertexPositionColor(positions[0], colors[0]),
            new VertexPositionColor(positions[1], colors[0]),
            new VertexPositionColor(positions[2], colors[0]),

            new VertexPositionColor(positions[3], colors[0]),
            new VertexPositionColor(positions[0], colors[0]),
            new VertexPositionColor(positions[2], colors[0]),

            
            new VertexPositionColor(positions[3], colors[1]),
            new VertexPositionColor(positions[2], colors[1]),
            new VertexPositionColor(positions[7], colors[1]),

            new VertexPositionColor(positions[7], colors[1]),
            new VertexPositionColor(positions[2], colors[1]),
            new VertexPositionColor(positions[6], colors[1]),
            

            new VertexPositionColor(positions[0], colors[2]),
            new VertexPositionColor(positions[3], colors[2]),
            new VertexPositionColor(positions[7], colors[2]),

            new VertexPositionColor(positions[0], colors[2]),
            new VertexPositionColor(positions[7], colors[2]),
            new VertexPositionColor(positions[4], colors[2]),


            new VertexPositionColor(positions[4], colors[3]),
            new VertexPositionColor(positions[6], colors[3]),
            new VertexPositionColor(positions[5], colors[3]),

            new VertexPositionColor(positions[4], colors[3]),
            new VertexPositionColor(positions[7], colors[3]),
            new VertexPositionColor(positions[6], colors[3]),


            new VertexPositionColor(positions[5], colors[4]),
            new VertexPositionColor(positions[2], colors[4]),
            new VertexPositionColor(positions[1], colors[4]),

            new VertexPositionColor(positions[5], colors[4]),
            new VertexPositionColor(positions[6], colors[4]),
            new VertexPositionColor(positions[2], colors[4]),


            new VertexPositionColor(positions[0], colors[5]),
            new VertexPositionColor(positions[5], colors[5]),
            new VertexPositionColor(positions[1], colors[5]),

            new VertexPositionColor(positions[0], colors[5]),
            new VertexPositionColor(positions[4], colors[5]),
            new VertexPositionColor(positions[5], colors[5]),
        };

            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();
        }
    }

}

GpuError.cs
using System.Windows.Graphics;

namespace SilverlightXna04
{
    public class GpuError
    {
        public static string Message
        {
            get
            {
                if (GraphicsDeviceManager.Current.RenderMode == RenderMode.Hardware)
                { return ""; }

                string message;

                switch (GraphicsDeviceManager.Current.RenderModeReason)
                {
                    case RenderModeReason.Not3DCapable:
                        message = "あなたのグラフィックスハードウェアはこのページを表示出来ません";
                        break;
                    case RenderModeReason.GPUAccelerationDisabled:
                        message = "ハードウェアグラフィックスアクセラレーションがこのwebページでは有効にされていません。\n\n" +
                            "webサイトのオーナーに通知してください";
                        break;
                    case RenderModeReason.TemporarilyUnavailable:
                        message = "あなたのグラフィックスハードウェアは一時的に使用不可能になっています。\n\n" +
                            "webページをリロードするかブラウザを再起動してください。";
                        break;
                    case RenderModeReason.SecurityBlocked:
                        message =
                          "webサイトが3Dグラフィックスを表示できるようにするには、システム構成を変える必要があります。\n\n" +
                          "  1. ここを右クリックします\n" +
                          "  2. 'Silverlight'を選択します\n" +
                          "     ('Microsoft Silverlight Configuration'ダイヤログが表示されます)\n" +
                          "  3. 'Permissions'タブを選択します\n" +
                          "  4. このサイトをリストの中から見つけ、その3Dグラフィックスパーミッションを'Deny'から'Allow'に変えます\n" +
                          "  5. 'OK'をクリックします\n" +
                          "  6. ページをリロードします";
                        break;
                    default:
                        message = "不明なエラー";
                        break;
                }

                return "3D表示がブロックされました!\n\n\n" + message;
            }
        }

    }
}

MainPage.xaml
<UserControl x:Class="SilverlightXna04.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="textBlock"></TextBlock>
        <DrawingSurface Draw="DrawingSurface_Draw"/>
        <Button Content="new Box" Width="80" Click="Button_Click" Margin="0,0,12,12" HorizontalAlignment="Right" Height="40" VerticalAlignment="Bottom" />
    </Grid>
</UserControl>

MainPage.xaml.cs
using System.Windows.Controls;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Xna = Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Windows.Graphics;
using JigLibX.Physics;
using JigLibX.Collision;

namespace SilverlightXna04
{
    public partial class MainPage : UserControl
    {
        private bool loaded = false;

        private BoxRenderer boxRenderer;

        private PhysicsSystem world;
        private List<BoxActor> mobileBoxes = new List<BoxActor>();
        private BoxActor immobileBox;

        public MainPage()
        {
            InitializeComponent();
            textBlock.Text = GpuError.Message;
            InitializePhysics();
        }

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

            immobileBox = new BoxActor(new Vector3(0, -5, 0), new Vector3(25, 5, 25));
            immobileBox.Body.Immovable = true;

            world.AddBody(immobileBox.Body);
        }

        private void DrawingSurface_Draw(object sender, DrawEventArgs e)
        {
            if (!loaded)
            {
                LoadContent();
                loaded = true;
            }

            Update();
            Draw();
            e.InvalidateSurface();
        }

        private GraphicsDevice GraphicsDevice
        {
            get
            {
                return GraphicsDeviceManager.Current.GraphicsDevice;
            }
        }

        private void LoadContent()
        {
            boxRenderer = new BoxRenderer(GraphicsDevice);
            boxRenderer.SetCamera(
                Matrix.CreateLookAt(
                    new Vector3(15, 15, 30),
                    new Vector3(),
                    Vector3.Up
                    ),
                Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45),
                    GraphicsDevice.Viewport.AspectRatio,
                    0.1f,
                    1000
                    )
                 );
        }

        private void Draw()
        {
            GraphicsDevice.Clear(new Xna.Color(0.39f, 0.58f, 0.93f));
            GraphicsDevice.RasterizerState = RasterizerState.CullNone;

            foreach (var box in mobileBoxes)
            {
                boxRenderer.Draw(box.GetWorldTransform());
            }
            boxRenderer.Draw(immobileBox.GetWorldTransform());

        }

        private void Update()
        {
            if (addingBox)
            {
                addBox();
                addingBox = false;
            }
            world.Integrate(1 / 60f);
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //こんな仕掛けが必要なのは
            //Update, Drawがスレッドで動いているため
            addingBox = true;
        }

        private bool addingBox;

        private void addBox()
        {
            var actor = new BoxActor(new Vector3(0, 10, 0), new Vector3(1));
            world.AddBody(actor.Body);
            mobileBoxes.Add(actor);
        }
    }
}




おまけ

プロジェクトファイルです。


拍手[0回]