2012年7月29日 星期日

JAVA Httpd Server (with thread)

neotestserver.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class neotestserver{
  public static void main(String args[]) {
    int port;
    ServerSocket server_socket;
    try {
      port = Integer.parseInt(args[0]);
    } catch (Exception e) {
      port = 2222;
    }
    try {
      server_socket = new ServerSocket(port);
      System.out.println("Web伺服器監聽port:"
          + server_socket.getLocalPort());

      // server infinite loop
      while (true) {
        Socket socket = server_socket.accept();
        System.out.println("偵測新的連線在" +socket.getInetAddress() + ":" + socket.getPort());
        try {
          httpRequestHandler request = new httpRequestHandler(socket);
          Thread thread = new Thread(request);
          thread.start();
        } catch (Exception e) {
          System.out.println(e);
        }
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}

class httpRequestHandler implements Runnable {
  Socket socket;
  InputStream input;
  OutputStream output;
  BufferedReader br;

  public httpRequestHandler(Socket socket) throws Exception {
    this.socket = socket;
    this.input = socket.getInputStream();
    this.output = socket.getOutputStream();
    this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  }
  
  public void run() {
    try {
    	while (true) {
    	      String headerLine = br.readLine();
    	      System.out.println(headerLine);
    	      if (headerLine.equals("\r\n") || headerLine.equals(""))
    	        break;
    	      StringTokenizer s = new StringTokenizer(headerLine);
    	      String temp = s.nextToken();
    	      if (temp.equals("GET")) {
    	    	  String fileName = s.nextToken();  //GET之後是fileName
    	    	  fileName = "." + fileName;		  //fileName前面記得加上"."
    	    	  FileInputStream fis = null;
    	    	  boolean fileExists = true;
    	    	  try {
    	    		  fis = new FileInputStream(fileName);
    	    	  } catch (FileNotFoundException e) {
    	    		  fileExists = false;
    	    	  }
    	    	  String urlstr ="";
    	    	  if (fileExists) {
    	    		  urlstr = "HTTP/1.0 200 OK\r\n" + "Content-type: " + contentType(fileName) + "\r\n" + "Content-Length: " + (new Integer(fis.available())).toString() + "\r\n" + "\r\n";
    	        	  //填上fileName的內容
    	    		  output.write(urlstr.getBytes());
    	    		  byte[] buffer = new byte[1024];
    	    		  int bytes = 0;
    	    		  while ((bytes = fis.read(buffer)) != -1) {
    	    			  output.write(buffer, 0, bytes);
    	    		  }
    	    		  socket.close();
    	    	  } else {
    	    		  urlstr = "HTTP/1.0 404 Not Found\r\n" + "text/html\r\n\r\n" + "<HTML> <HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY>404 Not Found<br>usage:http://yourHostName:port/fileName.html</BODY></HTML>\r\n";
    	    		  output.write(urlstr.getBytes());
    	    		  socket.close();
    	    	  }   
    	      }
    	    }    
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  
  private static String contentType(String fileName) {
    if (fileName.endsWith(".htm") || fileName.endsWith(".html")
        || fileName.endsWith(".txt")) {
      return "text/html";
    } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
      return "image/jpeg";
    } else if (fileName.endsWith(".gif")) {
      return "image/gif";
    } else {
      return "application/octet-stream";
    }
  }
}     

2012年7月28日 星期六

JDBC MySQL

加入mysql-connector-java-5.1.21-bin.jar
package neo.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcMySQL {
 Connection conn;
 String username;
 String password;
 String url;
 String databaseName;
 String port = "3306";
 String sqlstr = "jdbc:mysql://"+url+":"+port+"/"+databaseName+"?useUnicode=true&characterEncoding=UTF-8";
 String userNameString = "name";
 String passwdNameString = "passwd";
 public JdbcMySQL(String url, String databaseName, String username, String password){
  sqlstr = "jdbc:mysql://"+url+":"+port+"/"+databaseName+"?useUnicode=true&characterEncoding=UTF-8";
  //透過java.lang.Class類別的forName()來載入並向DriverManager註冊JDBC驅動程式(驅動程式會自動透過DriverManager.registerDriver()方法註冊), MySQL的驅動程式類別是com.mysql.jdbc.Driver
   try
       {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
       //jdbc:mysql://主機名稱:連接埠/資料庫名稱?參數1=值1&參數2=值2
      conn = java.sql.DriverManager.getConnection(sqlstr,username,password);
   if(!conn.isClosed()) System.out.println("MySQL資料庫連線成功"); 
  } catch (SQLException e) {
   System.out.println("連不上MySQL!!!"); 
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
 public void getConnection(){
   try
       {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
       //jdbc:mysql://主機名稱:連接埠/資料庫名稱?參數1=值1&參數2=值2
      conn = java.sql.DriverManager.getConnection(sqlstr,username,password);
   if(!conn.isClosed()) System.out.println("MySQL資料庫連線成功"); 
  } catch (SQLException e) {
   System.out.println("連不上MySQL!!!"); 
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
 public void close(){
  try {
   conn.close();
  } catch (SQLException e) {
   System.out.println("無法關閉跟MySQL的連線!!!"); 
  }
 }
 public void createTable(){
  String createdbSQL = "CREATE TABLE User (" +
     "    id     INTEGER " +
     "  , name    VARCHAR(20) " +
     "  , passwd  VARCHAR(20))";
  try {
   conn.setAutoCommit(false);
   Statement state = conn.createStatement();
   state.executeUpdate(createdbSQL);
   conn.commit();
  } catch (SQLException e) {
   System.out.println("MySQL新建資料表失敗!!!"); 
   e.printStackTrace();
  } 
 }
 public void insertData(String name, String passwd){
  String insertdbSQL = "insert into User(id,name,passwd) " +
       "select ifNULL(max(id),0)+1,?,? FROM User";
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(insertdbSQL);
   pst.setString(1, name);
   pst.setString(2, passwd);
   pst.executeUpdate();
   conn.commit();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public void updateData(int id,String name, String passwd){
  String insertdbSQL = "update User set name = ? ,passwd = ? where id = ?";
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(insertdbSQL);
   pst.setInt(3, id);
   pst.setString(1, name);
   pst.setString(2, passwd);
   pst.executeUpdate();
   conn.commit();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public void delete(String tableName,String username){
  String sql = "delete from "+tableName+" where "+userNameString+" = ?";
  Statement state;
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(sql);
   pst.setString(1, username);
   pst.execute();
   conn.commit();
   System.out.println("刪除成功!!!");   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   System.out.println("刪除失敗!!!"); 
   e.printStackTrace();
  }
 }
 public void research(){
  String sql = "select * from User";
  Statement state;
  try {
   conn.setAutoCommit(false);
   state = conn.createStatement();
   ResultSet rs = state.executeQuery(sql);
   conn.commit();
   while (rs.next()) {
    System.out.println(rs.getInt("id"));
    System.out.println(rs.getString("name"));
    System.out.println(rs.getString("passwd"));  
     //System.out.println(rs.toString());
    }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public boolean validation(String tableName,String username,String passwd){
  String sql = "SELECT "+passwdNameString+" FROM `"+tableName+"` WHERE "+userNameString+"=?";
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(sql);
   pst.setString(1, username);
   ResultSet rs = pst.executeQuery();
   conn.commit();
   while (rs.next()) {
    if (rs.getString(passwdNameString).equalsIgnoreCase(passwd)) return true;
   }
   return false;
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return false;
  
 }
}

2012年7月27日 星期五

JAVA multi-client server


MUDApplication.java
package neo.mudserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;


public class MUDApplication {
 public static void main(String[] args) throws InterruptedException, IOException {
  Server myServer = new Server(2222,50,10);
  long timestamp;
  long sleep;
  while(true){
   timestamp = System.currentTimeMillis();
   Client newclient = myServer.acceptNewConnetcion();
   if(newclient != null){
    Date date = new Date();
    System.out.println(date.toString()+"建立了新連線");
    myServer.flush();
   }
   ArrayList<CommandSet> cmds = null;
   cmds = myServer.readMessageFromClient();
   doProcessCommandSet(cmds);
   myServer.flush();
   sleep = 250 - (System.currentTimeMillis() - timestamp);
   if (sleep > 0)
    Thread.sleep(sleep);
  }
 }
 public  static void doProcessCommandSet(ArrayList cmds){
  Iterator<CommandSet> i = cmds.iterator();
  while(i.hasNext()){
   CommandSet command = i.next();
   Client client = command.client;
   String commandmessage = command.commandMessage;
   System.out.println("收到client("+client.ID+")端傳來的訊息:"+commandmessage);
   String colorWhite = (char) 27 + "[1;37m";
   client.write(colorWhite+"Server收到你傳去的message:\""+commandmessage+"\"\r\n");
   if(commandmessage.equalsIgnoreCase("quit")){
    try {
     client.close();
    } catch (IOException e) {
     System.out.println("嘗試關閉client("+client.ID+")端連線失敗");
    }
   }
  }
 }
}


Server.java
package neo.mudserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;

public class Server {
 ServerSocket serversocket;
 ArrayList<Client> clients;
 int port;
 int serverSocketTimeout;
 int clientSocketTimeout;
 public Server(int port, int serverSocketTimeout,int clientSocketTimeout){
  try {
   this.port = port;
   this.serverSocketTimeout = serverSocketTimeout;
   this.clientSocketTimeout = clientSocketTimeout;
   System.out.println("監聽"+port+"埠:");
   serversocket = new ServerSocket(port);
   clients = new ArrayList<Client>();
   serversocket.setSoTimeout(serverSocketTimeout);  //注意要設timeout時間server才不會pending在那裏
  } catch (IOException e) {
   System.out.println(+port+"埠被占用,關閉連線");
  }
 }
 public Client acceptNewConnetcion() throws IOException{
  Client client = null;
  try {
   Socket socket = serversocket.accept();
   client = new Client(this, clients.size(),socket);
   client.socket.setSoTimeout(clientSocketTimeout); //不設timeout的話Server的readMessageFromClient做client.read()就會hold在那裏
   clients.add(client);
   String colorCyan = (char) 27 + "[1;36m";
   client.write(colorCyan+"跟Server建立了連線\r\n");
  } catch (SocketTimeoutException e) {
   //當TimeOut時繼續做acceptNewConnetcion之後的動作所以這裡為空指令
  }
  return client;
 }
 public void flush(){
  Iterator<Client> i = clients.iterator();
  while (i.hasNext()){
   Client currectClient = i.next();
   try {
    currectClient.flush();
   } catch (IOException e) {
    System.out.println("client("+currectClient.ID+")不能被flush");
   }  
  }
 }
 public ArrayList<CommandSet> readMessageFromClient() throws IOException{
  ArrayList<CommandSet> cmds= new ArrayList();
  Iterator i = clients.iterator();
  while(i.hasNext()){
   String inputMessage;
   Client currectClient = i.next();
   try {
    currectClient.read();
   } catch (SocketTimeoutException e) {
    //當TimeOut時視為沒有輸入這裡為空指令
   }
   inputMessage = currectClient.inBuffer;
   if (inputMessage != null) cmds.add(new CommandSet(currectClient, inputMessage));
  }
  return cmds;
  
 }
}

Client.java
package neo.mudserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class Client {
 enum State{promptName,promptNameVerivfy,connected};
 int ID;
 Server server;
 Socket socket;
 StringBuffer outBuffer;
 String inBuffer;
 public Client(Server server, int cliendID, Socket socket) throws SocketException{
  this.ID = cliendID;
  this.server = server;
  this.socket = socket;
  this.outBuffer = new StringBuffer();
  this.inBuffer = null;
 }
 public void write(String message){
  this.outBuffer.append(message);
 }
 public void flush() throws IOException {
  OutputStream outputstream = socket.getOutputStream(); //socket是從server來的所以對server而言是output
  outputstream.write(outBuffer.toString().getBytes());
  outBuffer.setLength(0); //命令輸出了之後要記得清零
 }
 public void read() throws IOException,SocketTimeoutException{
  inBuffer = null;
  BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  inBuffer = br.readLine();
 }
 public void close() throws IOException{
  socket.close();
  server.clients.remove(this);
 }
}

CommandSet.java
package neo.mudserver;

public class CommandSet {
 Client client;
 String commandMessage;
 public CommandSet(Client client, String message){
  this.client = client;
  this.commandMessage = message;
 }
}

2012年7月24日 星期二

Java Applet


用javac -encoding utf-8 neoApplet.java 編譯

neoApplet.java
   import java.awt.*; 
   import java.awt.event.*; 
   import java.applet.Applet; 
   import java.applet.AudioClip;
    
    public class neoApplet extends Applet implements ItemListener,ActionListener,MouseListener,MouseMotionListener{ 
        Button btn;                   //  宣告 Button 型態的變數 btn 
     int image_x=10,image_y=10,dx,dy; 
  Image img; 
  Image imgBackup;      //  宣告 Image 類別型態的變數 imgB 
        Graphics gBackup;      //  宣告 Graphics 類別型態的變數 gB 
     boolean clicked=false;  
  AudioClip midi[]=new AudioClip[2]; //  宣告 AudioClip 介面型態的陣列  
        AudioClip midiplayer;  //  宣告 AudioClip 介面型態的變數 current
        Choice chc=new Choice();   //  建立 Choice 元件    
  public void mouseMoved(MouseEvent e){}   //MouseMotionListener
     public void mouseEntered(MouseEvent e){} //MouseListener
        public void mouseExited(MouseEvent e){}  //MouseListener
        public void mouseReleased(MouseEvent e){}//MouseListener
  public void mousePressed(MouseEvent e) 
  { 
   dx=e.getX()-image_x;  //  取得按下之點與基準點 x 方向之距離
   dy=e.getY()-image_y;  //  取得按下之點與基準點 y 方向之距離 
        } 
  public void mouseDragged(MouseEvent e) 
  { 
     if(dx>0 && dx< Integer.valueOf(getParameter("imageWIDTH")) && dy>0 && dy< Integer.valueOf(getParameter("imageHEIGHT")))  //  如果指標落在圖形上方 
         { 
    image_x=e.getX()-dx;   //  取得拖曳時,基準點的 x 座標 
            image_y=e.getY()-dy;   //  取得拖曳時,基準點的 y 座標 
   paint(getGraphics()); 
            //Graphics g=getGraphics(); 
           // update(g);   //  清空畫面為背景顏色,再呼叫 paint() 
        } 
      } 
  public void mouseClicked(MouseEvent e)
        { 
   }  
      public void init() 
   {  
      midi[0]=getAudioClip(getCodeBase(),"sky.mid"); 
         midi[1]=getAudioClip(getCodeBase(),"panther.mid");   
   midiplayer=midi[0];
   midiplayer.play(); 
   chc.add(" sky "); 
         chc.add(" panther "); 
   add(chc);
   
         btn=new Button(getParameter("buttonCaption"));     //  建立 btn 物件  
         btn.addActionListener(this);  //  以 applet 本身當成 btn 的傾聽者  
   add(btn);  //  將 btn 按鈕加入 applet 視窗裡  
   img=getImage(getCodeBase(),getParameter("imageFileName"));  //  載入圖檔  
   imgBackup=createImage(getWidth(),getHeight()); 
   gBackup=imgBackup.getGraphics();
   
   addMouseListener(this);  //  設定 applet 為自己本身的傾聽者 
   addMouseMotionListener(this);     
         chc.addItemListener(this);   //  把 applet 當成 chc 的傾聽者   
      } 
    public void paint(Graphics g) 
      {
     gBackup.setColor(new Color(255,255,255));      //  設定繪圖顏色為白色  
        gBackup.fillRect(0,0,getWidth(),getHeight()); //  以白色填滿整個畫面  
  gBackup.setColor(Color.blue);     //  設定繪圖顏色為藍色  
        gBackup.fillOval(30,30,50,50);    //  繪出圓形並填滿藍色  
        gBackup.drawImage(img,image_x,image_y,this);  //  將 img 畫上    
  gBackup.setColor(Color.orange);   //  設定繪圖顏色為橘色  
        gBackup.fillOval(60,40,90,90);    //  繪出圓形並填滿橘色 
        g.drawImage(imgBackup,0,0,this);   //  將 imgB 的內容顯示在 applet 上  
  
    } 
      public void actionPerformed(ActionEvent e) 
      { 
   System.out.println("Button was clicked message show in the java console");
         if(btn.getLabel().equals(getParameter("buttonCaption"))) 
   {   
   btn.setLabel("clicked");    //  設定按鈕上方的文字為 Stop 
   }
   else {          
   btn.setLabel(getParameter("buttonCaption"));   //  設定按鈕上方的文字
   }
      } 
    public void itemStateChanged(ItemEvent e) 
       { 
        midiplayer.stop();                      //  停止播放歌曲  
        int index=chc.getSelectedIndex();      //  取得被選取的索引值  
 midiplayer=midi[index];     //  設定播放的歌曲為 midi[index] 
        midiplayer.play();          //  播放歌曲  
       }    
    } 

web.html.
<!-- web.htm --> 
   <HTML> 
   <BODY BGCOLOR = "FFFF00" > 
   <APPLET                      
      CODE    = "neoApplet.class"  
      WIDTH   = "180"           
      HEIGHT  = "180"
      ALT     = " 很抱歉,您的瀏覽器不支援 Java applet" 
      ALIGN   = "MIDDLE"     
      VSPACE  = "20"   
 >
   <PARAM NAME = "buttonCaption" VALUE = "按鈕"> 
   <PARAM NAME = "imageFileName" VALUE = "logo.jpg"> 
   <PARAM NAME = "imageWIDTH" VALUE = "55">
   <PARAM NAME = "imageHEIGHT" VALUE = "55"> 
   </APPLET> 
   </BODY> 
   </HTML> 

要想在前面加package neo.applet; 封裝起來的話
用JAR方式可用 jar cvf neoAppletExample.jar -C ./classes/* .
注意最後有個點,classes下是/classes/neo/applet/neoApplet.class
web_jar.html

   <HTML> 
   <BODY BGCOLOR = "FFFF00" > 
   <APPLET  
         
      CODEBASE   =   "."  
      CODE    = "neo.applet.neoApplet"  
      ARCHIVE = "neoAppletExample.jar"
      WIDTH   = "180"           
      HEIGHT  = "180"
      ALT     = " 很抱歉,您的瀏覽器不支援 Java applet" 
      ALIGN   = "MIDDLE"     
      VSPACE  = "20"   
 >
   <PARAM NAME = "buttonCaption" VALUE = "按鈕"> 
   <PARAM NAME = "imageFileName" VALUE = "logo.jpg"> 
   <PARAM NAME = "imageWIDTH" VALUE = "55">
   <PARAM NAME = "imageHEIGHT" VALUE = "55">
 </APPLET> 
   </BODY> 
   </HTML> 

2012年7月23日 星期一

Apache Ant


build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="NEO TEST" default="run" basedir=".">
 <property name="src" value="src"/>
 <property name="dest" value="destfolder"/>
 <property name="hello_jar" value="hello1.jar"/>
 <target name="init">
  <mkdir dir="${dest}"/>
 </target>
 <target name="compile" depends="init">
  <javac srcdir="${src}" destdir="${dest}"/>
 </target>
 <target name="build" depends="compile">
  <jar jarfile="${hello_jar}" basedir="${dest}"/>
 </target>
 <target name="run" depends="build">
  <java classname="test.ant.neo" classpath="${hello_jar}"/>
 </target>
 <target name="clean">
  <delete dir="${dest}"/>
  <delete file="${hello_jar}"/>
 </target>
 <target name="rerun" depends="clean,run">
  <ant target="clean"/>
  <ant target="run"/>
 </target>
 </project>


neo.java在./src中

Box2D


CB的global compiler settings -> compiler settings -> Other options 填-fexceptions
#defines填FREEGLUT_STATIC
link libraries加入libFreeGLUT.a libGLUI.a GlU32(GlU32.Lib) Gdi32(Gdi32.Lib) OpenGL32(OpenGL32.Lib) User32(User32.Lib) WinMM(WinMM.Lib)
多加一個libBox2D.a
main.cpp
#include "gluiDraw.h"
#include "glui/GL/glui.h"
#include "myBox2D.h"

MyBox2D mybox2d;
GluiDraw draw;
GLint mainWindow;
GLint winWidth = 640;
GLint winHeight = 640;
int tx, ty, tw, th;
float viewCenterX=0,viewCenterY=0;
GLUI *glui;
int framePeriod = 16;
float viewZoom = 1.0f;
NeoVec2 mp,pre_mp;
bool isMouseRightPressed = false;
bool isMouseLeftPressed = false;

void Resize(int32 newWidth, int32 newHeight)
{
 winWidth = newWidth;
 winHeight = newHeight;
 GLUI_Master.get_viewport_area(&tx, &ty, &tw, &th);
 glViewport(tx, ty, tw, th);

 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 float32 ratio = float32(tw) / float32(th);

 b2Vec2 extents(ratio * 25.0f, 25.0f);
 extents *= viewZoom;

 b2Vec2 lower(viewCenterX-extents.x,viewCenterY-extents.y);
 b2Vec2 upper(viewCenterX+extents.x,viewCenterY+extents.y);

 // L/R/B/T
 gluOrtho2D(lower.x, upper.x, lower.y, upper.y);
}

void Mouse(int button, int state, int x, int y)
{
 // Use the mouse to move things around.
 if (button == GLUT_LEFT_BUTTON)
 {
  int specialKey  = glutGetModifiers();
  if (state == GLUT_DOWN)
  {
   if (specialKey  == GLUT_ACTIVE_SHIFT)
   {
               //  cout << "GLUT_LEFT_BUTTON click with SHIFT" << endl;
   }
   else
   {
                // cout << "GLUT_LEFT_BUTTON click" << endl;
   }
  }

  if (state == GLUT_UP)
  {
               // cout << "GLUT_LEFT_BUTTON release" << endl;
  }
 }
 else if (button == GLUT_RIGHT_BUTTON)
 {
  if (state == GLUT_DOWN)
  {
      isMouseRightPressed = true;
           // cout << "GLUT_RIGHT_BUTTON click" << endl;
  }

  if (state == GLUT_UP)
  {
      isMouseRightPressed = false;
           // cout << "GLUT_RIGHT_BUTTON release" << endl;
  }
 }
}
b2Vec2 ConvertScreenToWorld(int32 x, int32 y)
{
 float32 u = x / float32(tw);
 float32 v = (th - y) / float32(th);

 float32 ratio = float32(tw) / float32(th);
 b2Vec2 extents(ratio * 25.0f, 25.0f);
 extents *= viewZoom;

 b2Vec2 lower(viewCenterX-extents.x,viewCenterY-extents.y);
 b2Vec2 upper(viewCenterX+extents.x,viewCenterY+extents.y);

 b2Vec2 p;
 p.x = (1.0f - u) * lower.x + u * upper.x;
 p.y = (1.0f - v) * lower.y + v * upper.y;
 return p;
}
void MouseMotion(int x, int y)
{
    b2Vec2 p = ConvertScreenToWorld(x, y);
    if(isMouseRightPressed)
    {
        float distanceX = p.x - pre_mp.x;
        float distanceY = p.y - pre_mp.y;
        viewCenterX -= distanceX;
  viewCenterY -= distanceY;
  Resize(winWidth, winHeight);
  p = ConvertScreenToWorld(x, y);
        pre_mp.x = p.x;
        pre_mp.y = p.y;
        glutPostRedisplay(); //要求重畫視窗
    }
    //cout << "Mouse clicked and x=" << mp.x << ",y=" << mp.y << endl;
}
void MouseWheel(int wheel, int direction, int x, int y)
{
 B2_NOT_USED(wheel);
 B2_NOT_USED(x);
 B2_NOT_USED(y);
 if (direction > 0)
 {
  viewZoom /= 1.1f;
 }
 else
 {
  viewZoom *= 1.1f;
 }
 Resize(winWidth, winHeight);
}
void Keyboard(unsigned char key, int x, int y)
{
switch (key)
 {
 case 27:
     exit(0);
  break;
    case 'a':
        mybox2d.m_bodies[2]->ApplyForce(b2Vec2(-400,0), mybox2d.m_bodies[2]->GetWorldPoint(b2Vec2(1,1)));
        break;
    case 'd':
        mybox2d.m_bodies[2]->ApplyForce(b2Vec2(400,0), mybox2d.m_bodies[2]->GetWorldPoint(b2Vec2(-1,1)));
        break;
    default:
        break;
 }
}
void KeyboardSpecial(int key, int x, int y)
{
 B2_NOT_USED(x);
 B2_NOT_USED(y);

 switch (key)
 {
 case GLUT_ACTIVE_SHIFT:
  // Press left to pan left.
 case GLUT_KEY_LEFT:
  viewCenterX -= 0.5f;
  Resize(winWidth, winHeight);
  break;

  // Press right to pan right.
 case GLUT_KEY_RIGHT:
  viewCenterX += 0.5f;
  Resize(winWidth, winHeight);
  break;

  // Press down to pan down.
 case GLUT_KEY_DOWN:
  viewCenterY -= 0.5f;
  Resize(winWidth, winHeight);
  break;

  // Press up to pan up.
 case GLUT_KEY_UP:
  viewCenterY += 0.5f;
  Resize(winWidth, winHeight);
  break;
 }
}

void drawWholeBody(b2World* world,b2Body* m_bodies[])
{
     int32 bodyCount = world->GetBodyCount();
     for(int number = 0; number < bodyCount; number++)  //扣掉地面一個body
    {
        const b2Transform& xf = m_bodies[number]->GetTransform();
        for (b2Fixture* fixture = m_bodies[number]->GetFixtureList();fixture; fixture = fixture->GetNext())
        {
            switch (fixture->GetType())
            {
                case b2Shape::e_circle:
                {
                    b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
                    b2Vec2 center = b2Mul(xf, circle->m_p);
                    float32 radius = circle->m_radius;
                    b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); //還沒用到
                    draw.DrawSolidCircle(NeoVec2(center.x,center.y),radius,NeoVec2(axis.x,axis.y),NeoColor(1,1,1));
                }
                break;
                case b2Shape::e_edge:
                {
                    b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
                    b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
                    b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
                    draw.DrawLine(NeoVec2(v1.x,v1.y),NeoVec2(v2.x,v2.y),NeoColor(0,1,0));
                 }
                break;
                case b2Shape::e_chain:
                {
                    b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
                    int32 count = chain->GetVertexCount();
                    const b2Vec2* vertices = chain->GetVertices();

                    b2Vec2 v1 = b2Mul(xf, vertices[0]);
                    for (int32 i = 1; i < count; ++i)
                    {
                        b2Vec2 v2 = b2Mul(xf, vertices[i]);
                        draw.DrawLine(NeoVec2(v1.x,v1.y),NeoVec2(v2.x,v2.y),NeoColor(1,1,1));
                        draw.DrawCircle(NeoVec2(v1.x,v1.y),0.01,NeoColor(1,1,1));
                         v1 = v2;
                    }
                }
                break;
                case b2Shape::e_polygon:
                {
                    b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
                    int32 vertexCount = poly->m_vertexCount;
                    b2Assert(vertexCount <= b2_maxPolygonVertices);
                    b2Vec2 vertices[b2_maxPolygonVertices];
                    NeoVec2 v[b2_maxPolygonVertices];

                    for (int32 i = 0; i < vertexCount; ++i)
                    {
                    vertices[i] = b2Mul(xf, poly->m_vertices[i]);
                    v[i] = NeoVec2(vertices[i].x,vertices[i].y);
                    }
                    draw.DrawSolidPolygon(v,vertexCount,NeoColor(1,1,1));
                }
                break;
                default:
                break;
            }
        }
    }

}
void display()
{
    //glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    int32 bodyCount = mybox2d.m_world->GetBodyCount();
    float32 timeStep = 1.0f / 60.0f;
    int32 velocityIterations = 6;
    int32 positionIterations = 2;
    mybox2d.m_world->Step(timeStep, velocityIterations, positionIterations);
    drawWholeBody(mybox2d.m_world, mybox2d.m_bodies);
    glPopMatrix();
    glutSwapBuffers();
    glFlush();
}
void Timer(int)
{
 glutSetWindow(mainWindow);
    glutPostRedisplay(); //要求重畫視窗
 glutTimerFunc(framePeriod, Timer, 0); //Do Repeat
}
int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
 glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
 glutInitWindowSize(winWidth, winHeight);
    mainWindow = glutCreateWindow("Neo Box2D");
 glutDisplayFunc(display);
    GLUI_Master.set_glutReshapeFunc(Resize);
 GLUI_Master.set_glutSpecialFunc(KeyboardSpecial);
    GLUI_Master.set_glutKeyboardFunc(Keyboard);
 GLUI_Master.set_glutMouseFunc(Mouse);
 glutMouseWheelFunc(MouseWheel);
    glutMotionFunc(MouseMotion);

 glutTimerFunc(framePeriod, Timer, 0);
 //glui->set_main_gfx_window( mainWindow );
 glutMainLoop();
 return 0;
}

myBox2d.h
#ifndef MYBOX2D_H
#define MYBOX2D_H
#include <Box2D/Box2D.h>
class MyBox2D : public b2ContactListener
{
public:
    b2World* m_world;
    b2Body* m_groundBody;
    b2Body* m_bodies[4];
 b2Joint* m_joints[8];
    MyBox2D()
    {
b2Vec2 gravity(0.0f, -10.0f);
bool doSleep = true;
m_world = new b2World(gravity, doSleep);

//宣告static物體定義
b2BodyDef staticBodyDef;
staticBodyDef.type = b2_staticBody;
//宣告dynamic物體定義
b2BodyDef dynamicBodyDef;
dynamicBodyDef.type = b2_dynamicBody;

//註冊地面(先新增shape,再利用BodyDef給出location)
//shape
b2EdgeShape groundShape;
groundShape.Set(b2Vec2(-50,0), b2Vec2(50,0));
//材質
b2FixtureDef groundFixtureDef;
groundFixtureDef.shape = &groundShape;
groundFixtureDef.density = 1.0f;
groundFixtureDef.friction = 1.0f;
//location
staticBodyDef.position.Set(0, -20);
m_groundBody = m_world->CreateBody(&staticBodyDef);
m_groundBody->CreateFixture(&groundFixtureDef);
m_bodies[0] = m_groundBody;

//球shape
b2CircleShape dynamicCircle;
dynamicCircle.m_p.Set(0.0f, 0.0f);
dynamicCircle.m_radius = 3.0f;
//location
dynamicBodyDef.position.Set(2, 20);
m_bodies[1] = m_world->CreateBody(&dynamicBodyDef);
m_bodies[1]->CreateFixture(&dynamicCircle,1.0f);


b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(2, 2);
dynamicBodyDef.position.Set(0.0f, 10.0f);
m_bodies[2] = m_world->CreateBody(&dynamicBodyDef);
m_bodies[2]->CreateFixture(&dynamicBox, 1.0f);

/*
b2Vec2 vs[4];
vs[0].Set(0.7f, 0.0f);
vs[1].Set(1.0f, 0.02);
vs[2].Set(0.0f, 0.0f);
vs[3].Set(-0.7f, 0.4f);
b2ChainShape chain;
chain.CreateChain(vs, 4);
bodyDef.position.Set(0.0f, 0.0f);
m_bodies[4] = m_world->CreateBody(&bodyDef);
m_bodies[4]->CreateFixture(&chain, 0.01f);
*/
    }
 virtual ~MyBox2D()
 {
     delete m_world;
        m_world = NULL;
 }
};
#endif


gluiDraw.h
#ifndef GLUIDRAW_H
#define GLUIDRAW_H
#include <math.h>
#include <glui/GL/glui.h>
#define PI 3.141592653
const float deg2Rad = PI / 180.;
const float rad2Deg = 180. / PI;

struct NeoColor
{
    float r, g, b;
    NeoColor(){}
    NeoColor(float r_,float g_,float b_) : r(r_), g(g_), b(b_){}
    void Set(float r_,float g_,float b_) {r = r_; g = g_; b = b_;}
};
struct NeoVec2
{
    float x, y;
    NeoVec2(){}
    NeoVec2(float x_,float y_) : x(x_), y(y_){}
    void Set(float x_,float y_) {x = x_; y = y_;}
};
inline NeoVec2 operator + (const NeoVec2 &v1, const NeoVec2 &v2)
{
    return NeoVec2(v1.x + v2.x, v1.y + v2.y);
}
inline NeoVec2 operator * (float a, const NeoVec2 &v)
{
    return NeoVec2(v.x * a, v.y * a);
}

class GluiDraw
{
public:
    GluiDraw(){}
    ~GluiDraw(){}
    void DrawLine(const NeoVec2 &v1,const NeoVec2 &v2,const NeoColor &color)
    {
        glBegin(GL_LINES);
        glColor3f(color.r,color.g,color.b);
        glVertex2f(v1.x,v1.y);
        glVertex2f(v2.x,v2.y);
        glEnd();
    }
    void DrawCircle(const NeoVec2 ¢er, const float radius, const NeoColor &color)
    {
        const float segments = 16.;
        const float inc = 2 * PI / 16.;
        float theta = 0;
        glBegin(GL_LINE_LOOP);
        glColor3f(color.r,color.g,color.b);
        for (int i=0;i < segments;++i)
        {
            NeoVec2 real_v = center + radius * NeoVec2(cosf(theta),sinf(theta));
            glVertex2f(real_v.x,real_v.y);
            theta += inc;
        }
        glEnd();
    }
     void DrawSolidCircle(const NeoVec2 ¢er, const float radius,const NeoVec2 &axis, const NeoColor &color)
    {
        const float segments = 16.;
        const float inc = 2 * PI / 16.;
        float theta = 0;
        glBegin(GL_LINE_LOOP);
        glColor3f(color.r,color.g,color.b);
        for (int i=0;i < segments;++i)
        {
            NeoVec2 real_v = center + radius * NeoVec2(cosf(theta),sinf(theta));
            glVertex2f(real_v.x,real_v.y);
            theta += inc;
        }
        glEnd();
        DrawLine(center,center + (radius * axis),color);
    }
    void DrawPolygon(const NeoVec2* vertices, int vertexCount, const NeoColor& color)
    {
        glColor3f(color.r, color.g, color.b);
        glBegin(GL_LINE_LOOP);
        for (int i = 0; i < vertexCount; ++i)
        {
            glVertex2f(vertices[i].x, vertices[i].y);
        }
        glEnd();
    }
    void DrawSolidPolygon(const NeoVec2* vertices,  int vertexCount, const NeoColor& color)
    {
        glEnable(GL_BLEND);
        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glColor4f(0.5f * color.r, 0.5f * color.g, 0.5f * color.b, 0.5f);
        glBegin(GL_TRIANGLE_FAN);
        for (int i = 0; i < vertexCount; ++i)
        {
            glVertex2f(vertices[i].x, vertices[i].y);
        }
        glEnd();
        glDisable(GL_BLEND);

        glColor4f(color.r, color.g, color.b, 1.0f);
        glBegin(GL_LINE_LOOP);
        for (int i = 0; i < vertexCount; ++i)
        {
            glVertex2f(vertices[i].x, vertices[i].y);
        }
        glEnd();
    }
    void DrawBox(const NeoVec2 ¢er,const float half_width,const float half_height, const NeoColor& color)
    {
        NeoVec2 list[4] = {
        NeoVec2(center.x-(half_width),center.y-(half_height)),
        NeoVec2(center.x+(half_width),center.y-(half_height)),
        NeoVec2(center.x+(half_width),center.y+(half_height)),
        NeoVec2(center.x-(half_width),center.y+(half_height))
        };
        DrawSolidPolygon(list, 4, color);
    }
};
#endif

2012年7月22日 星期日

GTK+2.0


CB的global compiler settings -> compiler settings -> Other options 填-mms-bitfields

include:
$(CODEBLOCKS)\build\gtk\include\gtk-2.0
$(CODEBLOCKS)\build\gtk\include\glib-2.0
$(CODEBLOCKS)\build\gtk\include\cairo
$(CODEBLOCKS)\build\gtk\include\pango-1.0
$(CODEBLOCKS)\build\gtk\include\atk-1.0

link目錄
$(CODEBLOCKS)\build\gtk\lib

link libraries加入
gdk-win32-2.0
gtk-win32-2.0
atk-1.0
gdk_pixbuf-2.0
pangowin32-1.0
gdi32
pangocairo-1.0
pango-1.0
cairo
gobject-2.0
gmodule-2.0
glib-2.0
intl

main.cpp
#include <gtk/gtk.h>
//#include <stdio.h>
#include <stdlib.h>

static GdkPixmap *pixmap = NULL;
/* 創建一個適當大小的後端位圖 */
static gboolean configure_event( GtkWidget         *widget, GdkEventConfigure *event )
{
  if (pixmap) g_object_unref (pixmap);
  pixmap = gdk_pixmap_new (widget->window, widget->allocation.width, widget->allocation.height, -1);
  gdk_draw_rectangle (pixmap, widget->style->white_gc, TRUE, 0, 0, widget->allocation.width, widget->allocation.height);
  return TRUE;
}
/*  從後端位圖重新繪製螢幕 */
static gboolean expose_event(GtkWidget *widget,GdkEventExpose *event )
{
  gdk_draw_drawable (widget->window, widget->style->fg_gc[GTK_WIDGET_STATE (widget)],pixmap,event->area.x, event->area.y,event->area.x, event->area.y,event->area.width, event->area.height);
  return FALSE;
}
/* 在螢幕上繪製一個矩形 */
static void draw_brush( GtkWidget *widget, gdouble    x,gdouble    y)
{
  GdkRectangle update_rect;
  update_rect.x = x - 5;
  update_rect.y = y - 5;
  update_rect.width = 10;
  update_rect.height = 10;
  gdk_draw_rectangle (pixmap,widget->style->black_gc,TRUE,update_rect.x, update_rect.y,update_rect.width, update_rect.height);
  gtk_widget_queue_draw_area (widget, update_rect.x, update_rect.y, update_rect.width, update_rect.height);
}

static gboolean button_press_event(GtkWidget *widget, GdkEventButton *event )
{
  if (event->button == 1 && pixmap != NULL)
    draw_brush(widget, event->x, event->y);
  return TRUE;
}

static gboolean motion_notify_event( GtkWidget *widget, GdkEventMotion *event )
{
  int x, y;
  GdkModifierType state;
  if (event->is_hint)
    gdk_window_get_pointer (event->window, &x, &y, &state);
  else
    {
      x = event->x;
      y = event->y;
      state =(GdkModifierType) event->state;
    }
  if (state & GDK_BUTTON1_MASK && pixmap != NULL)
    draw_brush (widget, x, y);
  return TRUE;
}

gint processDelete_event(GtkWidget *widget, GdkEvent  *event, gpointer   data)
{
g_print ("delete event occurred\n");
return FALSE;
}
static void processButton( GtkWidget *widget, gpointer data)
{
    g_print ("Hello again - %s was pressed\n", (gchar *) data);
    if (!g_strcmp0((gchar *)data ,"button 2"))
    {
        system("dir");
    }
}

void precessDestroy(GtkWidget *widget, gpointer data )
{
   gtk_main_quit();
}
int main(int argc, char* argv[])
{
    GtkWidget* window;
    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_container_set_border_width(GTK_CONTAINER (window), 100);
    gtk_window_set_position (GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    g_signal_connect(window, "delete_event", G_CALLBACK(processDelete_event), NULL);
    g_signal_connect(window, "destroy", G_CALLBACK(precessDestroy), NULL);
    gtk_window_set_title(GTK_WINDOW(window), "哈囉!GTK+!");
   //------------------------------------------------------
    GtkWidget *vbox = gtk_vbox_new(FALSE, 20);
    gtk_container_add (GTK_CONTAINER(window), vbox);
    gtk_widget_show (vbox);
    GtkWidget *label = gtk_label_new ("底下是塗鴉牆");
    gtk_box_pack_start (GTK_BOX(vbox), label, FALSE, FALSE, 0);
    gtk_widget_show (label);
    GtkWidget *button = gtk_button_new_with_label("Exit");
    gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 0);
    g_signal_connect_swapped(button, "clicked", G_CALLBACK(gtk_widget_destroy), window);
    gtk_widget_show (button);
    //------------------------------------------------
    GtkWidget *hbox = gtk_hbox_new (TRUE, 30);
    gtk_box_pack_end (GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
    gtk_widget_show (hbox);
    button = gtk_button_new_with_label("Button1");
    gtk_box_pack_start(GTK_BOX(hbox), button, TRUE, TRUE, 0);
    g_signal_connect(button, "clicked",G_CALLBACK (processButton), (gpointer)"button 1");
    gtk_widget_show (button);
    button = gtk_button_new_with_label("Button2-Do DIR");
    gtk_box_pack_end(GTK_BOX(hbox), button, TRUE, TRUE, 0);
    g_signal_connect(button, "clicked",G_CALLBACK (processButton), (gpointer)"button 2");
    gtk_widget_show (button);
    //-------------------------------------------------
    GtkWidget *drawing_area = gtk_drawing_area_new ();
    gtk_widget_set_size_request (GTK_WIDGET(drawing_area), 200, 200);
    gtk_box_pack_start (GTK_BOX(vbox), drawing_area, TRUE, TRUE, 0);
    g_signal_connect (drawing_area, "expose_event",G_CALLBACK(expose_event), NULL);
    g_signal_connect (drawing_area,"configure_event",G_CALLBACK (configure_event), NULL);
/* 事件信號 */
    g_signal_connect (drawing_area, "motion_notify_event",G_CALLBACK(motion_notify_event), NULL);
    g_signal_connect (drawing_area, "button_press_event",G_CALLBACK (button_press_event), NULL);
    gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK| GDK_LEAVE_NOTIFY_MASK| GDK_BUTTON_PRESS_MASK| GDK_POINTER_MOTION_MASK| GDK_POINTER_MOTION_HINT_MASK);
    gtk_widget_show (drawing_area);

    gtk_widget_show(window);
    gtk_main();
    return 0;
}

GLUI


CB的global compiler settings -> compiler settings -> Other options 填-fexceptions
#defines填FREEGLUT_STATIC

link libraries加入libFreeGLUT.a libGLUI.a GlU32(GlU32.Lib) Gdi32(Gdi32.Lib) OpenGL32(OpenGL32.Lib) User32(User32.Lib) WinMM(WinMM.Lib)

main.cpp
//#define GLUT_DISABLE_ATEXIT_HACK //出ATEXIT_HACK錯要加
#include "iostream"
#include "math.h"
#include "glui/GL/glui.h"
#define PI 3.141592653
const float deg2Rad = PI / 180.;
const float rad2Deg = 180. / PI;

using namespace std;
//------------------------------------------------------------------------
struct neoColor
{
    float r, g, b;
 neoColor() {}
 neoColor(float r, float g, float b) : r(r), g(g), b(b) {}
 void Set(float ri, float gi, float bi) { r = ri; g = gi; b = bi; }
};
struct neoVec2
{
 float x, y;
 /// Default constructor does nothing (for performance).
 neoVec2() {}
 /// Construct using coordinates.
 neoVec2(float x, float y) : x(x), y(y) {}
 /// Set this vector to all zeros.
 void SetZero() { x = 0.0f; y = 0.0f; }
 /// Set this vector to some specified coordinates.
 void Set(float x_, float y_) { x = x_; y = y_; }
 /// Negate this vector.
 neoVec2 operator -() const { neoVec2 v; v.Set(-x, -y); return v; }
 /// Read from and indexed element.
 float operator () (int i) const
 {
  return (&x)[i];
 }

 /// Write to an indexed element.
 float& operator () (int i)
 {
  return (&x)[i];
 }
 /// Add a vector to this vector.
 void operator += (const neoVec2& v)
 {
  x += v.x; y += v.y;
 }
 /// Subtract a vector from this vector.
 void operator -= (const neoVec2& v)
 {
  x -= v.x; y -= v.y;
 }
 /// Multiply this vector by a scalar.
 void operator *= (float a)
 {
  x *= a; y *= a;
 }
 /*
 neoVec2 operator * (float a)
 {
  return neoVec2(x *= a, y *= a);
 }
 */
 /// Get the length of this vector (the norm).
 float Length() const
 {
  return sqrt(x * x + y * y);
 }
 /// Get the length squared. For performance, use this instead of
 /// b2Vec2::Length (if possible).
 float LengthSquared() const
 {
  return x * x + y * y;
 }
 /// Convert this vector into a unit vector. Returns the length.
 float Normalize()
 {
  float length = Length();
  float invLength = 1.0f / length;
  x *= invLength;
  y *= invLength;
  return length;
 }
 /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other)
 neoVec2 Skew() const
 {
  return neoVec2(-y, x);
 }
};
    inline neoVec2 operator + (const neoVec2& a, const neoVec2& b)
    {
        return neoVec2(a.x + b.x, a.y + b.y);
    }
    inline neoVec2 operator - (const neoVec2& a, const neoVec2& b)
    {
        return neoVec2(a.x - b.x, a.y - b.y);
    }
    inline neoVec2 operator * (float s, const neoVec2& a)
    {
        return neoVec2(s * a.x, s * a.y);
    }
    inline bool operator == (const neoVec2& a, const neoVec2& b)
    {
        return a.x == b.x && a.y == b.y;
    }




struct neoVec3
{
    float x, y, z;
 /// Default constructor does nothing (for performance).
 neoVec3() {}
 /// Construct using coordinates.
 neoVec3(float x, float y, float z) : x(x), y(y), z(z) {}

 /// Set this vector to all zeros.
 void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }

 /// Set this vector to some specified coordinates.
 void Set(float x_, float y_, float z_) { x = x_; y = y_; z = z_; }

 /// Negate this vector.
 neoVec3 operator -() const {neoVec3 v; v.Set(-x, -y, -z); return v; }

 /// Add a vector to this vector.
 void operator += (const neoVec3& v)
 {
  x += v.x; y += v.y; z += v.z;
 }

 /// Subtract a vector from this vector.
 void operator -= (const neoVec3& v)
 {
  x -= v.x; y -= v.y; z -= v.z;
 }

 /// Multiply this vector by a scalar.
 void operator *= (float s)
 {
  x *= s; y *= s; z *= s;
 }
};
//--------------------------------------------------------------------------------
namespace
{
int mainWindow;
GLint winWidth = 640;
GLint winHeight = 640;
GLUI *glui;
int listboxindx = 0;
int spinnerintegervar = 0;
int checkbox = false; //1=>checked 0=>cancle
float spinnerfloatvar;
neoVec2 mp,pre_mp;
int angToY=0, angToX=0;
bool isMouseRightPressed = false;
bool isMouseLeftPressed = false;

}
//-----------------------------------------------------------------------------
void Keyboard(unsigned char key, int x, int y)
{
switch (key)
 {
 case 27:
     exit(0);
  break;
    default:
        break;
 }
}
void KeyboardSpecial(int key, int x, int y)
{
    switch (key)
 {
 case GLUT_ACTIVE_SHIFT:
        break;
 case GLUT_KEY_LEFT:
        cout << checkbox << "," << listboxindx << endl;
  break;
 case GLUT_KEY_RIGHT:
  break;
 case GLUT_KEY_DOWN:
  break;
 case GLUT_KEY_UP:
  break;
 case GLUT_KEY_HOME:
  break;
 }
}
void Resize(int newWidth, int newHeight)
{
   glViewport(0, 0,(GLsizei) newWidth,(GLsizei) newHeight);
   winWidth  = newWidth;
   winHeight = newHeight;
   glClear(GL_COLOR_BUFFER_BIT);
}
void Mouse(int button, int state, int x, int y)
{
 // Use the mouse to move things around.
 if (button == GLUT_LEFT_BUTTON)
 {
  int specialKey  = glutGetModifiers();
  if (state == GLUT_DOWN)
  {
   if (specialKey  == GLUT_ACTIVE_SHIFT)
   {
                 cout << "GLUT_LEFT_BUTTON click with SHIFT" << endl;
   }
   else
   {
                 cout << "GLUT_LEFT_BUTTON click" << endl;
   }
  }

  if (state == GLUT_UP)
  {
                cout << "GLUT_LEFT_BUTTON release" << endl;
  }
 }
 else if (button == GLUT_RIGHT_BUTTON)
 {
  if (state == GLUT_DOWN)
  {
      isMouseRightPressed = true;
            cout << "GLUT_RIGHT_BUTTON click" << endl;
  }

  if (state == GLUT_UP)
  {
      isMouseRightPressed = false;
            cout << "GLUT_RIGHT_BUTTON release" << endl;
  }
 }
}
void MouseWheel(int wheel, int direction, int x, int y)
{
 if (direction > 0)
 {
   cout << "wheel in" << endl;
 }
 else
 {
   cout << "wheel out" << endl;
 }
}
void MouseMotion(int x, int y)
{
    if(isMouseRightPressed)
    {
        int distanceX = x - pre_mp.x;
        int distanceY = y - pre_mp.y;
        pre_mp.Set(x,y);
        angToY += distanceX;
        angToX += distanceY;
        glutPostRedisplay(); //要求重畫視窗
    }
    cout << "Mouse clicked and x=" << mp.x << ",y=" << mp.y << endl;
}
//glutPassiveMotionFunc(int x,int y);
//glutEntryFunc(processMouseEntryWindow);
void Exit(int code)
{
#ifndef __APPLE__
 glutLeaveMainLoop();
#endif
 exit(code);
}
void Timer(int)
{
    cout << "time up!" << endl;
 glutSetWindow(mainWindow);
    glutPostRedisplay(); //要求重畫視窗
 glutTimerFunc(16, Timer, 0); //Do Repeat
}
void DrawPoint(const neoVec2& p, float size, const neoColor& color)
{
    glPointSize(size);
    glBegin(GL_POINTS);
 glColor3f(color.r, color.g, color.b);
 glVertex2f(p.x, p.y);
    glEnd();
 glPointSize(1.0f);
}
void DrawCircle(const neoVec2& center, float radius, const neoColor& color)
{
 const float k_segments = 16.0f;
 const float k_increment = 2.0f * PI / k_segments;
 float theta = 0.0f;
 glColor3f(color.r, color.g, color.b);
 glBegin(GL_LINE_LOOP);
 for (int i = 0; i < k_segments; ++i)
 {
     neoVec2 v = center +  radius * neoVec2(cosf(theta), sinf(theta)) ;
  glVertex2f(v.x, v.y);
  theta += k_increment;
 }
 glEnd();
}

void DrawSegment(const neoVec2& p1, const neoVec2& p2, const neoColor& color,  bool realline)
{
     if (!realline)
    {
        glLineStipple (1, 0x1C47);
        glEnable(GL_LINE_STIPPLE);
    }
    glBegin(GL_LINES);
 glColor3f(color.r, color.g, color.b);
 glVertex2f(p1.x, p1.y);
 glVertex2f(p2.x, p2.y);
 glEnd();
 if (!realline) glDisable(GL_LINE_STIPPLE);
}
void DrawPolygon(const neoVec2* vertices, int vertexCount, const neoColor& color)
{
 glColor3f(color.r, color.g, color.b);
 glBegin(GL_LINE_LOOP);
 for (int i = 0; i < vertexCount; ++i)
 {
  glVertex2f(vertices[i].x, vertices[i].y);
 }
 glEnd();
}
void DrawString(int x, int y, const char *string, ...)
{
 char buffer[128];

 va_list arg;
 va_start(arg, string);
 vsprintf(buffer, string, arg);
 va_end(arg);

 glMatrixMode(GL_PROJECTION);
 glPushMatrix();
 glLoadIdentity();
 int w = glutGet(GLUT_WINDOW_WIDTH);
 int h = glutGet(GLUT_WINDOW_HEIGHT);
 gluOrtho2D(0, w, h, 0);
 glMatrixMode(GL_MODELVIEW);
 glPushMatrix();
 glLoadIdentity();

 glColor3f(0.9f, 0.6f, 0.6f);
 glRasterPos2i(x, y);
 int length = (int)strlen(buffer);
 for (int i = 0; i < length; ++i)
 {
  glutBitmapCharacter(GLUT_BITMAP_8_BY_13, buffer[i]);
 }

 glPopMatrix();
 glMatrixMode(GL_PROJECTION);
 glPopMatrix();
 glMatrixMode(GL_MODELVIEW);
}

void display()
{
    //glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glRotatef(angToX, 1.0, 0.0, 0.0);
    glRotatef(angToY, 0.0, 1.0, 0.0);
//---------------------------------------------------------------------
DrawSegment(neoVec2(0,0),neoVec2(0.1,0.1),neoColor(0.5,1,1),false);
DrawPoint(neoVec2(0,0),5,neoColor(1,1,1));
DrawPoint(neoVec2(0.1,0.1),5,neoColor(1,0,1));
DrawCircle(neoVec2(0,0),0.1,neoColor(1,1,1));
neoVec2 list[3] = {neoVec2(0,0), neoVec2(-0.1,0.1), neoVec2(-0.1,0)};
DrawPolygon(list,3,neoColor(0.5,1,1));
DrawString(100,200,"abc");
//---------------------------------------------------------------------
    glPopMatrix();
    glutSwapBuffers();
    glFlush();
}
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
 glutInitWindowSize(winWidth, winHeight);
    glutInitWindowPosition(200, 50);
    gluOrtho2D(0, winWidth,winHeight, 0);
    mainWindow = glutCreateWindow( "Neo Glui" );
    glClearColor(0.0, 0.0, 0.0, 0.0); //指定填視窗背景的顏色
    glViewport(0, 0, (GLsizei) winWidth, (GLsizei) winHeight);
    glutDisplayFunc(display);
    GLUI_Master.set_glutReshapeFunc(Resize);
 GLUI_Master.set_glutKeyboardFunc(Keyboard);
 GLUI_Master.set_glutSpecialFunc(KeyboardSpecial);
    GLUI_Master.set_glutMouseFunc(Mouse);
    glutMouseWheelFunc(MouseWheel);
    glutMotionFunc(MouseMotion);
    //------------------------------------------------
    glui = GLUI_Master.create_glui_subwindow(mainWindow, GLUI_SUBWINDOW_RIGHT );
 glui->add_statictext("Text");
 GLUI_Listbox* selectbox = glui->add_listbox("", &listboxindx);
 selectbox->add_item(0, "One");
 selectbox->add_item(1, "Two");
 selectbox->add_item(2, "Three");

 GLUI_Spinner* spinnerinteger = glui->add_spinner("spin1", GLUI_SPINNER_INT, &spinnerintegervar);
 spinnerinteger->set_int_limits(1,10);
    GLUI_Spinner* spinnerfloat = glui->add_spinner("spin2", GLUI_SPINNER_FLOAT, &spinnerfloatvar);
 spinnerfloat->set_float_limits(5.0f, 10.0f);

    glui->add_checkbox("checkbox", &checkbox);
  glui->add_separator();
    GLUI_Panel* panel = glui->add_panel("panel");
    glui->add_checkbox_to_panel(panel,"Panel checkbox",&checkbox);
 glui->add_separator();
 glui->add_button("Exit", 0, (GLUI_Update_CB)Exit);
 glui->set_main_gfx_window( mainWindow );
    glutTimerFunc(16, Timer, 0);

    glutMainLoop();
    cout << "中文!" << endl;
    return 0;

2012年7月21日 星期六

Lua with c++

main.cpp


extern "C"{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#define err_return(num,fmt,args...) do{printf("[%s:%d]"fmt"\n",__FILE__,__LINE__,##args);return(num);} while(0)
#define err_exit(num,fmt,args...) do{printf("[%s:%d]"fmt"\n",__FILE__,__LINE__,##args);exit(num);} while(0)

using namespace std;
int csum(lua_State* l)
{
    int a = lua_tointeger(l,1) ;
    int b = lua_tointeger(l,2) ;
    lua_pushinteger(l,a+b) ;
    return 1 ;
}
int main()
{
    lua_State* luaState = luaL_newstate() ;        //創建lua運行環境
    if (luaState == NULL) err_return(-1,"luaL_newstat() failed");
    int ret = 0 ;
    ret = luaL_loadfile(luaState,"func.lua") ;      //加載lua腳本文件
    if (ret != 0) err_return(-1,"luaL_loadfile failed") ;
    ret = lua_pcall(luaState,0,0,0) ;
    if (ret != 0) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    //----------------------------------------------------------------------------------------
    lua_getglobal(luaState,"width");  //-2           //獲取lua中定義的變量
    lua_getglobal(luaState,"height"); //-1
    printf("height:%ld width:%ld\n",lua_tointeger(luaState,-1),lua_tointeger(luaState,-2)) ;
    lua_pop(luaState,1) ; //恢復lua的棧
    //----------------------------------------------------------------------------------------
    int a = 11 ;
    int b = 12 ;
    lua_getglobal(luaState,"sub");               //調用lua中的函數sub
    lua_pushinteger(luaState,a) ;
    lua_pushinteger(luaState,b) ;
    ret = lua_pcall(luaState,2,1,0) ;  //a-b
     if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    printf("sum:%d - %d = %ld\n",a,b,lua_tointeger(luaState,-1)) ;
    lua_pop(luaState,1) ;
    //----------------------------------------------------------------------------------------
     const char str1[] = "hello" ;
    const char str2[] = "world" ;
    lua_getglobal(luaState,"mystrcat");          //調用lua中的函數mystrcat
    lua_pushstring(luaState,str1) ;
    lua_pushstring(luaState,str2) ;
    ret = lua_pcall(luaState,2,1,0) ;
    if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    printf("mystrcat:%s%s = %s\n",str1,str2,lua_tostring(luaState,-1)) ;
    lua_pop(luaState,1) ;
    //----------------------------------------------------------------------------------------
    lua_pushcfunction(luaState,csum) ;         //註冊在lua中使用的c函數
    lua_setglobal(luaState,"csum") ;           //綁定到lua中的名字csum
    lua_getglobal(luaState,"mysum");           //調用lua中的mysum函數,該函數調用本程序中定義的csum函數實現加法
    lua_pushinteger(luaState,a) ;
    lua_pushinteger(luaState,b) ;
    ret = lua_pcall(luaState,2,1,0) ;
    if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    printf("mysum:%d + %d = %ld\n",a,b,lua_tointeger(luaState,-1)) ;
    lua_pop(luaState,1) ;

    lua_close(luaState) ;                     //釋放lua運行環境
    return 0 ;
}

func.lua

--變量定義
width=1 ;
height=2 ;
--lua函數定義,實現減法
function sub(a,b)
    return a-b ;
end
--lua函數定義,實現字符串相加
function mystrcat(a,b)
    return a..b ;
end
--lua函數定義,通過調用c代碼中的csum函數實現加法
function mysum(a,b)
    return csum(a,b) ;
end

2012年7月20日 星期五

NeoOgreApplication

NeoOgreApplicaion.h


#ifndef _NEO_OGRE_APPLICATION_H_
#define _NEO_OGRE_APPLICATION_H_
#include "Ogre\Ogre.h"
#include "OIS\OIS.h"
class NeoFrameListener : public Ogre::FrameListener
{
public:
    NeoFrameListener(): _listener(NULL){}
    NeoFrameListener(Ogre::RenderWindow* win, Ogre::Camera* camera, Ogre::SceneNode* node, Ogre::Entity* ent)
    {
        _camMovementSpeed = 50.0f;
        _walkingSpeed = 10.0f;
        _walkingRotation = 0;
        _cam = camera;
        _node = node;
        _ent = ent;
        OIS::ParamList pl;
        unsigned int windowHandle = 0;
        std::ostringstream windowHandleString;
        win->getCustomAttribute("WINDOW",  &windowHandle);
        windowHandleString << windowHandle;
        pl.insert(std::make_pair("WINDOW",  windowHandleString.str()));
        _im = OIS::InputManager::createInputSystem(pl);
        _key = static_cast(_im->createInputObject(OIS::OISKeyboard,false ));
        _mouse = static_cast(_im->createInputObject( OIS::OISMouse, false ));

        _aniState = _ent->getAnimationState("RunBase");
        _aniState->setLoop(false);
        _aniStateTop = _ent->getAnimationState("RunTop");
        _aniStateTop->setLoop(false);
    }
    ~NeoFrameListener()
    {
        delete _listener;
        _im->destroyInputObject(_key);
        _im->destroyInputObject(_mouse);
        OIS::InputManager::destroyInputSystem(_im);
    }
    bool frameStarted(const Ogre::FrameEvent& evt)
    {
        bool walked = false;
        Ogre::Vector3 camTranslate(0,0,0);
        Ogre::Vector3 nodeTranslate(0,0,0);
        _key->capture();
        if(_key->isKeyDown(OIS::KC_ESCAPE))
        {
            return false;
        }
        if(_key->isKeyDown(OIS::KC_1) && !_downKey1)
        {
            _downKey1 = true;
            _comp1 = !_comp1;
            Ogre::CompositorManager::getSingleton().setCompositorEnabled(_cam->getViewport(),"Compositor1",_comp1);
            return true;
        }
         if(!_key->isKeyDown(OIS::KC_1))
        {
            _downKey1 = false;
        }
         if(_key->isKeyDown(OIS::KC_SPACE))
        {

          _isActionKeyPress = true;
          _aniStateTop = _ent->getAnimationState("SliceHorizontal");
          _aniStateTop->setLoop(false);
          _aniStateTop->setTimePosition(0.0f);

        }
        if(_key->isKeyDown(OIS::KC_UP))
        {
            nodeTranslate += Ogre::Vector3(0,0,-1);
            _walkingRotation = 3.14f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_DOWN))
        {
            nodeTranslate += Ogre::Vector3(0,0,1);
            _walkingRotation = 0.0f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_LEFT))
        {
            nodeTranslate += Ogre::Vector3(-1,0,0);
            _walkingRotation = -1.57f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_RIGHT))
        {
            nodeTranslate += Ogre::Vector3(1,0,0);
            _walkingRotation = 1.57f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_W))
        {
            camTranslate += Ogre::Vector3(0,0,-1);
        }
        if(_key->isKeyDown(OIS::KC_S))
        {
            camTranslate += Ogre::Vector3(0,0,1);
        }
        if(_key->isKeyDown(OIS::KC_A))
        {
            camTranslate += Ogre::Vector3(-1,0,0);
        }
        if(_key->isKeyDown(OIS::KC_D))
        {
            camTranslate += Ogre::Vector3(1,0,0);
        }

        if(walked){
             _aniStateTop->setEnabled(true);
             _aniState->setEnabled(true);
             if(_aniState->hasEnded())
            {
                _aniState->setTimePosition(0.0f);
            }
            if(_aniStateTop->hasEnded())
            {
                _aniStateTop->setTimePosition(0.0f);
            }
             _aniState->addTime(evt.timeSinceLastFrame*1);
             _aniStateTop->addTime(evt.timeSinceLastFrame*1);
        }
        else
        {
            if(_isActionKeyPress)
            {
                _aniStateTop->setEnabled(true);
                _aniStateTop->addTime(evt.timeSinceLastFrame*1);
                if(_aniStateTop->hasEnded())
                {
                    _isActionKeyPress = false;
                    _aniStateTop = _ent->getAnimationState("RunTop");
                    _aniStateTop->setLoop(false);
                    _aniStateTop->setTimePosition(0.0f);
                }
            }
            else
            {
                if(!_aniStateTop->hasEnded())
                {
                    _aniStateTop->addTime(evt.timeSinceLastFrame*1);
                }
                 if(!_aniState->hasEnded())
                {
                    _aniState->addTime(evt.timeSinceLastFrame*1);
                }
            }
        }
        _node->translate(nodeTranslate * evt.timeSinceLastFrame * _walkingSpeed);
        _node->resetOrientation();
        _node->yaw(Ogre::Radian(_walkingRotation));

        _cam->moveRelative(camTranslate*evt.timeSinceLastFrame * _camMovementSpeed);
        _mouse->capture();
        float mouseRotX = _mouse->getMouseState().X.rel * evt.timeSinceLastFrame* -1;
        float mouseRotY = _mouse->getMouseState().Y.rel * evt.timeSinceLastFrame * -1;
        _cam->yaw(Ogre::Radian(mouseRotX));
        _cam->pitch(Ogre::Radian(mouseRotY));
        return true;
    }
    bool frameEnded(const Ogre::FrameEvent& evt)
    {
        return true;
    }
    bool frameRenderingQueued(const Ogre::FrameEvent& evt)
    {
        return true;
    }
    float _camMovementSpeed;
    float _walkingSpeed;
    float _walkingRotation;
    Ogre::AnimationState* _aniState;
    Ogre::AnimationState* _aniStateTop;
    NeoFrameListener* _listener;
    OIS::InputManager* _im;
    OIS::Keyboard* _key;
    OIS::Mouse* _mouse;
    Ogre::Camera* _cam;
    Ogre::SceneNode* _node;
    Ogre::Entity* _ent;
    bool _downKey1;
    bool _comp1;
    bool _isActionKeyPress;

};

class NeoOgreApplication
{
public:
     NeoOgreApplication(): mSceneMgr(NULL),mRoot(NULL),mCamera(NULL),mWindow(NULL){}
    ~NeoOgreApplication(){if (mRoot) delete mRoot;}
    void runFirstFrame()
    {
        if(!initinalize())
        {
            exit(-1);
        }
        createCamera();
        loadResources();
        createScene();
        createCompositor();
        createFrameListener();
        runOneFrame();
    }
    void runOneFrame()
    {
          Ogre::WindowEventUtilities::messagePump();
          _keepRunning = mRoot->renderOneFrame();
    }
    bool keepRunning()
    {
        return _keepRunning;
    }
    void run()
    {
        if(!initinalize())
        {
            exit(-1);
        }
        createCamera();
        createCompositor();
        loadResources();
        createScene();
        createFrameListener();
        mRoot->startRendering();
    }
protected:
    void loadGroupResources(void)
    {
        Ogre::ConfigFile cf;
        cf.load("resources.cfg");
        Ogre::ConfigFile::SectionIterator sectionIter = cf.getSectionIterator();
        Ogre::String sectionName, typeName,  dataName;
        while (sectionIter.hasMoreElements())
        {
            sectionName = sectionIter.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap *settings = sectionIter.getNext();
            Ogre::ConfigFile::SettingsMultiMap::iterator i;
            for (i = settings->begin(); i != settings->end(); ++i)
            {
                typeName = i->first;
                dataName = i->second;
                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(dataName,typeName, sectionName);
            }
        }
        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    }
    virtual void loadResources(void)
    {
        //Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./Media/packs/Sinbad.zip","Zip");
        //Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
        loadGroupResources();
    }
    bool initinalize(void)
    {
        //Load Pluging
        /*
        mRoot = new Ogre::Root("plugins.cfg","ogre.cfg","Ogre.log");
        if(!mRoot->showConfigDialog())
            return -1;
        */
        mRoot = new Ogre::Root("","");
        //mRoot->loadPlugin( "RenderSystem_Direct3D9" );
        mRoot->loadPlugin("RenderSystem_GL");
        mRoot->loadPlugin("Plugin_ParticleFX");
        mRoot->loadPlugin("Plugin_CgProgramManager");
       // mRoot->loadPlugin("Plugin_OctreeSceneManager");

        const Ogre::RenderSystemList &render_sys_list = mRoot->getAvailableRenderers();//for 1.7
        Ogre::RenderSystemList::const_iterator it_render_sys( render_sys_list.begin() );//for 1.7
        while ( it_render_sys != render_sys_list.end() )                                //for 1.7
        {
            Ogre::RenderSystem* render_sys = *(it_render_sys++);
            //if(render_sys->getName().find("Direct3D9") != Ogre::String::npos)
            if(render_sys->getName().find("OpenGL") != Ogre::String::npos)
            {
                mRoot->setRenderSystem(render_sys);
                break;
            }
        }
        if(mRoot == NULL)
        {
            delete mRoot;
            return false;
        }

        Ogre::NameValuePairList opts;
        opts["resolution"] = "1024x768";
        opts["Full Screen"] = "Yes";
        opts["vsync"] = "false";
        opts["Colour Depth"] = "2";

        mRoot->initialise(false);//false表示不自動產生視窗,手動產生
        mWindow = mRoot->createRenderWindow("Neo Ogre", 800, 600, false,&opts); //false表非全螢幕模式
        Ogre::RenderSystem* rs = mRoot->getRenderSystemByName("Neo Ogre");

        //mWindow = mRoot->initialise(true,"Neo Ogre");
        mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
        //設定camera和vierport----------------------------------------------------------------------
        mCamera = mSceneMgr->createCamera("MyCamera");
        return true;
    }
    virtual void createCompositor()
    {
        Ogre::CompositorManager::getSingleton().addCompositor(mCamera->getViewport(),"Compositor1");
    }
     virtual void createCamera()
    {
        mCamera->setPosition(Ogre::Vector3(0,0,50));
        mCamera->lookAt(Ogre::Vector3(0,0,0));
        mCamera->setNearClipDistance(5);
        mCamera->setFarClipDistance(10000);
        mCamera->setFOVy(Ogre::Degree(45));
        Ogre::Viewport* vp = mWindow->addViewport(mCamera);
        vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
        mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth())/Ogre::Real(vp->getActualHeight()));
    }
     virtual void createScene()
    {
       mEnt = mSceneMgr->createEntity("NeoEntity","Sinbad.mesh");
       mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("NeoNode");
       mNode->attachObject(mEnt);
    }
    virtual void createFrameListener()
    {
        NeoFrameListener* _listener = new NeoFrameListener(mWindow,mCamera,mNode, mEnt);
        mRoot->addFrameListener(_listener);
    }
protected:
    bool _keepRunning;
    Ogre::Root* mRoot;
    Ogre::SceneManager* mSceneMgr;
    Ogre::Camera* mCamera;
    Ogre::RenderWindow* mWindow;
    Ogre::SceneNode* mNode;
    Ogre::Entity* mEnt;
};
#endif

main.cpp
#include "NeoOgreApplication.h"
class MyOgre : public NeoOgreApplication
{
    void loadResources()
    {
        Ogre::ResourceGroupManager::getSingleton().createResourceGroup( "test" );
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./neoResource/packs/Sinbad.zip","Zip","test");
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./neoResource/resource","FileSystem","test");
        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    }

    void createScene()
    {
       mEnt = mSceneMgr->createEntity("NeoEntity","Sinbad.mesh");
       mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("NeoNode");
       mNode->attachObject(mEnt);
       Ogre::Entity* sword1 = mSceneMgr->createEntity("Sword1","Sword.mesh");
       Ogre::Entity* sword2 = mSceneMgr->createEntity("Sword2","Sword.mesh");
       mEnt->attachObjectToBone("Handle.L",sword1);
       mEnt->attachObjectToBone("Handle.R", sword2);
       Ogre::Plane plane(Ogre::Vector3::UNIT_Y,-5);
       Ogre::MeshManager::getSingleton().createPlane("plane",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,plane,1500,1500,20,20,true,1,5,5,Ogre::Vector3::UNIT_Z);
       Ogre::Entity* ground = mSceneMgr->createEntity("LightPlaneEntity", "plane");
       mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ground);
       ground->setMaterialName("Examples/BeachStones");
       Ogre::Light* light = mSceneMgr->createLight("Light1");
       light->setType(Ogre::Light::LT_DIRECTIONAL);
       light->setDirection(Ogre::Vector3(1,-1,0));
       mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
    }

};
int main (void)
{
MyOgre a;
//a.run();
a.runFirstFrame();
while(a.keepRunning())
{
    a.runOneFrame();
}
return 0;
}

Ogre Two Viewport


main.cpp
#include "Ogre\ExampleApplication.h"
class Example : public ExampleApplication
{
public:
      void createScene()
      {
          Ogre::SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode();
          Ogre::Entity* ent = mSceneMgr->createEntity("Sinbad.mesh");
          node->attachObject(ent);
      }
      void createCamera()
      {
        mCamera = mSceneMgr->createCamera("MyCamera1");
        mCamera->setPosition(0,10,20);
        mCamera->lookAt(0,0,0);
        mCamera->setNearClipDistance(5);
        mCamera2 = mSceneMgr->createCamera("MyCamera2");
        mCamera2->setPosition(20,10,0);
        mCamera2->lookAt(0,0,0);
        mCamera2->setNearClipDistance(5);
      }
      void createViewports()
    {
        Ogre::Viewport* vp1 = mWindow->addViewport(mCamera,0,0.0,0.0,0.5,1.0);
        vp1->setBackgroundColour(ColourValue(0.0f,0.0f,0.1f));
        Ogre::Viewport* vp2 = mWindow->addViewport(mCamera2,1,0.5,0.0,0.5,1.0);
        vp2->setBackgroundColour(ColourValue(0.0f,0.1f,0.0f));
        mCamera->setAspectRatio(Real(vp1->getActualWidth()) / Real(vp1->getActualHeight()));
        mCamera2->setAspectRatio(Real(vp2->getActualWidth()) / Real(vp2->getActualHeight()));
    }
private:
       Ogre::Camera* mCamera1;
       Ogre::Camera* mCamera2;
};
int main (void)
{
    Example app;
    app.go();
    return 0;
}

Ogre Compositor

main.cpp


#include "Ogre\ExampleApplication.h"
class CompositorListener1 : public Ogre::CompositorInstance::Listener
{
    public:
    CompositorListener1()
    {
      number = 125.0f;
    }
    void notifyMaterialRender(uint32 pass_id, MaterialPtr &mat)
    {
      mat->getBestTechnique()->getPass(pass_id)->getFragmentProgramParameters()->setNamedConstant("numpixels",number);
    }
    void setNumber(float num)
    {
        number = num;
    }
    float getNumber()
    {
        return number;
    }
    private:
    float number;
};

class NeoLastener : public Ogre::FrameListener
{
public:
    NeoLastener(Ogre::RenderWindow* win, CompositorListener1* listener)
    {
       _comListener = listener;
       size_t windowHan = 0;
       std::stringstream windowHanStr;
       win->getCustomAttribute("WINDOW",&windowHan);
       windowHanStr << windowHan;
       OIS::ParamList pl;
       pl.insert(std::make_pair(std::string("WINDOW"), windowHanStr.str()));
       _man = OIS::InputManager::createInputSystem(pl);
       _key = static_cast(_man->createInputObject(OIS::OISKeyboard,false));
    }
    bool frameStarted(const Ogre::FrameEvent &ent)
    {
        _key->capture();
        if(_key->isKeyDown(OIS::KC_SPACE))
        {
            return false;
        }
        if(_key->isKeyDown(OIS::KC_EQUALS))
        {
            float num = _comListener->getNumber();
            num++;
            _comListener->setNumber(num);
            std::cout << num << std::endl;
        }
        if(_key->isKeyDown(OIS::KC_MINUS))
        {
            float num = _comListener->getNumber();
            num--;
            _comListener->setNumber(num);
            std::cout << num << std::endl;
        }
        return true;
    }
private:
    OIS::InputManager* _man;
    OIS::Keyboard* _key;
     CompositorListener1* _comListener;
};
class Example : public ExampleApplication
{
public:
      void createScene()
      {
        Ogre::Entity* ent = mSceneMgr->createEntity("E1","Sinbad.mesh");
        mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent);
        Ogre::CompositorManager::getSingleton().addCompositor(mCamera->getViewport(),"Compositor1");
        Ogre::CompositorManager::getSingleton().setCompositorEnabled(mCamera->getViewport(),"Compositor1",true);
        Ogre::CompositorInstance* comp = Ogre::CompositorManager::getSingleton().getCompositorChain(mCamera->getViewport())->getCompositor("Compositor1");
        CompositorListener1* compListener = new CompositorListener1();
        comp->addListener(compListener);
       Ogre::FrameListener* FrameListener = new NeoLastener(mWindow,compListener);
       mRoot->addFrameListener(FrameListener);
    }

};
int main (void)
{
    Example app;
    app.go();
    return 0;
}


\media\materials\scripts\neo.compositor

compositor Compositor1
{ 
      technique 
        { 
                texture scene target_width target_height PF_R8G8B8 
                target scene 
                { 
                        input previous 
                } 
     
                target_output 
                { 
                        input none 
                        pass render_quad 
                        { 
                                material neo/Comp1
                                input 0 scene 
                        } 
                } 
        } 
} 

\media\materials\scripts\neo.material

fragment_program MyFragmentShader1 cg
{ 
    source neo.cg         
    entry_point MyFragmentShader1       
    profiles ps_1_1    arbfp1 
 default_params                                         
    {                 
      param_named numpixels float 50  
    } 
}

material neo/Comp1
{ 
    technique 
        { 
                pass 
                { 
    fragment_program_ref MyFragmentShader1       
                     { 
                     } 
       texture_unit 
                        { 
                        } 
                } 
        } 
}

\media\materials\programs\neo.cg

void MyFragmentShader1(float2 uv : TEXCOORD0,out float4 color: COLOR,uniform sampler2D texture,  uniform float numpixels)
{  
float num = numpixels; 
float stepsize = 1.0/ num; 
float2 fragment = float2(stepsize * floor(uv.x * num),stepsize *    floor(uv.y * num)); 
color = tex2D(texture, fragment); 
}

meterial還能加vertex

vertex_program MyVertexShader1 cg 
{
    source neo.cg     
    entry_point MyVertexShader1       
    profiles vs_1_1 arbvp1                                           
    default_params                                         
    {                 
        param_named_auto worldViewMatrix worldviewproj_matrix   
 param_named_auto pulseTime time        
    }  
}
material neo/Comp1
{ 
    technique 
        { 
                pass 
                { 
                     fragment_program_ref MyFragmentShader1 
                     { 
                     } 
                    vertex_program_ref MyVertexShader1
                    { 
                    } 
                    texture_unit 
                        { 
                        } 
                } 
        } 
}

cg部分vertex加

void MyVertexShader1( uniform float pulseTime, float4 position : POSITION, out float4 oPosition : POSITION, float2 uv : TEXCOORD0,out float2 oUv : TEXCOORD0,uniform float4x4 worldViewMatrix) 
{ 
       oPosition = mul(worldViewMatrix, position); 
    oUv = uv;
    oPosition.x *= (2+sin(pulseTime)); 
}

灰階合成器neo.cg

void MyFragmentShader1(float2 uv : TEXCOORD0,out float4 color: COLOR,uniform sampler2D texture)
{  
 float4 temp_color = tex2D(texture,uv);  
 float greyvalue = temp_color.r * 0.3 + temp_color.g * 0.59 + temp_color.b * 0.11; 
 color = float4( greyvalue,  greyvalue,greyvalue,0); 
} 

Ogre OIS Keyboard Code Map

KC_UNASSIGNED    = 0x00   
KC_ESCAPE    = 0x01   
KC_1    = 0x02   
KC_2    = 0x03   
KC_3    = 0x04   
KC_4    = 0x05   
KC_5    = 0x06   
KC_6    = 0x07   
KC_7    = 0x08   
KC_8    = 0x09   
KC_9    = 0x0A   
KC_0    = 0x0B   
KC_MINUS    = 0x0C    // - on main keyboard
KC_EQUALS    = 0x0D   
KC_BACK    = 0x0E    // backspace
KC_TAB    = 0x0F   
KC_Q    = 0x10   
KC_W    = 0x11   
KC_E    = 0x12   
KC_R    = 0x13   
KC_T    = 0x14   
KC_Y    = 0x15   
KC_U    = 0x16   
KC_I    = 0x17   
KC_O    = 0x18   
KC_P    = 0x19   
KC_LBRACKET    = 0x1A   
KC_RBRACKET    = 0x1B   
KC_RETURN    = 0x1C    // Enter on main keyboard
KC_LCONTROL    = 0x1D   
KC_A    = 0x1E   
KC_S    = 0x1F   
KC_D    = 0x20   
KC_F    = 0x21   
KC_G    = 0x22   
KC_H    = 0x23   
KC_J    = 0x24   
KC_K    = 0x25   
KC_L    = 0x26   
KC_SEMICOLON    = 0x27   
KC_APOSTROPHE    = 0x28   
KC_GRAVE    = 0x29    // accent
KC_LSHIFT    = 0x2A   
KC_BACKSLASH    = 0x2B   
KC_Z    = 0x2C   
KC_X    = 0x2D   
KC_C    = 0x2E   
KC_V    = 0x2F   
KC_B    = 0x30   
KC_N    = 0x31   
KC_M    = 0x32   
KC_COMMA    = 0x33   
KC_PERIOD    = 0x34    //. on main keyboard
KC_SLASH    = 0x35    // / on main keyboard
KC_RSHIFT    = 0x36   
KC_MULTIPLY    = 0x37    // * on numeric keypad
KC_LMENU    = 0x38    // left Alt
KC_SPACE    = 0x39   
KC_CAPITAL    = 0x3A   
KC_F1    = 0x3B   
KC_F2    = 0x3C   
KC_F3    = 0x3D   
KC_F4    = 0x3E   
KC_F5    = 0x3F   
KC_F6    = 0x40   
KC_F7    = 0x41   
KC_F8    = 0x42   
KC_F9    = 0x43   
KC_F10    = 0x44   
KC_NUMLOCK    = 0x45   
KC_SCROLL    = 0x46    // Scroll Lock
KC_NUMPAD7    = 0x47   
KC_NUMPAD8    = 0x48   
KC_NUMPAD9    = 0x49   
KC_SUBTRACT    = 0x4A    // - on numeric keypad
KC_NUMPAD4    = 0x4B   
KC_NUMPAD5    = 0x4C   
KC_NUMPAD6    = 0x4D   
KC_ADD    = 0x4E    // + on numeric keypad
KC_NUMPAD1    = 0x4F   
KC_NUMPAD2    = 0x50   
KC_NUMPAD3    = 0x51   
KC_NUMPAD0    = 0x52   
KC_DECIMAL    = 0x53    //. on numeric keypad
KC_OEM_102    = 0x56    //<>|on UK/Germany // keyboards
KC_F11    = 0x57   
KC_F12    = 0x58   
KC_F13    = 0x64    // (NEC PC98)
KC_F14    = 0x65    // (NEC PC98)
KC_F15    = 0x66    // (NEC PC98)
KC_KANA    = 0x70    // (Japanese keyboard)
KC_ABNT_C1    = 0x73    // / ? on Portugese (Brazilian) // keyboards
KC_CONVERT    = 0x79    // (Japanese keyboard)
KC_NOCONVERT    = 0x7B    // (Japanese keyboard)
KC_YEN    = 0x7D    // (Japanese keyboard)
KC_ABNT_C2    = 0x7E    // Numpad. on Portugese // (Brazilian) keyboards
KC_NUMPADEQUALS    = 0x8D    // = on numeric keypad // (NEC PC98)
KC_PREVTRACK    = 0x90   
KC_AT    = 0x91    // (NEC PC98)
KC_COLON    = 0x92    // (NEC PC98)
KC_UNDERLINE    = 0x93    // (NEC PC98)
KC_KANJI    = 0x94    // (Japanese keyboard)
KC_STOP    = 0x95    // (NEC PC98)
KC_AX    = 0x96    // (Japan AX)
KC_UNLABELED    = 0x97    // (J3100)
KC_NEXTTRACK    = 0x99    // Next Track
KC_NUMPADENTER    = 0x9C    // Enter on numeric keypad
KC_RCONTROL    = 0x9D   
KC_MUTE    = 0xA0    // Mute
KC_CALCULATOR    = 0xA1    // Calculator
KC_PLAYPAUSE    = 0xA2    // Play/Pause
KC_MEDIASTOP    = 0xA4    // Media Stop
KC_VOLUMEDOWN    = 0xAE    // Volume ?
KC_VOLUMEUP    = 0xB0    // Volume +
KC_WEBHOME    = 0xB2    // Web home
KC_NUMPADCOMMA    = 0xB3    // on numeric keypad // (NEC PC98)
KC_DIVIDE    = 0xB5    // / on numeric keypad
KC_SYSRQ    = 0xB7   
KC_RMENU    = 0xB8    // right Alt
KC_PAUSE    = 0xC5    // Pause
KC_HOME    = 0xC7    // Home on arrow keypad
KC_UP    = 0xC8    // UpArrow on arrow keypad
KC_PGUP    = 0xC9    // PgUp on arrow keypad
KC_LEFT    = 0xCB    // LeftArrow on arrow keypad
KC_RIGHT    = 0xCD    // RightArrow on arrow // keypad
KC_END    = 0xCF    // End on arrow keypad
KC_DOWN    = 0xD0    // DownArrow on arrow // keypad
KC_PGDOWN    = 0xD1    // PgDn on arrow keypad
KC_INSERT    = 0xD2    // Insert on arrow keypad
KC_DELETE    = 0xD3    // Delete on arrow keypad
KC_LWIN    = 0xDB    // Left Windows key
KC_RWIN    = 0xDC    // Right Windows key
KC_APPS    = 0xDD    // AppMenu key
KC_POWER    = 0xDE    // System Power
KC_SLEEP    = 0xDF    // System Sleep
KC_WAKE    = 0xE3    // System Wake
KC_WEBSEARCH    = 0xE5    // Web Search
KC_WEBFAVORITES    = 0xE6    // Web Favorites
KC_WEBREFRESH    = 0xE7    // Web Refresh
KC_WEBSTOP    = 0xE8    // Web Stop
KC_WEBFORWARD    = 0xE9    // Web Forward
KC_WEBBACK    = 0xEA    // Web Back
KC_MYCOMPUTER    = 0xEB    // My Computer
KC_MAIL    = 0xEC    // Mail
KC_MEDIASELECT    = 0xED    // Media Select

2012年7月19日 星期四

Ogre Sinbad Moving

需要加入model資料夾和resource.cfg和plugins.cfg

#include "Ogre\ExampleApplication.h"
class Example25FrameListener : public Ogre::FrameListener
{
    public:
    Example25FrameListener(Ogre::SceneNode* node,Ogre::Entity* ent,RenderWindow* win,Ogre::Camera* cam)
    {
        _node = node;
        _Cam = cam;
        _ent = ent;
        _WalkingSpeed = 50.0f;
        _rotation = 0.0f;
        _isActionKeyPress = false;
        size_t windowHnd = 0;
        std::stringstream windowHndStr;
        win->getCustomAttribute("WINDOW", &windowHnd);
        windowHndStr << windowHnd;
        OIS::ParamList pl;
        pl.insert(std::make_pair(std::string("WINDOW"),windowHndStr.str()));
        _man = OIS::InputManager::createInputSystem( pl );
        _key = static_cast( _man->createInputObject(OIS::OISKeyboard, false ));
        _mouse = static_cast(_man->createInputObject( OIS::OISMouse, false ));
        translate = Ogre::Vector3(0,0,0);

        _aniState = _ent->getAnimationState("RunBase");
        _aniState->setLoop(false);
        _aniStateTop = _ent->getAnimationState("RunTop");
        _aniStateTop->setLoop(false);
     }

    bool frameStarted(const Ogre::FrameEvent    &evt)
    {
        bool walked = false;
        Ogre::Vector3 SinbadTranslate(0,0,0);
        _key->capture();
        if(_key->isKeyDown(OIS::KC_ESCAPE))
        {
            return false;
        }
        if(_key->isKeyDown(OIS::KC_SPACE))
        {
          _isActionKeyPress = true;
          _aniStateTop = _ent->getAnimationState("SliceHorizontal");
          _aniStateTop->setLoop(false);
          _aniStateTop->setTimePosition(0.0f);
        }
        if(_key->isKeyDown(OIS::KC_W))
        {
        }
        if(_key->isKeyDown(OIS::KC_S))
        {
        }
        if(_key->isKeyDown(OIS::KC_A))
        {
        }
        if(_key->isKeyDown(OIS::KC_D))
        {
        }
        if(_key->isKeyDown(OIS::KC_UP))
        {
            SinbadTranslate += Ogre::Vector3(0,0,-1);
            _rotation = 3.14f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_DOWN))
        {
            SinbadTranslate += Ogre::Vector3(0,0,1);
            _rotation = 0.0f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_LEFT))
        {
            SinbadTranslate += Ogre::Vector3(-1,0,0);
            _rotation = -1.57f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_RIGHT))
        {
            SinbadTranslate += Ogre::Vector3(1,0,0);
            _rotation = 1.57f;
            walked = true;
        }

        if(walked)
        {
            _aniState->setEnabled(true);
            _aniStateTop->setEnabled(true);
            if(_aniState->hasEnded())
            {
                _aniState->setTimePosition(0.0f);
            }
            if(_aniStateTop->hasEnded())
            {
                _aniStateTop->setTimePosition(0.0f);
            }
        }
        else
        {
            if(_isActionKeyPress)
            {
                _aniStateTop->setEnabled(true);
                if(_aniStateTop->hasEnded())
                {
                    _isActionKeyPress = false;
                    _aniStateTop = _ent->getAnimationState("RunTop");
                    _aniStateTop->setLoop(false);
                    _aniStateTop->setTimePosition(0.0f);
                    _aniStateTop->setEnabled(false);
                }
            }
            else
            {
                _aniState->setTimePosition(0.0f);
                _aniState->setEnabled(false);
                _aniStateTop->setTimePosition(0.0f);
                _aniStateTop->setEnabled(false);
            }
        }
        _mouse->capture();
        float rotX = _mouse->getMouseState().X.rel * evt.timeSinceLastFrame* -1;
        float rotY = _mouse->getMouseState().Y.rel * evt.timeSinceLastFrame * -1;
        _node->translate(SinbadTranslate * evt.timeSinceLastFrame * _WalkingSpeed);
        _node->resetOrientation();
        _node->yaw(Ogre::Radian(_rotation));

        _Cam->yaw(Ogre::Radian(rotX));
        _Cam->pitch(Ogre::Radian(rotY));
        _Cam->moveRelative(translate*evt.timeSinceLastFrame * 10);

        _aniState->addTime(evt.timeSinceLastFrame*1);
        _aniStateTop->addTime(evt.timeSinceLastFrame*0.4);
        return true;
    }

    Example25FrameListener()
    {
        FrameListener = NULL;
    }
    ~Example25FrameListener()
    {
        _man->destroyInputObject(_key);
        OIS::InputManager::destroyInputSystem(_man);
        _man->destroyInputObject(_mouse);
        if(FrameListener)
        {
            delete FrameListener;
        }
    }

    private:
    Ogre::FrameListener* FrameListener;
    Ogre::SceneNode* _node;
    OIS::InputManager* _man;
    OIS::Keyboard* _key;
    Ogre::Vector3 translate;
    Ogre::Degree rotate;
    Ogre::Camera* _Cam;
    OIS::Mouse* _mouse;
    Ogre::Entity* _ent;
    Ogre::AnimationState* _aniState;
    Ogre::AnimationState* _aniStateTop;
    float _WalkingSpeed;
    float _rotation;
    bool _isActionKeyPress;
 };

class Example1 : public ExampleApplication
{
    public:
    void createScene()
    {
        Ogre::Plane plane(Vector3::UNIT_Y,  -10);
        Ogre::MeshManager::getSingleton().createPlane("plane",ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,plane,1500,1500,20,20,true,1,5,5,Vector3::UNIT_Z );
        Ogre::Entity* ent = mSceneMgr->createEntity("LightPlaneEntity", "plane");
        mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent);
        ent->setMaterialName("Examples/BeachStones");
        Ogre::Light* light = mSceneMgr->createLight("Light1");
        light->setType(Ogre::Light::LT_DIRECTIONAL);
        light->setDirection(Ogre::Vector3(1,-1,0));

        Ogre::SceneNode* node = mSceneMgr->createSceneNode("Node1");
        mSceneMgr->getRootSceneNode()->addChild(node);
        _SinbadEnt = mSceneMgr->createEntity("Sinbad", "Sinbad.mesh");
        Ogre::Entity* sword1 = mSceneMgr->createEntity("Sword1","Sword.mesh");
        Ogre::Entity* sword2 = mSceneMgr->createEntity("Sword2","Sword.mesh");
        _SinbadEnt->attachObjectToBone("Handle.L",sword1);
        _SinbadEnt->attachObjectToBone("Handle.R", sword2);
        _SinbadNode = node->createChildSceneNode("SinbadNode");
        _SinbadNode->setScale(3.0f,3.0f,3.0f);
        _SinbadNode->setPosition(Ogre::Vector3(0.0f,4.0f,0.0f));
        _SinbadNode->attachObject(_SinbadEnt);
    }
    void createCamera()
    {
        mCamera = mSceneMgr->createCamera("MyCamera1");
        mCamera->setPosition(0,100,200);
        mCamera->lookAt(0,0,0);
        mCamera->setNearClipDistance(5);
    }
    void createFrameListener()
    {
        Ogre::FrameListener* FrameListener = new Example25FrameListener(_SinbadNode,_SinbadEnt,mWindow,mCamera);
        mRoot->addFrameListener(FrameListener);
    }
    private:
    Ogre::SceneNode* _SinbadNode;
    Ogre::Entity* _SinbadEnt;
};
int main (void)
{
    Example1 app;
    app.go();
    return 0;
}

2012年7月18日 星期三

MinGW需要的檔案

以MinGW4.5為例

binutils-2.20.51-1-mingw32-bin
gcc-c++-4.5.0_20100311-2-mingw32-bin
gcc-core-4.5.0_20100311-2-mingw32-bin
gdb-7.1-2-mingw32-bin.tar 
libgmp-5.0.1-1-mingw32-dll-10
libmpc-0.8.1-1-mingw32-dll-2
libmpfr-2.4.1-1-mingw32-dll-1
libstdc++-4.5.0_20100311-2-mingw32-dll-6
mingw32-make-3.81-2
mingwrt-3.18-mingw32-dev
w32api-3.14-mingw32-dev

NeoOgreBase

NeoOgreBase.h


#ifndef _NEO_OGRE_BASE_H_
#define _NEO_OGRE_BASE_H_
#include <Ogre.h>
class NeoOgreBase
{
public:
     NeoOgreBase() : m_root(NULL), m_render_win(NULL), m_scene_mgr(NULL), m_camera(NULL){}
    ~NeoOgreBase(){if (m_root) delete m_root;}
    void Run(void)
    {
        if (!Initialize())
        {
            exit(-1);
        }
        CreateScene();
        m_root->startRendering();
    }
protected:
    bool Initialize(void)
    {
        m_root = new Ogre::Root("","");
        #ifdef _DEBUG
            m_root->loadPlugin( "RenderSystem_Direct3D9_d" );     // for a debug build
        #else
            m_root->loadPlugin( "RenderSystem_Direct3D9" );     // for a release build
        #endif
//------------------------------------------------------------------------------------
//   Ogre::RenderSystemList *render_sys_list = m_root->getAvailableRenderers();  //for 1.6
//   Ogre::RenderSystemList::iterator it_render_sys(render_sys_list->begin() );//for 1.6
//   while (it_render_sys != render_sys_list->end() )                          //for 1.6
//------------------------------------------------------------------------------------
    const Ogre::RenderSystemList &render_sys_list = m_root->getAvailableRenderers();//for 1.7
    Ogre::RenderSystemList::const_iterator it_render_sys( render_sys_list.begin() );//for 1.7
    while ( it_render_sys != render_sys_list.end() )                                //for 1.7
            {
                Ogre::RenderSystem* render_sys = *(it_render_sys++);
                if(render_sys->getName().find("Direct3D9") != Ogre::String::npos)
                {
                    m_root->setRenderSystem(render_sys);
                    break;
                }
            }
            if (m_root == NULL) 
            {
                delete m_root;
                return false;
            }
            m_root->initialise(false);//false表示不自動產生視窗,手動產生
            m_render_win = m_root->createRenderWindow("Neo Ogre", 320, 240, false); //false表非全螢幕模式
            m_scene_mgr = m_root->createSceneManager(Ogre::ST_GENERIC,"neo scene manager");
            m_camera = m_scene_mgr->createCamera("MainCamera");
            Ogre::Viewport* viewport = m_render_win->addViewport(m_camera);
            viewport->setBackgroundColour(Ogre::ColourValue::Black); //same as ColourValue( 0, 0, 0 )
          
            //設定camera
             m_camera->setAspectRatio( Ogre::Real( viewport->getActualWidth() ) /  Ogre::Real( viewport->getActualHeight() ) );
             m_camera->setNearClipDistance( 10 );
             m_camera->setFarClipDistance( 10000 );
             m_camera->setFOVy( Ogre::Degree( 45 ) );
             m_camera->setPosition( 0, 0, 1000 );

            //增加材質
            Ogre::MaterialPtr mtl;
            mtl = Ogre::MaterialManager::getSingleton().create("NeoMatrial_0", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            mtl->setLightingEnabled(false);
            mtl = Ogre::MaterialManager::getSingleton().create("CheeseCube", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            mtl->setLightingEnabled( true );
            mtl->setAmbient(Ogre::ColourValue( 0.87, 0.77, 0.46 ) );
            mtl->setDiffuse(Ogre::ColourValue( 0.87, 0.77, 0.46 ) );

            return true; 
    }
protected:
    virtual void CreateScene(void) = 0;
    Ogre::Root* m_root;
    Ogre::RenderWindow* m_render_win;
    Ogre::SceneManager* m_scene_mgr;
    Ogre::Camera* m_camera;
private:
};
#endif 

main.cpp
#include <Ogre.h>
#include <iostream>
#include "NeoOgreBase.h"
using namespace Ogre;

class myOgre : public NeoOgreBase
{
protected:
    void CreateScene(void)
    {
      Light *light = m_scene_mgr->createLight( "light0" );
      light->setType( Light::LT_DIRECTIONAL );
      light->setDirection( Vector3( 0, -1, -1 ) );
      m_scene_mgr->setAmbientLight( ColourValue( 0.5, 0.5, 0.5 ) );
      
      SceneNode *center_node = m_scene_mgr->getRootSceneNode()->createChildSceneNode();
            //--------------------------------     
            std::ostringstream entity_name;
            entity_name << "cube0";
            Entity *ent = m_scene_mgr->createEntity(entity_name.str(), SceneManager::PT_CUBE );
            ent->setMaterialName( "CheeseCube" );
            SceneNode *scene_node = center_node->createChildSceneNode();
            scene_node->rotate( Vector3::UNIT_Z, Degree( 0 ), SceneNode::TS_LOCAL );
            scene_node->translate( Vector3( 0, 0, 0 ), SceneNode::TS_LOCAL );
            scene_node->attachObject( ent );
            //---------------------------------
            entity_name << "cube1";
            Entity *ent2 = m_scene_mgr->createEntity(entity_name.str(), SceneManager::PT_CUBE );
            ent2->setMaterialName( "NeoMatrial_0" );
            SceneNode *scene_node2 = center_node->createChildSceneNode();
            scene_node2->rotate( Vector3::UNIT_Z, Degree( 0 ), SceneNode::TS_LOCAL );
            scene_node2->translate( Vector3( 300, 0, 0 ), SceneNode::TS_LOCAL );
            scene_node2->attachObject(ent2);
            //---------------------------------
    }
};

int main(int argc, char *argv[])
{
    myOgre a;
    a.Run();
    return true;
}

Orge 1.6 & 1.7 with vs2008

http://www.ogre3d.org/download/sdk下載Orge 1.6 for vc90

環境Path變數加入
;%OGRE_HOME%/bin/debug;%OGRE_HOME%/bin/release

在VS2008中的工具->選項中找到"專案和方案"->"VC++目錄"
在「Include 檔案」中,加入 $(OGRE_HOME)/include
在「程式庫檔」中,加入 $(OGRE_HOME)/lib

Orge 1.7 :
Include 檔案
OgreSDK_vc9_v1-7-4\include
OgreSDK_vc9_v1-7-4\boost_1_48

Lib檔案
OgreSDK_vc9_v1-7-4\lib\Debug      或    OgreSDK_vc9_v1-7-4\lib\Release
OgreSDK_vc9_v1-7-4\boost_1_48/lib



記得要加入
OgreMain.lib OIS.lib 或 OgreMain_d.lib OIS_d.lib

輸出目錄放
OgreMain.dll OIS.dll 或 OgreMain_d.dll OIS_d.dll
RenderSystem_Direct3D9.dll
d3dx9_43.dll
RenderSystem_GL.dll



main.cpp


目前ogre1.7用codeblock只能跑release mode
記得在Toolchain executable 中的Additional paths中加上$(CODEBLOCKS)\build\vs2008\Microsoft Visual Studio 9.0\Common7\IDE
#include <Ogre.h>
using namespace Ogre;

int main(int argc, char *argv[])
{
    // start the Ogre application
    Root *root = new Root( "", "" );

    // load a plugin(DLL) of the render system
#ifdef _DEBUG
    root->loadPlugin( "RenderSystem_Direct3D9_d" );     // for a debug build
   //  root->loadPlugin("RenderSystem_GL_d");
#else
    root->loadPlugin( "RenderSystem_Direct3D9" );       // for a release build
    // root->loadPlugin("RenderSystem_GL");
#endif

    // select the Direct3D renderer
//------------------------------------------------------------------------------------
//   RenderSystemList *render_sys_list = root->getAvailableRenderers(); //for 1.6
//   RenderSystemList::iterator it_rs( render_sys_list->begin() );      //for 1.6
//   while ( it_rs != render_sys_list->end() )                          //for 1.6
//------------------------------------------------------------------------------------
    const RenderSystemList &render_sys_list = root->getAvailableRenderers();//for 1.7
    RenderSystemList::const_iterator it_rs( render_sys_list.begin() );      //for 1.7
    while ( it_rs != render_sys_list.end() )                                //for 1.7
    {
        RenderSystem *render_sys = *(it_rs++);
      //if ( render_sys->getName().find( "OpenGL" ) != String::npos )
         if ( render_sys->getName().find( "Direct3D9" ) != String::npos )
        {
            root->setRenderSystem( render_sys );
            break;
        }
    }

    // end gracelessly if the preferred renderer is not available
    if ( root->getRenderSystem() == NULL )
    {
        delete root;
        return -1;
    }

    // initialize the root, and tell the root NOT to create a render window
    root->initialise( false );

    // manually create a render window
    RenderWindow* render_win = root->createRenderWindow( "Hello, Ogre!",   // window title
                              320,              // window (client area) width
                              240,              // window height
                              false );          // full screen mode
    // create the SceneManager, in this case a generic one
    SceneManager *scene_mgr = root->createSceneManager(ST_GENERIC, "my scene manager");
    // create the Camera
    Camera *camera = scene_mgr->createCamera( "MainCamera" );
    // create the Viewport
    Viewport *viewport = render_win->addViewport( camera );
     viewport->setBackgroundColour( ColourValue::Black ); // same as ColourValue( 0, 0, 0 )
     camera->setAspectRatio( Real( viewport->getActualWidth() ) / Real( viewport->getActualHeight() ) );
     camera->setNearClipDistance( 1 );
     camera->setFarClipDistance( 1000 );
     camera->setFOVy( Degree( 45 ) );
     camera->setPosition( 0, 0, 500 );
     // create a material with nothing and no lighting
     MaterialPtr mtl = MaterialManager::getSingleton().create( "Neo_MaterIal_NoLighting",ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
     mtl->setLightingEnabled( false );
     // create the triangular face by using ManualObject
     ManualObject* manual = scene_mgr->createManualObject( "triangular_face" );
     manual->begin( "Neo_MaterIal_NoLighting", RenderOperation::OT_TRIANGLE_LIST );
     manual->position(-100.0,  100.0, 0.0);
     manual->colour( ColourValue::Red ); // ColourValue( 1, 0, 0 );
     manual->position(-100.0, -100.0, 0.0);
     manual->colour( ColourValue::Green ); // ColourValue( 0, 1, 0 );
     manual->position( 100.0, -100.0, 0.0);
     manual->colour( ColourValue::Blue ); // ColourValue( 0, 0, 1 );
     manual->end();
     // attach the object to the root node
     scene_mgr->getRootSceneNode()->attachObject( manual );

    // start the rendering loop
    root->startRendering();
    return 0;
}