2013/10/30

とりあえずJoystick

Kです。テスト用プログラムにJoystickを使いたいので、C#からDirect Inputを使用してボタンの判定を行うクラスを作ってみました。


動作との関連づけは、各デバイスクラスにonbuttonメソッドがあり、全てのコントローラからのデータはこいつが受け取ります。設定により登録されたデバイスに対して、登録されたボタンが押されたりするとそのボタンと任意の文字列を渡す仕組みです。アナログスティックについては、常に通知する仕組みです。

joystick.setButtons(new Byte[] { 1, 3, 2, 0 }, 4);
によってキー割り当てを変更しています。
これは、左が1, 上が2, 下が3, 右が4となっているコントローラにおいて、
上から時計回りに0, 1, 2, 3と割り当てるための記述です。
また、上記4つのボタン以外は受け付けません。


using System;
using System;
using IWshRuntimeLibrary;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectInput;
using System.Windows.Forms;

using System.Collections.Generic;

class Form1 : Form {

}

class Program {
   public static void Main() {
      Device device;
      Joystick joystick;
      Form1 form;

      form = new Form1();

      device = serachDevice(form.Handle);

      if(device != null) {
         Joystick.Command jc;

         System.Console.WriteLine("デバイス見付かった");
         joystick = new Joystick(device);

         joystick.setButtons(new Byte[] { 1, 3, 2, 0 }, 4);

         jc = new Joystick.Command(0, "△");
         jc.onbutton += onButton;
         joystick.setCommand(jc);

         jc = new Joystick.Command(1, "○");
         jc.onbutton += onButton;
         joystick.setCommand(jc);

         jc = new Joystick.Command(2, "×");
         jc.onbutton += onButton;
         joystick.setCommand(jc);

         jc = new Joystick.Command(3, "□");
         jc.onbutton += onButton;
         joystick.setCommand(jc);
      }
      Application.Run(form);
   }

   private static void onButton(int no, string message) {
      System.Console.WriteLine("ID={0} / mes={1}", no, message);
   }

   private static Device serachDevice(System.IntPtr hwnd) {
      DeviceList dl;
      Device joystick = null;

      dl = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);

      foreach(DeviceInstance dev in dl) {
         joystick = new Device(dev.InstanceGuid);
         joystick.SetCooperativeLevel(hwnd, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);

         // 最初に見つかったジョイスティックを操作対象とする
         break;
      }

      if(joystick != null) {
         joystick.Acquire();
      }

      return joystick;
   }
}

/*
 * ### ゲーミング用Joystickクラス ###
 * 特定のコマンドを検出したら、登録されたデリゲートに通知する。
 * setButtons(int[] )で、
 */
class Joystick {
   // pulibc
   public delegate void onButton(int no, string message);

   public Joystick(Device joystick) {
      this.joystick = joystick;

      // タイマーの作成・起動
      var mytimer = new System.Threading.Timer(new System.Threading.TimerCallback(onTimer),
         this, 0, 10);

      // ボタンルール・ボタンカウントの初期設定
      button_rule = new byte[128];
      button_number = 0;

      button_counter = new int[128];
      button_repeat_counter = new int[128];

      // コマンドリストの作成
      commands = new List<Command>();
   }

   public void setButtons(byte[] button_rule, int button_number) {
      button_rule.CopyTo(this.button_rule, 0);

      this.button_number = button_number;
   }

   public void setCommand(Command command) {
      commands.Add(command);
   }

   // private
   private Device joystick;
   private int button_number;
   private byte[] button_rule;
   private int[] button_counter, button_repeat_counter;
   private List<Command> commands;

   private static void onTimer(object sender) {
      Joystick joystick = (Joystick)sender;

      // ポーリング
      joystick.joystick.Poll();
      JoystickState js = joystick.joystick.CurrentJoystickState;

      // ボタンの検出
      byte[] buttons = js.GetButtons();

      // ここでのiは再定義した仮想番号
      // 仮想番号→実Joystick番号に変換した後データを受け取る
      for(int i = 0; i < joystick.button_number; i++){
         if(buttons[joystick.button_rule[i]] == 0x80) {
            // 通常単押しまでカウント
            if(joystick.button_counter[i] >= 5) {
               // 長押しの検出
               if(joystick.button_repeat_counter[i] > 1) {
                  foreach(Command command in joystick.commands) {
                     if(command.checkRepeatCommand(i)) {
                        command.onbutton(i, command.message);
                     }
                  }

                  joystick.button_repeat_counter[i] = 0;
               }
               else {
                  joystick.button_repeat_counter[i]++;
               }

               // 1回目だけ単押し
               if(joystick.button_counter[i] == 5) {
                  foreach(Command command in joystick.commands) {
                     if(command.checkCommand(i)) {
                        command.onbutton(i, command.message);
                     }
                  }
               }
            }

            joystick.button_counter[i]++;
         }
         else {
            joystick.button_counter[i] = 0;
            joystick.button_repeat_counter[i] = 0;
         }
      }
   }

   // 仮想番号を登録または、アナログスティックの登録
   public class Command {
      // public
      public onButton onbutton;
      public string message;

      public enum analog_direction {
         RX, RY, LX, LY, ZX, ZY, NONE
      };

      public Command(int no, string message) {
         this.no = no;
         this.is_repeat = false;
         this.ad = analog_direction.NONE;
         this.message = message;
      }

      public Command(int no, bool is_repeat, string message) {
         this.no = no;
         this.is_repeat = is_repeat;
         this.ad = analog_direction.NONE;
         this.message = message;
      }

      public Command(analog_direction ad, string message) {
         this.no = 0;
         this.is_repeat = false;
         this.ad = ad;
         this.message = message;
      }

      public bool checkCommand(int no) {
         // アナログスティックの場合は無条件
         if(ad != analog_direction.NONE) {
            return true;
         }
         
         // コマンドの照会
         return this.no == no;
      }

      public bool checkRepeatCommand(int no) {
         // コマンドの照会
         return this.no == no && is_repeat;
      }

      // private
      private int no;
      private bool is_repeat;
      private analog_direction ad;
   }
}

2013/10/25

to ka  です。
CADで試作品の角材を作ってみました。

2013/10/24

浜松基地に行ってきました

Contrailです。

サークル活動とは関係ありませんが、日曜日に大学の北にある空自の浜松基地で航空祭があったので行ってきました。

あいにくの天候で、予定されていたF-15の機動飛行やブルーインパルスの演技が中止になってしまいました。ただ、気になっていたF-15のエンジンノズルの機構を見ることができたので、それは良かったです。

来月の岐阜基地の航空祭も天候がよければ見に行きたいと考えています。

また、来月9,10日にあるテクノフェスタにサークルで展示をすることになっていて、それに向けて現在活動中です。

2013/10/23

C#からRubyを実行★IronRuby★

Kです。本日2回目の投稿です。というのも、テーマごとに1つの記事にすべきなので1日に何回投稿しても構いません。メールがうざったい人は管理できる人に言ってリストから削除して貰って下さい。尚、私は削除しました。笑

さて、本題のIronRubyに関して、まずは動機を説明しましょう。先日の操縦テストプログラムの要望によって、スクリプトファイルで処理した結果をデバイスに送信する必要が出てきました。従って、C#から数値の配列を渡し、Rubyが処理し、その結果を数値の配列で受け取る必要が出てきました。

次に、必要な環境について説明しましょう。IronRubyはC#上でRubyのソースコードを解釈し、実行するプログラムです。これを組み込めば、上記の目的は達成できるでしょう。さて、これを使うには次の4つのdllファイルを参照に追加する必要があります。
  • IronRuby.dll
  • IronRuby.Libraries.dll
  • Microsoft.Dynamic.dll
  • Microsoft.Scripting.dll
これらは、公式サイトからダウンロードできます。尚、Microsoft.Dynamic.dllについてはdynamicを使用しない場合は要らないようです。(適当)

とりあえずネット上から探してコードを実行してみました。

using System;
class Program {
 public static void Main() {
  var engine = IronRuby.Ruby.CreateEngine();
  var scope = engine.CreateScope();

  engine.ExecuteFile("./test.rb", scope);
  var ss = engine.CreateScriptSourceFromString("foo()");
  ss.Execute(scope);

  int res = engine.Execute<int>("fooo", scope);
  Console.WriteLine(res);
 }
}
test.rbの中身は以下の通りです。ちなみにRubyの流派ではreturnを書きません。
def foo
 $x = 10
end

def fooo
 return $x
end
これを実行すると、10と表示されます。

中身を追っていきます。 IronRuby.Ruby.CreateEngine();でRubyのインタプリタエンジンを作成します。

次に、engine.CreateScope();で変数などを記録するフィールド(適当)を作成します。このscopeが異なると別々の領域で実行されることになってしまいますので注意。

次に、engine.ExecuteFile("./test.rb", scope);でファイル都市コープを指定して実行します。実行された結果、値が返ってきますが、今回はメソッドの定義しかしていないのでその必要はありません。

 次に、var ss = engine.CreateScriptSourceFromString("foo()");でfooというメソッドを呼び出すプログラムを作成し、そのプログラムを変数ssに代入しています。これは次の行のとおりss.Execute(scope);と実行できます。ループして実行する場合は一度プログラムを解釈した後にまとめてExecuteしたほうが速かったです。

 最後にint res = engine.Execute<int>("fooo()", scope);でfoooメソッドを実行しました。結果をintで受け取り、ごにょごにょしています。文字列の場合はstringを、配列の場合はRubyArrayを指定します。

 その後いろいろ調べていたら、 次のコードでも実行できることが分かりました。但し参照にMicrosoft.CSharpを追加する必要があります。
using System;

class Program {
 public static void Main() {
  var rt = IronRuby.Ruby.CreateRuntime();
  dynamic t1 = rt.UseFile("./test.rb");
  dynamic t2 = rt.UseFile("./test2.rb");

  t1.foo();
  t2.bar();

  Console.WriteLine(t1.fooo());
 }
}
 Rubyは次の2ファイルです。1つめがtest.rbです。
def foo
 $x = 10
end

def fooo
 return $x
end
2つめがtest2.rbです。
def bar
 $x = 20
end

さてこの実行結果は20を表示します。

まず、var rt = IronRuby.Ruby.CreateRuntime();でRubyのランタイムを作成します。(適当)次にdynamic t1 = rt.UseFile("./test.rb");でソースコードを読み込み、解析結果をt1に代入します。このとき、dynamicを指定します。これは動的に動作が変わるためです。そしてt1.foo();で実行します。

この方法ではRuby内のメソッドをC#のメソッドで呼び出せます。更に、1つめのサンプルに比べてかなり高速です。これを使うしかありませんね!!

ファイルを分割しても、同じスコープを共有されるためグローバル変数が上書きされました。

デザインを変えてみた

Kです。Bloggerのデザインを変えてみました。

初め、クラシックテンプレートで編集していましたが、細かいことが出来ないことに気づいたので(「タグ」があまりじゃないか。)適当にテンプレートを選択しました。こいつのせいで2時間くらい無駄にしました。ああ最悪!

これでも不満はばっちりなんですけどね。まず、ブログ全体の幅がpx指定じゃないといけないこと。今時どの端末で見ているかもわからないのにどうして%指定じゃないのでしょうか。px固定とか10年前かっての!他にも投稿者と時刻の表示がおかしい点や上げればきりがないのですが;

更に、bloggerに限らず段落分けの機能がないことが非常に不満です。未だにbr要素で改行を表現しているんですよ? もう2013年ですよ。 10年m(ry

いいですか、今時のブログは意味づけが出来るようなエディタであるべきです。基本は段落とリスト、表で構成されており、必要ならば強調、リンク、削除など付け加えればいいのです。

もういろいろ面倒になってきたのでこれでいいや。あ、デザイン変更するとシンタックスハイライトのコードまで削除されちゃうから注意ね!