2011年8月21日日曜日

Using TwitterAPI from Unity Web Player

This blog is a translation of this entry that written by my student.
http://d.hatena.ne.jp/anchan828/20110821

There's a crossdomain limitation to post a tweet from UnityWebPlayer.

Here, we used some detour for this.
The main idea is calling javascript function from Unity and using OAuth2.0 to POST.
We used @Anywhere to implement this.

1. Preparation

Register your application to Twitter dev(https://dev.twitter.com/).
After you finish registration, move to @Anywhere Domains in the settings section for the application and register your domain name.










ex. unity-games.appspot.com for UnityGames(http://unity-games.appspot.com/)

That's all for setting up your application.

Then, insert the line into the webpage where you want to put your UnityWebPlayer.
<script src="http://platform.twitter.com/anywhere.js?id=Consumer key for your Twitter App&v=1">



Now, you are ready to use @AnyWhere

2. Implement javascript function in the webpage.

The functions you need are Authorization and POST.
Authorization function is here.
function connect(){


var url = "https://oauth.twitter.com/2/authorize?oauth_callback_url="
      //the call back should be the webpage address where your Unity Web Player is.
+ encodeURIComponent(location.href)
+ "&oauth_mode=flow_web_client&oauth_client_identifier=Consumer Key for your Twitter App";
var F = 0;
if (screen.height > 500) {
F = Math.round((screen.height / 2) - (250))
}
  // The window option is a default for @AnyWhere
window.open(url, "twitter_anywhere_auth", "left=" + Math.round((screen.width / 2) - (250)) + ",top=" + F
+ ",width=500,height=500"
+ ",personalbar=no,toolbar=no,resizable=no,scrollbars=yes");
}
Next, post function using ajax will be like this. (The function is using JQuery(http://jquery.com))
//url will be something like "https://api.twitter.com/1/statuses/update.json". You must url encode the parameters.

function post(url) {
$.ajax({
type: "post",
     //The access token for twitter can be load with localStorage.getItem("twttr_anywhere")
url: url+ "&oauth_access_token="+encodeURIComponent(localStorage.getItem("twttr_anywhere")),
success: function (e) {
// write whatever you want to do.
}
});
}
Mind that you should use HTTPS protocol here.
You must always give "oauth_access_token=取得したAccess_Token" as a parameter for posting to Twitter.

3. Implementation in Unity.

It's easy to call javascript function in the webpage from Unity.
You can use,
Application.ExternalCall (http://unity3d.com/support/documentation/ScriptReference/Application.ExternalCall.html)

First, authorize your self. If you call the function, a popup window will be shown.
Application.ExternalCall ("connect");

Next, POST your tweet.
//URL encode your twee (http://unity3d.com/support/documentation/ScriptReference/WWW.EscapeURL.html)

Application.ExternalCall ("post", "https://api.twitter.com/1/statuses/update.json?status=" + WWW.EscapeURL (tweet));
Now, you can tweet from your Unity Web Player!
You can try the working example here ->(Let’s Twitter In UnityWebPlayer)

2011年1月14日金曜日

Head to "Sojo University Unity3D Competition"

In our university, 3rd grade students are studying game development using Unity3D in the lecture called "Animation Study". Students are required to plan and create their original 3D/2D game with Unity3D. For most students, game development is a first trial (some of them did not even make any 3D models before). They studied Blender and Unity3D, that I introduced in the lecture. Also, some students studied Metasequoia or Google Sketchup to emphasize their work. Finally, their works are forming into a game.

The evaluation of their games is done by public voting on the Web. If they get many votes, they will get a good mark!

I am building the voting system with Slim3 and AppEngine/J. They are really powerful!



You will be able to vote with Google and Mixi OpenID. Also you can use Twitter authentication.
Something like "Like" from Facebook will be supported as well.

It will start on 26th of January, if there is no problem. We hope that many people get interested in the trial. We will post the link for our voting system on the blog later.

Please vote for their games!

2010年8月26日木曜日

Using Emgu CV on Mac OSX


Yesterday, I thought of trying to run Emgu CV on Mac OSX.
I write what I did for that here.

*Emgu CV is a OSS Open CV wrapper for .Net framework.

OS: Mac OSX Snow Leopard (10.6.4) failed
Mac OSX Leopard(10.5.8) succeed!

1. Installing Mono and Monodevelop (for now you dont really need Monodevelop)

== Japanese problem ==
You need to specify a font that can be used for your own language if you are using Multi-bytes.
Create next file with admin authority.
/Library/Frameworks/Mono.Framework/Version/Current/etc/pango/pango.aliases
Write a line like below.
"Lucida Grande" = "Hiragino Kaku Gothic Pro"
==================

2. Installing depending libraries via Macports
sudo port selfupdate
sudo port upgrade outdated
sudo port install cmake
sudo port install ffmpeg
sudo port install tiff
3. Get a source code from SVN repository
svn co https://emgucv.svn.sourceforge.net/svnroot/emgucv/trunk emgucv
4. Creating make file by cmake
cmake -DBUILD_NEW_PYTHON_SUPPORT:BOOL=FALSE -DBUILD_TESTS:BOOL=FALSE .

5. Executing make
make
6. Running samples
move to bin directory
set value to read library from current directory

export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
execute a sample
mono Example.PlanarSubdivision.monoexe
Error!
System.DllNotFoundException
7. Setting Log level and execute again
MONO_LOG_LEVEL=debug mono Example.PlanarSubdivision.monoexe
It seems 64bit is not supported by Mono 2.6.7 so that it is hard to run on Snow Leopard.

8. Trying to build with 32bit option
cmake -DCMAKE_OSX_ARCHITECTURES=i386 -DBUILD_NEW_PYTHON_SUPPORT:BOOL=FALSE -DBUILD_TESTS:BOOL=FALSE .
got an error at make command.
It said something like Open CV should be 64bit...

hmm, I gave up with Snow Leopard ...

9. Trying with Leopard (10.5.8)
Mostly same as above however library path was different so set as below.
export LD_LIBRARY_PATH=../lib:.:$LD_LIBRARY_PATH
I could run the sample!

2010年7月18日日曜日

Tomcat 6 grant setting for GWT, Lucene, JPA, HIbernate and Spring Framework

WIth Ubuntu 10.04,

Running GWT on Tomcat6 with Lucene, JPA, Hibernate and Spring Framework,
you need to grant many permissions.

Write in, "04webapps.policy"

grant {

permission java.util.PropertyPermission "user.dir", "read";
permission java.util.PropertyPermission "org.apache.lucene.lockDir", "read";
permission java.util.PropertyPermission "sun.arch.data.model", "read";
permission java.util.PropertyPermission "org.apache.lucene.store.FSDirectoryLockFactoryClass", "read";
permission java.util.PropertyPermission "org.apache.lucene.analysis.standard.StandardAnalyzer.replaceInvalidAcronym", "read";
permission java.util.PropertyPermission "cglib.debugLocation", "read";
permission java.util.PropertyPermission "ANTLR_DO_NOT_EXIT", "read";
permission java.util.PropertyPermission "ANTLR_USE_DIRECT_CLASS_LOADING", "read";


//Required for Spring Framework
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.lang.RuntimePermission "getProtectionDomain";
permission java.net.SocketPermission "127.0.0.1:3306","connect,resolve,listen,accept";
permission java.net.SocketPermission "localhost:3306","connect,resolve,listen,accept";

Linux and Proxy setting notes

Linux & proxy settings are always very bothersome to search.

[apt-get] export command or set as a environmental variable
export http_proxy=http://[address]:[port]/

[wget] xport command or set as a environmental variable
export http_proxy=http://[address]:[port]/

[yum] 環xport command or set as a environmental variable
export http_proxy=http://[address]:[port]/

[rpm] use command line options
rpm --httpproxy [address] --httpport [port]

Ubuntu 10.04 sudo via ssh

When you try to send sudo command via ssh, I got this message.
sudo: no tty present and no askpass program specified

There are some entries that says you should comment out "Defaults requiretty" from /etc/sudoers, however, there is no such line in the file for Ubuntu 10.04.

Writing "Defaults visibletty" works fine although you password will be visible when you type.

It didn't sound the best solution and I found out that using "-t" option for ssh command is better way. Then the command will be something like this.

ssh -t [address] sudo shutdown -h now

In addition,
Writing the following like in "/etc/sudoers" will let you "sudo" without prompting password request.
username ALL=NOPASSWD: ALL

2010年3月1日月曜日

Japanese Morphological Analyzer on GAE

I made a Japanese morphological analyzer on Google Apps Engine.

You can input Japanese sentences and then you will see the analysis result.
http://onlinejpanalyser.appspot.com/sen/

I used Slim3 that is a full-stack MVC framework optimized for Google App Engine/Java.
Also, I used Sen to analyze Japanese sentences.

2009年10月31日土曜日

Hadoop Plugin for Eclipse 3.5.1 Galileo

Recently I started trying Apache Hadoop and there were some people wrote about Eclipse Plugin.I checked out latest source code but it seems they didn't include the plugin no longer, so I checked out version 0.19.2 that was the newest one I found that had the plugin.

I tried with hadoop 0.19.2 however the plugin didn't work well on Eclipse 3.5.1 Galileo.
The error log said they couldn't find a class and couldn't instanciate the plugin when they try to run Hadoop program. I looked through the source and found that was using "internal" class. It seemed the class was no longer in the latest Eclipse. I changed "import" sentences, fixed one bug about null checking and finally got the plugin working.

===========================
The system specification was :

Host OS : Mac OSX 10.5
Guest OS on VMware : Ubuntu 9.04

Eclipse 3.5.1 Galileo
Hadoop 0.19.2
===========================

I uploaded the fixed plugin here. In case, if anyone is trying to use the plugin, the following that I write about installation and usage will help.


First, you need to install Hadoop. I prefere downloading not the latest but version 0.19.2.
Quick Start will help greatly. Latest one( currently 0.20.1 ) is using separated files for configuration however you can just find same entries in conf/hadoop-site.xml (you might need to copy from hadoop-default.xml first time ) . Please run hadoop and create directory input on Hadoop File System (HDFS) before you go to next step. You may also want't to copy some text files in it as it is done in Quick Start.

Second, download the plugin and copy it in "plugins" directory then start Eclipse. You will see "Map/Reduce Project" when you try to create "New Project". However, you can't create its project until you configure the plugin. So, open "Preference -> Hadop Map/Reduce" and set Hadoop installed directory(fig 1). Finally we can start creating and run Hadoop project.

fig 1 : Setup Hadoop installed directory
  1. Create new Hadoop Project then Eclipse will lead you to Hadoop Plugin Perspective. Now, you can see blue elephant icons.
  2. Open "Window->Show View->Other->MapReduce Tools->Map/Reduce Locations"(fig 2).
  3. Click "Blue Elephant" in "Map/Reduce Locations" view and define Hadoop location. For testing you need to edit "Location Name", "Host" and "Port" in General tab, also you need to set "eclipse.plugin.jobtracker.host", "eclipse.plugin.jobtracker.port", "fs.default.name" (fig 3, 4).
  4. Check if you can connect to HDFS from Eclipse. In "Project Explorer", open DFS Locations.
  5. Create Hadoop programs (you can use this sample) and try running them. You can select a class that has main and "Right Click -> Run As ->Run on Hadoop" (fig 5).
  6. Choose Location and Finish then you will see Hadoop outputs in Console.
fig 2 : Map/Reduce Location View and DFS Explorer

fig 3, 4 : Hadoop Location setup


fig 5 : Running Hadoop Program


2009年9月2日水曜日

NyArtoolkit on jMonkeyEngine

I was trying to use jMonkeyEngine for a 3D engine with NyArtoolkit these few days. I uploaded my first result on Youtube.

jMonkeyEngine is a 3D game engine written in Java. It supports many features such as collisions, particle systems, shaders, terrain system and so on.


Here, I put my source codes however I modified original NyARToolkit utils library for a compatibility between mac and windows so they might not work. If you have any question, feel free to ask.

2009年3月21日土曜日

Source code for Java3D Collada1.4.1 Loader

After I answered Mariano's comment I got another work and was a bit busy so it got so late to upload my source code here. This source code is originally from j3d-incubator project so every rights should follow their policy except some codes that I wrote entirely new. My codes are published under GPL for now. I'd love to marge my code to incubator project when I get time.

Sorry for this inconvenience.

You can download source code here.

2009年1月26日月曜日

Java3D model loader for Google SketchUp

I'm trying to implement a Java3D model loader for Collada 1.4.1 format.
There's an implementation on j3d-incubator project however it doesn't seem that is supporting many functions so that I checked out from their repository and tried implementing additional functions.
When I get some result, I'd like to submit my codes.

For the first step, I tried loading models that were made with Google SketchUp (it's using Collada format) 
As you know, there is a lot of great models on 3D Warehouse and it must be very helpful if you can load them into your java 3d application.

I made a very simple applet to try loading them.
(I sincerely ask you guys to accept my personal signature that is needed to access local files by the applet)


It hasn't been supporting a lot of functions however it is able to load geometry, basic materials (such as diffuse or ambient colours) and simple textures.
Please be careful loading a large file, it might require a huge amount of memory space.

You can also download jar binary archive.
Here's a code fragment to try it. Please refer Java3D object loader usage that you can find on several web sites. 
loader.KmzLoader l = new loader.KmzLoader();
Scene s = l.load(new URL(path));
BranchGroup bg = s.getSceneGraph();
You may also need to adjust camera location or things.
I found out if the model is too large Java3D is not able to handle z buffer orders so then you need to use Transform group to scale it smaller. 
If someone has information on this problem and solution please let me know.

Hope you can enjoy it. :)
When you find bugs or have any requirements, I'd be grateful if you leave messages here.

2009年1月22日木曜日

Compiling Collada 1.5 schema by JAXB

I had a problem compiling Collada 1.5 schema by JAXB so I write problems and the way I solved it.

What you need to prepare is
  1. Download Collada 1.5.0 Schema (if the extension is "txt", the change it to "xsd")
  2. Download latest JAXB (currently 2.1.9 is the latest)
  3. Open and place them as you need. (also set a path for Java and others)
First, I tried the command "xjc collada_schema_1_5.xsd" and got the following errors.

[ERROR] Property "Source" is already defined. Use <jaxb:property> to resolve this conflict.
line 8785 of file:/Users/shiva/TMP/collada/collada_schema_1_5.xsd
...

This problem is occurred by name collision it seemed and I found a solution here
"simpleMode.xml" helped to avoid the first problem. (and it worked well for collada 1.4 schema)
The Command was 

"xjc collada_schema_1_5.xsd -extension simpleMode.xml"
(make sure the path to "simpleMode.xml")

When I tried it, "xjc" died of OutOfMemory error however I could not find a way to enlarge memory space for "xjc" command.
So that I needed to call "xjc" from "java" command as follows.

"java -Xmx1024m -jar jaxb-xjc.jar collada_schema_1_5.xsd -extension simpleMode.xsd"

This worked enough and I could get java classes for the schema.

2008年6月25日水曜日

64-bit Mac OSXではSWTがサポートされていないんだね、、、

以前公開したプラグインがMacで動かせないとの報告をいただいていたのですが、
今日Mac Bookを入手したのでいろいろ調べてみたところ
どうやら原因はSWTがサポートされていないということらしい。


困ったなぁ。

2008年6月3日火曜日

NyARToolkit Eclipse Plugin 更新

リフレクションでネイティブライブラリのロードを実現するように更新しました。

あと、NyARToolkit Eclipse Plugin 解説をA虎@さんのNyARToolkit wikiに執筆中です。
今までマニュアル皆無でごめんなさい。

Sourceforgeからダウンロードしてくださった方々。
私の説明不足だったのですが、上がっているのはソースコードでプラグインとしてインストールできる形のものではありません。
インストールはEclipseの更新マネージャを使って
http://www.ylab.ai.kyutech.ac.jp/~shiva/nativecapable/update
からお願いします。

P.S.
Macで試された方から新規プロジェクト生成ウィザードがの開始できないという報告をいただいています。近日中にMacを手に入れてやってみる予定です。しばしお待ちくださいm(_ _)m

2008年5月27日火曜日

Appletからネイティブライブラリをロードする(リフレクション編)

以前、NyARToolkitをApplet化するときに、かなり複雑なことをしてネイティブライブラリをロードしていました。
が、リフレクション使えばもっと簡単に出来そうなことに今更ながら気が付きました。

URL url = NativeLoadTest.class.getResource("jogl_awt.dll");
File file = new File(url.toURI());

ClassLoader cl = Thread.currentThread().getContextClassLoader();

Field f = ClassLoader.class.getDeclaredField("usr_paths");
f.setAccessible(true);
String[] paths = (String[]) f.get(cl);

String[] paths2 = new String[paths.length + 1];
System.arraycopy(paths, 0, paths2, 0, paths.length);
paths2[paths2.length - 1] = file.getParentFile().getAbsolutePath();

f.set(cl, paths2);
f.setAccessible(false);

System.loadLibrary("jogl_awt");
まだAppletでは試していませんが、これならかなり簡単。
もちろんセキュリティーは無視するとして。
ClassLoaderの実装依存(フィールド名が変わったらダメ)なのが問題点ですが、今更変わるものでもないでしょう。
ということで、近々NativeCapableフレームワーク更新します。


SunがApplet Launcherというものを公開しているのを最近知りました。
Java Web StartのApplet適用っていう感じです。
Sunが署名しているため、安心して使うことが出来ます。
メジャーなネイティブライブラリ(JOGLやJava3Dなど)を使う場合はこれを使うのがよさそうです。
(ライブラリ側で対応しておかないといけないのが難点ですが)

時間があれば使ってみて感想を書きたいと思います。

2008年5月21日水曜日

Sourceforge.jpのSVNをEclipseから使う

ちょっと面倒くさいので、参考リンクをメモ。
どっちもSourceforgeJPにきちんと書いてあるんだけどね。


2008年5月20日火曜日

NyARToolkit on Google Android 更新と公開


ずいぶん前にNyARToolkitをAndroidの上で動かしてみたわけですが、
NyARToolkitの作者 A虎@ さんのご好意によりSourceforge.jpにてサブプロジェクトとして公開することになりました!

Eclipseのプロジェクトをエクスポートしたものなので、動かすにはAndroidSDKおよびプラグインが必要です。
(みゅおさんがAndroidのドキュメントを日本語化しておられます。ありがたい!)


当時にくらべて本家NyARToolkitが格段にブラッシュアップされているため速度も大幅に改善。
1.2秒に一回ぐらい認識できます、、、前は10秒だったからね。。。
(開発環境がとても貧弱なため、Androidエミュレータの制限によるものでは無い可能性もあります)
ついでに少しUIも付けてみました。実機欲しいなぁ~。


エミュレータでは現在のところカメラデバイスは実装されていないので
JMFでキャプチャした画像をソケット通信で送ってます。
送信用のプログラムサンプルも同封してありますが、
関連ライブラリが必要で面倒なのでApplet及びJWSにしたものを公開します。
現在のところWindows版のみです。

P.S.
Flash版も開発され空前のAR移植ブームですなぁ。しみじみ。
開発環境およびNativeCapableフレームワークもほぼ完成し今週中には公開できそうです。
いろんなARアプリがブラウザの上で遊べる時代になると楽しいな!!

2008年5月8日木曜日

テキストフィールド等で入力補完を使う

テキストエディタに対してコード補完を設定する方法は幾つか紹介されているのだが、
テキストフィールドやリストなどで入力補完を行う方法は見つけ難かったのでメモ。

Text text = ....
IControlContentAdapter contentAdapter = new TextContentAdapter();
IContentProposalProvider provider = new IContentProposalProvider() {
public IContentProposal[] getProposals(String contents, int position) {
IContentProposal[] icps = ....
}
}
ContentAssistCommandAdapter ca = new ContentAssistCommandAdapter(
text, contentAdapter, provider, null, new char[] {}, true);

解ってしまえば非常に簡単。

NyARToolkit Eclipse Plugin 更新 ~ エクスポート機能

ずいぶん間が空きましたが、少し機能追加や変更を行いました。
NyARToolkitに限らず、NativeなApplet(及びデスクトップアプリ)を開発する環境に方向が変わってきつつあります。
名前をNativeCapableプラグインに変更しました。

Native Capable Eclipse Plugin
ダウンロードしてpluginsフォルダに配置してください。

Eclipseプロジェクトを圧縮したものは以下からダウンロードできます。
Eclipse Project

小さな変更点:
Windows以外のプラットフォームでも利用できるようにネイティブライブラリの配備を変更
(手元に他の環境がないため、Windows以外のライブラリは同封されていません)

大きな機能追加:
NativeCapableModuleを実装したクラスからAppletとアプリケーションを自動生成するExportウィザードを追加しました。

作業中のプロジェクトで
PackageExplorer->右クリックメニュー->Export(エクスポート)
を選びます。


Module: 対象となるNativeCapableModule実装クラスを指定
Create: 生成物を指定
Targets: 対象クラスの設定
Strategy: 対象クラスのロード方法を指定
-Delegate Targets: 対象クラス以外をNativeCapableローダでロード
-Load Targets:対象クラスをNativeCapableローダでロード

次回目標:
Antファイルの自動生成、自動実行でApplet及びJWSとしてデプロイ可能な状態にするExport機能の実装!!

2008年4月27日日曜日

Native library loading framework for Applet (Native Capable)

NyARToolkitのデモAppletを作る際、JMFやJOGLなど実行時にネイティブライブラリを必要とするAPI利用のためにクラスローダ等を実装したのですが、全体をフレームワーク化したので公開します。
ライセンスはLGPLとしています。

(2008/5/8 追記) テンポラリファイルが削除されないバグを修正しました。
File.deleteOnExit関数がWindows上では正しく機能しない既知のバグ
によるものです。



Applet、Java Web Startまたはスタンドアロンアプリケーションにおいて、ネイティブライブラリを可能な限り同じコードで利用できることを目的として作成したフレームワークです。(JWSにはネイティブを扱う機構が存在します)
動作には、nativecapable.jarのほかにjavassist.jar、ant.jarが必要です。
(バイナリ&ソース&サンプルに同封)

何かに使って見た際にでも感想などいただけると幸せです^^

以下に使用方法を説明します。

1. NativeCapableModuleの実装

ネイティブライブラリを利用したいモジュールはNativeCapableModuleインタフェースを実装します。NativeCapableModuleインタフェースでは4つのメソッドが定義されています。

       //モジュールの初期化処理を記述します
      public boolean initModule();
       //モジュールの停止及び破棄処理を記述します
      public boolean destroyModule();
       //GUIアプリケーションの場合、
       //最上位に配置されるコンポーネントを返す処理を記述します
      public Component getRootComponent();
       //モジュールの開始処理を記述します
       public boolean startModule();

NativeCapableModuleの実装クラスはApplet及びスタンドアロンアプリケーションとして利用することができます。

2.Appletとして実装する

Appletとして実装する場合はNativeCapableAppletクラスを継承して利用します。
NativeCapableAppletクラスはJAppletクラスを継承し、NativeCapableインタフェースを実装しています。
Java3DTestAppletをもとに説明します。(バイナリ&ソース&サンプルに含まれる)

public class Java3DTestApplet extends NativeCapableApplet {
    public void init() {
               //Moduleの生成を行うインスタンスを生成します
             NativeCapableModuleBuilder builder = new NativeCapableModuleBuilder(
           this, "java3d.Java3DTestModule");

               //ネイティブライブラリを利用するクラスのロードについて設定します -  ①
             Collection col = new HashSet();
             col.add("javax.media.j3d");
              builder.setTargetPackages(col);
             builder.setDelegateTargets(false);

               //Moduleインスタンスを生成します
              NativeCapableModule module = builder.newModule();
               //モジュールの初期化
              module.initModule();
               //モジュールからAppletに追加するコンポネントを取得して追加します
              add(module.getRootComponent());

               //必要に応じてstartやdestroyを呼び出します。
              //module.startModule();
              //module.destroyModule();
}

① クラスのロードについて
NativeCapableModuleBuilder#setDelegateTarget(boolean)メソッドによりターゲット指定されたパッケージに属するクラスをNativeCapableClassLoaderでロードするか、指定されたもの意外をロードするかを設定することができます。
NyARToolkitのデモであるJavaSimpleLiteAppletでは次のように使用しています。

               Collection col = new HashSet();
             boolean dTargets = true;
              if (!dTargets) {
               col.add("javax.media.");
               col.add("com.sun.opengl.");
               col.add("jp.nyatla.");
                col.add("com.sun.media.");
                col.add("jp.ac.kyutech.ai.ylab.shiva");
             } else {
               col.add("java.");
                col.add("javax.swing.");
                col.add("sun.reflect.");
             }
            builder.setTargetPackages(col);
             builder.setDelegateTargets(dTargets);

3.スタンドアロンアプリケーションとして実装する

Appletの場合とほぼ同じですが、NativeCapableApplicationを利用します。
public class Java3DTestApplication {
    public static void main(String[] args) throws Exception {
           NativeCapableApplication nca = new NativeCapableApplication();
           NativeCapableModuleBuilder builder = new NativeCapableModuleBuilder(
         nca, "java3d.Java3DTestModule");

            Collection col = new HashSet();
            col.add("javax.media.j3d");
           builder.setTargetPackages(col);
            builder.setDelegateTargets(false);

           final NativeCapableModule module = builder.newModule();
            module.initModule();

           nca.add(module.getRootComponent());
           nca.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            nca.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                  module.destroyModule();
              }
           });
           nca.setBounds(100, 100, 640, 480);
           nca.setVisible(true);

           module.startModule();
}

4.ネイティブライブラリを配備

以下に説明する設定ファイルで指定したディレクトリに必要なネイティブライブラリを配備します。

ネイティブライブラリ設定ファイル(os.xml)
OSごとに利用するライブラリの設定をos.xmlに記述します。os.xmlはNativeCapableModuleのクラスファイルが存在するディレクトリルートに配備します。
配備例

記述例
<?xml version="1.0" encoding="UTF-8" ?>
<libraries>
<library arch="x86" name="Windows" path="native/x86/windows" />
<library arch="x86" name="Linux" path="native/x86/linux" />
</libraries>

archプロパティにはアーキテクチャをnameプロパティはOSの名前を指定します。
それぞれつぎのJavaプログラムで取得される文字列と前方一致を行います。
  System.getProperty("os.name");
  System.getProperty("os.arch");
pathプロパティにはネイティブライブラリの位置をos.xmlファイルからの相対パスで指定します。

5.AppletやJavaWebStart(JWS)として公開する場合の注意点
ネイティブライブラリを実行時に展開するためにサンドボックス外へのアクセスが必要となります。
そのため、AppletやJWSにする場合はJARファイルに署名を行う必要があります。
署名つきJARファイルの作成やJWSでのパーミッション設定などはここでは省略します。