code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package org.vn.unit;
import java.util.ArrayList;
import java.util.HashMap;
import org.vn.gl.BaseObject;
public class CharacterManager extends BaseObject {
public ArrayList<UnitCharacterSwordmen> arrayCharactersMyTeam = new ArrayList<UnitCharacterSwordmen>();
public ArrayList<UnitCharacterSwordmen> arrayCharactersOtherTeam = new ArrayList<UnitCharacterSwordmen>();
public HashMap<Integer, UnitCharacterSwordmen> mapEnemyInGame = new HashMap<Integer, UnitCharacterSwordmen>();
public UnitCharacterSwordmen myKing;
@Override
public void update(float timeDelta, BaseObject parent) {
for (UnitCharacter character : arrayCharactersMyTeam) {
character.update(timeDelta, parent);
}
for (UnitCharacter character : arrayCharactersOtherTeam) {
character.update(timeDelta, parent);
}
}
// public void setIsMapChangeAndPutAllCharacter(boolean b) {
// mapEnemyInGame.clear();
// for (UnitCharacterSwordmen character : arrayCharactersMyTeam) {
// character.isMapChange = b;
// mapEnemyInGame.put(character.idEnemy, character);
// }
// for (UnitCharacterSwordmen character : arrayCharactersOtherTeam) {
// character.isMapChange = b;
// mapEnemyInGame.put(character.idEnemy, character);
// }
// }
public void nextTurn() {
for (UnitCharacterSwordmen character : arrayCharactersMyTeam) {
character.nextTurn();
}
for (UnitCharacterSwordmen character : arrayCharactersOtherTeam) {
character.nextTurn();
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/unit/CharacterManager.java | Java | oos | 1,490 |
package org.vn.unit;
import org.vn.gl.Priority;
public class EffectSoBayLen extends Effect {
private float mX, mY;
private float mAlpha;
private int mNum;
private NumberDrawable mNumberDrawable;
public boolean cameraRelative = true;
public float speed = 1;
public boolean isDraw = true;
public int priority = Priority.CharacterTakeDamage;
public EffectSoBayLen(NumberDrawable numberDrawable, int num, float x,
float y) {
mX = x;
mY = y;
mAlpha = 3;
mNum = num;
mNumberDrawable = numberDrawable;
}
public void setDrawAble(boolean b) {
isDraw = b;
}
@Override
public boolean update(float timeDelta) {
if (mAlpha > 0) {
if (isDraw) {
if (mAlpha > 1) {
mNumberDrawable.drawNumberWithAlpha(mX, mY, mNum, 1,
cameraRelative, true, priority);
} else {
mNumberDrawable.drawNumberWithAlpha(mX, mY, mNum, mAlpha,
cameraRelative, true, priority);
}
}
mY += 0.5f / speed;
mAlpha -= 0.08f * speed;
return true;
}
return false;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/unit/EffectSoBayLen.java | Java | oos | 1,057 |
package org.vn.custom;
import java.util.ArrayList;
import org.vn.herowar.R;
import org.vn.model.Enemy;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class EnemyWaitingAdapter extends ArrayAdapter<Enemy> {
public EnemyWaitingAdapter(Context pContext, int textViewResourceId,
ArrayList<Enemy> enemys) {
super(pContext, textViewResourceId, enemys);
mEnemys = enemys;
context = pContext;
}
private Context context;
private final ArrayList<Enemy> mEnemys;
// public EnemyWaitingAdapter(Context context, ArrayList<Enemy> enemys) {
// this.context = context;
// this.mEnemys = enemys;
// }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.enemy_waiting, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(mEnemys.get(position).getEnemyType().armyName);
// set image based on selected text
// ImageView imageView = (ImageView) gridView
// .findViewById(R.id.grid_item_image);
} else {
gridView = (View) convertView;
}
return gridView;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/custom/EnemyWaitingAdapter.java | Java | oos | 1,571 |
package org.vn.custom;
import org.vn.herowar.R;
import org.vn.model.Result;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ResuftAdapter extends BaseAdapter {
private Context context;
private final Result pResult;
public ResuftAdapter(Context context, Result result) {
this.context = context;
this.pResult = result;
}
private class ViewHolder {
public ImageView per;
public TextView text1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView = convertView;
if (gridView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.item_resuft, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.per = (ImageView) gridView
.findViewById(R.id.image_winner);
viewHolder.text1 = (TextView) gridView
.findViewById(R.id.name_player);
gridView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) gridView.getTag();
if (position == 0) {
holder.text1.setText(context.getString(R.string.is_winner,
pResult.winnerName));
holder.per.setVisibility(View.VISIBLE);
} else {
holder.text1.setText(context.getString(R.string.is_loser,
pResult.loserName));
holder.per.setVisibility(View.INVISIBLE);
}
return gridView;
}
@Override
public int getCount() {
return 2;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/custom/ResuftAdapter.java | Java | oos | 1,867 |
package org.vn.custom;
import org.vn.herowar.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.image_and_text, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(mobileValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
String mobile = mobileValues[position];
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return mobileValues.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/custom/ImageAdapter.java | Java | oos | 1,570 |
package org.vn.custom;
import java.util.ArrayList;
import org.vn.gl.DebugLog;
import org.vn.herowar.R;
import org.vn.model.EnemyType;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class EnemyShopAdapter extends ArrayAdapter<EnemyType> {
public EnemyShopAdapter(Activity pContext, int textViewResourceId,
ArrayList<EnemyType> enemys) {
super(pContext, textViewResourceId, enemys);
context = pContext;
}
private class ViewHolder {
public TextView text;
}
private Activity context;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View gridView = convertView;
if (gridView == null) {
LayoutInflater inflater = context.getLayoutInflater();
gridView = inflater.inflate(R.layout.enemy_waiting, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) gridView
.findViewById(R.id.grid_item_label);
gridView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) gridView.getTag();
holder.text.setText(this.getItem(position).armyName);
DebugLog.d("DUC", "getView " + this.getItem(position).armyName);
return gridView;
}
@Override
public void add(EnemyType object) {
DebugLog.d("DUC", "add " + object.armyName);
super.add(object);
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/custom/EnemyShopAdapter.java | Java | oos | 1,452 |
package org.vn.custom;
import org.vn.herowar.R;
import org.vn.model.Board;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class BoardAdapter extends BaseAdapter {
private Context context;
private final Board[] mobileValues;
public BoardAdapter(Context context, Board[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
private class ViewHolder {
public TextView text;
public ImageView per1;
public ImageView per2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView = convertView;
if (gridView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.item_board, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) gridView
.findViewById(R.id.grid_item_label);
viewHolder.per1 = (ImageView) gridView.findViewById(R.id.per1);
viewHolder.per2 = (ImageView) gridView.findViewById(R.id.per2);
gridView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) gridView.getTag();
holder.text.setText(context.getString(R.string.board)
+ mobileValues[position].id);
if (mobileValues[position].nPlayer > 0) {
holder.per1.setColorFilter(Color.TRANSPARENT);
} else {
holder.per1.setColorFilter(Color.BLACK);
}
if (mobileValues[position].nPlayer > 1) {
holder.per2.setColorFilter(Color.TRANSPARENT);
} else {
holder.per2.setColorFilter(Color.BLACK);
}
return gridView;
}
@Override
public int getCount() {
return mobileValues.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/custom/BoardAdapter.java | Java | oos | 2,119 |
package org.vn.network;
import java.io.IOException;
import java.util.ArrayList;
import org.vn.cache.CurrentGameInfo;
import org.vn.cache.CurrentUserInfo;
import org.vn.constant.CommandClientToServer;
import org.vn.model.Server;
import org.vn.unit.UnitCharacterSwordmen;
import vn.thedreamstudio.socket.IMobileClient;
import vn.thedreamstudio.socket.Message;
import vn.thedreamstudio.socket.MobileClient;
public class GlobalService {
protected static GlobalService instance;
static IMobileClient mSession = MobileClient.getInstance();
private CurrentGameInfo mCurrentGameInfo = CurrentGameInfo.getIntance();
private GlobalService() {
}
public static GlobalService getInstance() {
if (instance == null) {
instance = new GlobalService();
}
return instance;
}
public boolean isConnected() {
return mSession.isConnected();
}
public void close() {
mSession.close();
}
public boolean connect(Server server) {
mSession.setHandler(GlobalMessageHandler.getInstance());
if (MobileClient.CONNECT_STATUS_CONNECTED == mSession.connect(
server.ip, server.port)) {
// sendClientInformation();
return true;
}
return false;
}
public void SYS_LOGIN(String username, String pass) {
Message m = new Message(CommandClientToServer.SYS_LOGIN);
try {
CurrentUserInfo.mUsername = username;
CurrentUserInfo.mUsername = pass;
m.writer().writeUTF(username);
m.writer().writeUTF(pass);
mSession.sendMessage(m);
m.cleanup();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Đăng ký
*
* @param username
* @param password
*/
public void SYS_REGISTER(String username, String password, String phone_num) {
Message m = new Message(CommandClientToServer.SYS_REGISTER);
try {
m.writer().writeUTF(username);
m.writer().writeUTF(password);
m.writer().writeUTF(phone_num);
} catch (IOException e) {
}
mSession.sendMessage(m);
m.cleanup();
}
/**
* Lấy danh sách các bàn chơi trong một phòng
*/
public void SYS_BOARD_LIST() {
Message m = new Message(CommandClientToServer.SYS_BOARD_LIST);
mSession.sendMessage(m);
m.cleanup();
}
/**
* Tham gia vào một bàn chơi game
*
* @param roomID
* @param boardID
*/
public void JOIN_BOARD(int boardID) {
Message m = new Message(CommandClientToServer.JOIN_BOARD);
try {
m.writer().writeInt(boardID);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
/**
*
* @param platform
* @param model
* @param version
* @param language
* 0:vn ; 1:eng
*/
public void GET_CLIENT_INFO(String platform, String model, String version,
byte language) {
Message m = new Message(CommandClientToServer.GET_CLIENT_INFO);
try {
m.writer().writeUTF(platform);
m.writer().writeUTF(model);
m.writer().writeUTF(version);
m.writer().writeByte(language);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void EXIT_BOARD(int boardID) {
Message m = new Message(CommandClientToServer.EXIT_BOARD);
try {
m.writer().writeInt(boardID);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void SET_GAME_TYPE(byte idGame) {
Message m = new Message(CommandClientToServer.SET_GAME_TYPE);
try {
m.writer().writeByte(idGame);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void CHAT_BOARD(String content) {
Message m = new Message(CommandClientToServer.CHAT_BOARD);
try {
m.writer().writeUTF(content);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void LEAVE_BOARD() {
Message m = new Message(CommandClientToServer.LEAVE_BOARD);
mSession.sendMessage(m);
m.cleanup();
}
public void GET_ARMY_SHOP() {
Message m = new Message(CommandClientToServer.GET_ARMY_SHOP);
mSession.sendMessage(m);
m.cleanup();
}
// public void ARMY_SELECTION(ArrayList<Integer> enemyIDs) {
// Message m = new Message(CommandClientToServer.ARMY_SELECTION);
// try {
// m.writer().writeInt(enemyIDs.size());
// for (Integer i : enemyIDs) {
// m.writer().writeInt(i);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// mSession.sendMessage(m);
// m.cleanup();
// }
public void ARMY_SELECTION(
ArrayList<UnitCharacterSwordmen> arrayCharactersMyTeam) {
Message m = new Message(CommandClientToServer.ARMY_SELECTION);
try {
m.writer().writeInt(arrayCharactersMyTeam.size());
for (UnitCharacterSwordmen unitCharacter : arrayCharactersMyTeam) {
m.writer().writeInt(unitCharacter.mEnemyType.armyType);
}
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void GET_ALL_MAP() {
Message m = new Message(CommandClientToServer.GET_ALL_MAP);
mSession.sendMessage(m);
m.cleanup();
}
public void GET_MAP(byte mapId) {
Message m = new Message(CommandClientToServer.GET_MAP);
try {
m.writer().writeByte(mapId);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void SET_MAP(byte mapId) {
Message m = new Message(CommandClientToServer.SET_MAP);
try {
m.writer().writeByte(mapId);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void LAYOUT_ARMY(
ArrayList<UnitCharacterSwordmen> arrayCharactersMyTeam) {
Message m = new Message(CommandClientToServer.LAYOUT_ARMY);
try {
for (UnitCharacterSwordmen unitCharacterSwordmen : arrayCharactersMyTeam) {
m.writer().writeInt(unitCharacterSwordmen.idEnemy);
m.writer().writeInt(unitCharacterSwordmen.mTileTaget.xTile);
m.writer().writeInt(unitCharacterSwordmen.mTileTaget.yTile);
}
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void READY() {
Message m = new Message(CommandClientToServer.READY);
mSession.sendMessage(m);
m.cleanup();
}
public void START_GAME() {
Message m = new Message(CommandClientToServer.START_GAME);
mSession.sendMessage(m);
m.cleanup();
}
public void MOVE_ARMY(int idEnemyMove, int xTileMoveNext, int yTileMoveNext) {
Message m = new Message(CommandClientToServer.MOVE_ARMY);
try {
m.writer().writeInt(idEnemyMove);
m.writer().writeInt(xTileMoveNext);
m.writer().writeInt(yTileMoveNext);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void ATTACH(int idAtack, int idBeAtack) {
Message m = new Message(CommandClientToServer.ATTACH);
try {
m.writer().writeInt(idAtack);
m.writer().writeInt(idBeAtack);
} catch (IOException e) {
e.printStackTrace();
}
mSession.sendMessage(m);
m.cleanup();
}
public void NEXT_TURN() {
Message m = new Message(CommandClientToServer.NEXT_TURN);
mSession.sendMessage(m);
m.cleanup();
}
public void LOGIN_TRIAL(String username) {
Message m = new Message(CommandClientToServer.LOGIN_TRIAL);
try {
m.writer().writeUTF(username);
mSession.sendMessage(m);
m.cleanup();
} catch (IOException e) {
e.printStackTrace();
}
}
public void BUY_SOLDIER_INGAME(int armyType, int x_tile, int y_tile) {
Message m = new Message(CommandClientToServer.BUY_SOLDIER_INGAME);
try {
m.writer().writeInt(armyType);
m.writer().writeInt(x_tile);
m.writer().writeInt(y_tile);
mSession.sendMessage(m);
m.cleanup();
} catch (IOException e) {
e.printStackTrace();
}
}
public void ACHIEVEMENT(String playerName) {
Message m = new Message(CommandClientToServer.ACHIEVEMENT);
try {
m.writer().writeUTF(playerName);
mSession.sendMessage(m);
m.cleanup();
} catch (IOException e) {
e.printStackTrace();
}
}
public void LOGOUT() {
Message m = new Message(CommandClientToServer.LOGOUT);
mSession.sendMessage(m);
m.cleanup();
}
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/network/GlobalService.java | Java | oos | 8,333 |
package org.vn.network;
import java.util.ArrayList;
import org.vn.cache.CurrentGameInfo;
import org.vn.cache.CurrentUserInfo;
import org.vn.constant.CommandClientToServer;
import org.vn.gl.BaseObject;
import org.vn.gl.DebugLog;
import org.vn.model.Achievement;
import org.vn.model.AttackMessage;
import org.vn.model.Board;
import org.vn.model.BuyEnemy;
import org.vn.model.Enemy;
import org.vn.model.EnemyType;
import org.vn.model.Map;
import org.vn.model.MapType;
import org.vn.model.Money;
import org.vn.model.MoveMessage;
import org.vn.model.NextTurnMessage;
import org.vn.model.PlayerModel;
import org.vn.model.Result;
import org.vn.unit.ActionList;
import org.vn.unit.ActionServerToClient.ActionType;
import org.vn.unit.UnitCharacterSwordmen;
import vn.thedreamstudio.socket.IMessageListener;
import vn.thedreamstudio.socket.Message;
public class GlobalMessageHandler implements IMessageListener {
protected static GlobalMessageHandler instance;
private ArrayList<MessageListener> mMessageListeners = new ArrayList<GlobalMessageHandler.MessageListener>();
private CurrentGameInfo mCurrentGameInfo = CurrentGameInfo.getIntance();
private ActionList mActionList = ActionList.getInstance();
private GlobalService mGs = GlobalService.getInstance();
private GlobalMessageHandler() {
}
public static GlobalMessageHandler getInstance() {
if (instance == null) {
instance = new GlobalMessageHandler();
}
return instance;
}
synchronized public void addMessageListener(MessageListener msgListener) {
if (!mMessageListeners.contains(msgListener)) {
mMessageListeners.add(0, msgListener);
}
}
synchronized public void removeMessageListener(MessageListener msgListener) {
if (mMessageListeners.contains(msgListener)) {
mMessageListeners.remove(msgListener);
}
}
@Override
public void onMessage(Message msg) {
LightWeightMessage lightweightMsg = new LightWeightMessage();
lightweightMsg.command = msg.command;
try {
switch (msg.command) {
case CommandClientToServer.LOGOUT:
if (mGs.isConnected()) {
mGs.close();
}
break;
case CommandClientToServer.SYS_LOGIN: {
byte result = msg.reader().readByte();
if (result == 1) {
// login thanh cong
lightweightMsg.arg1 = 1;
} else {
// login loi
lightweightMsg.arg1 = 0;
}
}
break;
case CommandClientToServer.SYS_REGISTER: {
byte result = msg.reader().readByte();
if (result == 1) {
// login thanh cong
lightweightMsg.arg1 = 1;
lightweightMsg.obj = msg.reader().readUTF();
} else {
// login loi
lightweightMsg.arg1 = 0;
lightweightMsg.obj = msg.reader().readUTF();
}
}
break;
case CommandClientToServer.SYS_BOARD_LIST: {
int countBoard = msg.reader().readInt();
Board[] boards = new Board[countBoard];
for (int i = 0; i < boards.length; i++) {
boards[i] = new Board();
boards[i].id = msg.reader().readInt();
boards[i].maxPlayer = msg.reader().readByte();
boards[i].nPlayer = msg.reader().readByte();
}
lightweightMsg.obj = boards;
}
break;
case CommandClientToServer.GET_USER_INFO: {
PlayerModel playerModel = CurrentUserInfo.mPlayerInfo;
playerModel.ID = msg.reader().readInt();
playerModel.name = msg.reader().readUTF();
playerModel.money = msg.reader().readLong();
playerModel.lv = msg.reader().readInt();
}
break;
case CommandClientToServer.JOIN_BOARD: {
mCurrentGameInfo.mListPlayerInGame.clear();
int boardId = msg.reader().readInt();
byte result = msg.reader().readByte();
lightweightMsg.arg1 = result;
lightweightMsg.arg2 = boardId;
if (result == 1) {
mCurrentGameInfo.reset();
mCurrentGameInfo.boardId = boardId;
mCurrentGameInfo.ownerId = msg.reader().readInt();
while (msg.reader().available() != 0) {
PlayerModel playerModel = new PlayerModel();
playerModel.ID = msg.reader().readInt();
playerModel.name = msg.reader().readUTF();
if (playerModel.ID != -1) {
mCurrentGameInfo.mListPlayerInGame.add(playerModel);
if (mCurrentGameInfo.mHashAchievement
.get(playerModel.name) == null) {
mGs.ACHIEVEMENT(playerModel.name);
}
}
}
}
}
break;
case CommandClientToServer.CHAT_BOARD: {
lightweightMsg.arg1 = msg.reader().readInt();
String content = msg.reader().readUTF();
content += ":" + msg.reader().readUTF();
;
lightweightMsg.obj = content;
}
break;
case CommandClientToServer.GET_ARMY_SHOP: {
mCurrentGameInfo.gold = msg.reader().readInt();
int countEnemy = msg.reader().readByte();
mCurrentGameInfo.listEnemytype.clear();
for (int i = 0; i < countEnemy; i++) {
EnemyType enemy = new EnemyType();
enemy.armyType = msg.reader().readInt();
enemy.armyName = msg.reader().readUTF();
enemy.cost = msg.reader().readInt();
enemy.hp = msg.reader().readInt();
enemy.damageMax = msg.reader().readInt();
enemy.damageMin = msg.reader().readInt();
enemy.mana = msg.reader().readInt();
enemy.movecost = msg.reader().readInt();
enemy.attackcost = msg.reader().readInt();
enemy.rangeattack = msg.reader().readInt();
enemy.rangeview = msg.reader().readInt();
mCurrentGameInfo.listEnemytype.add(enemy);
}
}
break;
case CommandClientToServer.SOMEONE_JOIN_BOARD: {
mCurrentGameInfo.mListPlayerInGame.clear();
mCurrentGameInfo.boardId = msg.reader().readInt();
while (msg.reader().available() != 0) {
PlayerModel playerModel = new PlayerModel();
playerModel.ID = msg.reader().readInt();
playerModel.name = msg.reader().readUTF();
if (playerModel.ID != -1) {
mCurrentGameInfo.mListPlayerInGame.add(playerModel);
lightweightMsg.obj = playerModel.name;
if (mCurrentGameInfo.mHashAchievement
.get(playerModel.name) == null) {
mGs.ACHIEVEMENT(playerModel.name);
}
}
}
}
break;
case CommandClientToServer.SOMEONE_LEAVE_BOARD: {
boolean isBackToWaiting = false;
int idPlayerLeave = msg.reader().readInt();
int idNewOwner = msg.reader().readInt();
// Neu chuyen? quyen` host va` da~ lo~ chon linh thi cho chon
// lai
if (idNewOwner == CurrentUserInfo.mPlayerInfo.ID) {
for (PlayerModel playerModel : mCurrentGameInfo.mListPlayerInGame) {
if (playerModel.ID == CurrentUserInfo.mPlayerInfo.ID
&& playerModel.isReady) {
isBackToWaiting = true;
break;
}
}
}
for (PlayerModel playerModel : mCurrentGameInfo.mListPlayerInGame) {
if (idPlayerLeave == playerModel.ID) {
mCurrentGameInfo.mListPlayerInGame.remove(playerModel);
lightweightMsg.obj = playerModel.name;
break;
}
}
mCurrentGameInfo.ownerId = idNewOwner;
lightweightMsg.arg1 = isBackToWaiting ? 1 : 0;
}
break;
case CommandClientToServer.ARMY_SELECTION: {
byte result = msg.reader().readByte();
lightweightMsg.arg1 = result;
if (result == 1) {
while (msg.reader().available() != 0) {
int armyId = msg.reader().readInt();
int armyType = msg.reader().readInt();
for (UnitCharacterSwordmen unitCharacter : BaseObject.sSystemRegistry.characterManager.arrayCharactersMyTeam) {
if (armyType == unitCharacter.mEnemyType.armyType
&& unitCharacter.idEnemy == -1) {
unitCharacter.idEnemy = armyId;
break;
}
}
}
}
}
break;
case CommandClientToServer.GET_ALL_MAP: {
CurrentGameInfo gameInfo = CurrentGameInfo.getIntance();
gameInfo.listMaps.clear();
byte count = msg.reader().readByte();
for (byte i = 0; i < count; i++) {
if (msg.reader().available() != 0) {
Map map = new Map();
map.mapId = msg.reader().readByte();
map.mapName = msg.reader().readUTF();
gameInfo.listMaps.add(map);
}
}
}
break;
case CommandClientToServer.GET_MAP: {
CurrentGameInfo gameInfo = CurrentGameInfo.getIntance();
byte mapId = msg.reader().readByte();
if (mapId == mCurrentGameInfo.mMapSelected.mapId) {
MapType mapType = new MapType();
mapType.row = msg.reader().readInt();
if (mapType.row > 0) {
mapType.column = msg.reader().readInt();
mapType.mapType = new byte[mapType.column][mapType.row];
int count = 0;
for (int x = 0; x < mapType.row; x++) {
for (int y = 0; y < mapType.column; y++) {
mapType.mapType[y][x] = msg.reader().readByte();
count++;
}
}
}
mCurrentGameInfo.mMapSelected.mapType = mapType;
break;
}
lightweightMsg.arg1 = mapId;
}
break;
case CommandClientToServer.SET_MAP: {
byte mapId = msg.reader().readByte();
byte result = msg.reader().readByte();
lightweightMsg.arg1 = result;
if (result == 1) {
// - row: int (vi tri tuong)
// - col: int (vi tri tuong)
// - range: int
mCurrentGameInfo.mMapSelected = new Map();
mCurrentGameInfo.mMapSelected.mapId = mapId;
while (msg.reader().available() > 0) {
int idUser = msg.reader().readInt();
int xTileKing = msg.reader().readInt();
int yTileKing = msg.reader().readInt();
int rangerSetupEnemy = msg.reader().readInt();
if (idUser == CurrentUserInfo.mPlayerInfo.ID) {
mCurrentGameInfo.xTileKing = xTileKing;
mCurrentGameInfo.yTileKing = yTileKing;
mCurrentGameInfo.rangerSetupEnemy = rangerSetupEnemy;
}
}
}
}
break;
case CommandClientToServer.LAYOUT_ARMY: {
lightweightMsg.arg1 = msg.reader().readByte();
}
break;
case CommandClientToServer.READY: {
int boardId = msg.reader().readInt();
if (mCurrentGameInfo.boardId == boardId) {
int userId = msg.reader().readInt();
lightweightMsg.arg1 = userId;
boolean isReady = msg.reader().readByte() == 1 ? true
: false;
for (PlayerModel playerModel : mCurrentGameInfo.mListPlayerInGame) {
if (playerModel.ID == userId) {
lightweightMsg.obj = playerModel.name;
playerModel.isReady = isReady;
break;
}
}
}
}
break;
case CommandClientToServer.START_GAME: {
mActionList.clear();
for (PlayerModel playerModel : mCurrentGameInfo.mListPlayerInGame) {
playerModel.isReady = false;
}
ArrayList<Enemy> listEnemies = new ArrayList<Enemy>();
while (msg.reader().available() > 0) {
Enemy enemy = new Enemy();
enemy.armyId = msg.reader().readInt();
enemy.armyType = msg.reader().readInt();
enemy.playerId = msg.reader().readInt();
enemy.xTile = msg.reader().readInt();
enemy.yTile = msg.reader().readInt();
listEnemies.add(enemy);
}
lightweightMsg.obj = listEnemies;
}
break;
case CommandClientToServer.MOVE_ARMY: {
lightweightMsg.arg1 = msg.reader().readByte();
if (lightweightMsg.arg1 == 1)// suscess
{
MoveMessage moveMessage = new MoveMessage();
moveMessage.idMove = msg.reader().readInt();
moveMessage.xTypeMoveNext = msg.reader().readInt();
moveMessage.yTypeMoveNext = msg.reader().readInt();
lightweightMsg.obj = moveMessage;
mActionList.push(ActionType.move, moveMessage);
}
}
break;
case CommandClientToServer.ATTACH: {
lightweightMsg.arg1 = msg.reader().readByte();
if (lightweightMsg.arg1 == 1)// suscess
{
AttackMessage atackMessage = new AttackMessage();
atackMessage.idAttacker = msg.reader().readInt();
atackMessage.hpIdAttack = msg.reader().readInt();
atackMessage.idBeAttacker = msg.reader().readInt();
atackMessage.hpIdBeAttack = msg.reader().readInt();
lightweightMsg.obj = atackMessage;
mActionList.push(ActionType.attack, atackMessage);
}
}
break;
case CommandClientToServer.NEXT_TURN: {
NextTurnMessage nextTurnMessage = new NextTurnMessage();
nextTurnMessage.idPlayerInTurnNext = msg.reader().readInt();
nextTurnMessage.totaltime = msg.reader().readLong();
nextTurnMessage.turntime = msg.reader().readLong();
nextTurnMessage.rivalTotaltime = msg.reader().readLong();
nextTurnMessage.rivalTurnTime = msg.reader().readLong();
lightweightMsg.obj = nextTurnMessage;
mActionList.push(ActionType.next_turn, nextTurnMessage);
}
break;
case CommandClientToServer.SERVER_MESSAGE: {
int type = msg.reader().readByte();
String content = msg.reader().readUTF();
lightweightMsg.obj = content;
}
break;
case CommandClientToServer.END_GAME:
mCurrentGameInfo.endGame();
Result result = new Result();
result.winnerID = msg.reader().readInt();
result.winnerName = msg.reader().readUTF();
result.winnerMoney = msg.reader().readLong();
result.winnerLevel = msg.reader().readInt();
result.loserID = msg.reader().readInt();
result.loserName = msg.reader().readUTF();
result.loserMoney = msg.reader().readLong();
result.loserLevel = msg.reader().readInt();
lightweightMsg.obj = result;
mCurrentGameInfo.result = result;
Achievement achievement = mCurrentGameInfo.mHashAchievement
.get(result.winnerName);
if (achievement != null) {
achievement.winnumber++;
}
achievement = mCurrentGameInfo.mHashAchievement
.get(result.loserName);
if (achievement != null) {
achievement.losenumber++;
}
mActionList.push(ActionType.end_game, result);
break;
case CommandClientToServer.SET_FOG:
byte b = msg.reader().readByte();
mCurrentGameInfo.isSuongMu = b == 1;
break;
case CommandClientToServer.BUY_SOLDIER_INGAME:
BuyEnemy buyEnemy = new BuyEnemy();
buyEnemy.buyerId = msg.reader().readInt();
buyEnemy.money = msg.reader().readInt();
buyEnemy.armytype = msg.reader().readInt();
buyEnemy.armyid = msg.reader().readInt();
buyEnemy.x_tile = msg.reader().readInt();
buyEnemy.y_tile = msg.reader().readInt();
mActionList.push(ActionType.buy_enemy, buyEnemy);
break;
case CommandClientToServer.MONEY:
byte subCommand = msg.reader().readByte();
lightweightMsg.arg1 = subCommand;
switch (subCommand) {
case CommandClientToServer.MONEY_UPDATE:
ArrayList<Money> listMoney = new ArrayList<Money>();
while (msg.reader().available() > 0) {
Money money = new Money();
money.playerID = msg.reader().readInt();
money.money = msg.reader().readInt();
listMoney.add(money);
}
mActionList.push(ActionType.update_money, listMoney);
break;
}
case CommandClientToServer.ACHIEVEMENT:
achievement = new Achievement();
achievement.playerID = msg.reader().readInt();
achievement.playerName = msg.reader().readUTF();
achievement.winnumber = msg.reader().readInt();
achievement.losenumber = msg.reader().readInt();
Achievement achievement2 = mCurrentGameInfo.mHashAchievement
.get(achievement.playerName);
if (achievement2 == null) {
mCurrentGameInfo.mHashAchievement.put(
achievement.playerName, achievement);
} else {
achievement2.winnumber = achievement.winnumber;
achievement2.losenumber = achievement.losenumber;
}
break;
}
try {
for (MessageListener listener : mMessageListeners) {
listener.onMessageReceived(lightweightMsg);
}
} catch (Exception e) {
DebugLog.e("MobileClient", "Can't process ms: " + msg.command
+ "--/--" + e.toString());
}
} catch (Exception e) {
DebugLog.e("MobileClient", "Can't read ms: " + msg.command
+ "--/--" + e.toString());
}
}
@Override
public void onConnectionFail() {
}
@Override
public void onDisconnected() {
LightWeightMessage lightweightMsg = new LightWeightMessage();
lightweightMsg.command = CommandClientToServer.LOST_CONNECTION;
try {
for (MessageListener listener : mMessageListeners) {
listener.onMessageReceived(lightweightMsg);
}
} catch (Exception e) {
DebugLog.e("MobileClient", "Can't process ms: "
+ lightweightMsg.command + "--/--" + e.toString());
}
}
@Override
public void onConnectOK() {
}
public static class LightWeightMessage {
public byte command;
public int arg1;
public int arg2;
public Object obj;
}
public interface MessageListener {
public void onMessageReceived(LightWeightMessage msg);
}
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/network/GlobalMessageHandler.java | Java | oos | 16,846 |
package org.vn.herowar;
import java.util.ArrayList;
import org.vn.cache.CurrentGameInfo;
import org.vn.cache.CurrentUserInfo;
import org.vn.constant.CommandClientToServer;
import org.vn.custom.ImageAdapter;
import org.vn.gl.Utils;
import org.vn.model.Achievement;
import org.vn.model.EnemyType;
import org.vn.model.PlayerModel;
import org.vn.network.GlobalMessageHandler.LightWeightMessage;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class WaitingActivity extends CoreActiity {
private static final int DLG_EXIT = 1;
private CurrentGameInfo mCurrentGameInfo = CurrentGameInfo.getIntance();
EditText editFog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.waiting);
mListViewPlayerInBoard = (ListView) findViewById(R.id.listViewPlayerInBoard);
mBtChat = (Button) findViewById(R.id.btChatWaiting);
mEdChat = (EditText) findViewById(R.id.editTextChatWaiting);
mListviewChatInWaiting = (ListView) findViewById(R.id.listViewChatInWaiting);
// mEnemyShop = (ListView) findViewById(R.id.listViewEnemyInWaiting);
mBtReady = (Button) findViewById(R.id.btReadyEnemyWaiting);
// mTextViewGold = (TextView) findViewById(R.id.textInforGoldWaiting);
// mEnemyChosse = (ListView) findViewById(R.id.listViewEnemyChossen);
mBtChat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String content = mEdChat.getText().toString();
if (content.length() > 0) {
mGS.CHAT_BOARD(content);
mEdChat.setText("");
mBtChat.setClickable(false);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mBtChat.getWindowToken(), 0);
}
}
});
mEdChat.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
editTextChatChange("" + arg0);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
editTextChatChange("" + arg0);
}
@Override
public void afterTextChanged(Editable arg0) {
}
});
mBtReady.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showProgressDialog();
if (mCurrentGameInfo.isHost()) {
mGS.START_GAME();
} else {
mGS.READY();
}
mBtReady.setTextColor(Color.WHITE);
mBtReady.setEnabled(true);
}
});
{
ArrayList<String> mList_content_chat = new ArrayList<String>();
mAdapterChat = new ArrayAdapter<String>(this,
R.layout.array_string, mList_content_chat);
mListviewChatInWaiting.setAdapter(mAdapterChat);
mAdapterChat.setNotifyOnChange(true);
}
processMs();
}
synchronized public void processMs() {
runOnUiThread(new Runnable() {
@Override
public void run() {
updatePerson();
mBtReady.setTextColor(Color.BLACK);
mBtReady.setEnabled(false);
if (mCurrentGameInfo.isHost()) {
mBtReady.setText("Start");
} else {
mBtReady.setText("Ready");
}
// CHECK GET_ARMY_SHOP
if (mCurrentGameInfo.listEnemytype.size() == 0) {
showProgressDialog();
mGS.GET_ARMY_SHOP();
} else {
updateGold();
if (mCurrentGameInfo.listMaps.size() == 0) {
showProgressDialog();
mGS.GET_ALL_MAP();
} else if (mCurrentGameInfo.mMapSelected == null) {
if (mCurrentGameInfo.isHost()) {
showProgressDialog();
mGS.SET_MAP(mCurrentGameInfo.listMaps.get(0).mapId);
}
} else {
if (mCurrentGameInfo.mMapSelected.mapType == null) {
showProgressDialog();
mGS.GET_MAP(mCurrentGameInfo.mMapSelected.mapId);
} else {
dismissProgressDialog();
if (mCurrentGameInfo.isHost()) {
if (mCurrentGameInfo.isReadyAll()) {
mBtReady.setTextColor(Color.WHITE);
mBtReady.setEnabled(true);
}
} else {
for (PlayerModel playerInBoard : mCurrentGameInfo.mListPlayerInGame) {
if (playerInBoard.ID == CurrentUserInfo.mPlayerInfo.ID) {
if (playerInBoard.isReady) {
mBtReady.setTextColor(Color.BLACK);
} else {
mBtReady.setTextColor(Color.WHITE);
}
mBtReady.setEnabled(true);
break;
}
}
}
}
}
}
}
});
}
private ListView mListViewPlayerInBoard;
private Button mBtChat;
private EditText mEdChat;
private ListView mListviewChatInWaiting;
private ArrayAdapter<String> mAdapterChat;
// private ListView mEnemyShop;
// private ListView mEnemyChosse;
private Button mBtReady;
// private TextView mTextViewGold;
// private EnemyShopAdapter mEnemyShopAdapter;
// private EnemyShopAdapter mEnemyChosseAdapter;
public ArrayList<EnemyType> listEnemyChossen = new ArrayList<EnemyType>();
private int mCurrenGold;
@Override
public void onMessageReceived(LightWeightMessage msg) {
switch (msg.command) {
case CommandClientToServer.LOST_CONNECTION:
onDisconnect();
break;
case CommandClientToServer.SOMEONE_JOIN_BOARD:
case CommandClientToServer.SOMEONE_LEAVE_BOARD:
processMs();
break;
case CommandClientToServer.CHAT_BOARD:
String content = (String) msg.obj;
final String tamp = content;
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapterChat.add(tamp);
}
});
break;
case CommandClientToServer.GET_ARMY_SHOP:
processMs();
break;
case CommandClientToServer.GET_ALL_MAP:
processMs();
break;
case CommandClientToServer.SET_MAP:
processMs();
break;
case CommandClientToServer.GET_MAP:
processMs();
break;
case CommandClientToServer.READY:
String s = (String) msg.obj;
if (s != null) {
showToast(getString(R.string.ready_in_game, s));
}
processMs();
break;
case CommandClientToServer.START_GAME:
showToast(getString(R.string.The_game_has_start));
gotoInGame();
break;
case CommandClientToServer.ACHIEVEMENT:
runOnUiThread(new Runnable() {
@Override
public void run() {
updatePerson();
}
});
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showDialog(DLG_EXIT);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DLG_EXIT:
return new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit))
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface arg0,
int arg1) {
gotoBoard();
}
}).setNegativeButton(R.string.dialog_cancel, null)
.create();
}
return super.onCreateDialog(id);
}
private void gotoBoard() {
// mGS.EXIT_BOARD(CurrentGameInfo.getIntance().boardId);
mGS.LEAVE_BOARD();
Intent intent = new Intent(this, BoardActivity.class);
startActivity(intent);
finish();
}
private void editTextChatChange(String content) {
if (content.length() == 0) {
mBtChat.setClickable(false);
} else {
mBtChat.setClickable(true);
}
}
public void updatePerson() {
ArrayList<PlayerModel> listPlayerInBoard = mCurrentGameInfo.mListPlayerInGame;
final String[] ListPlayers = new String[listPlayerInBoard.size()];
for (int i = 0; i < ListPlayers.length; i++) {
ListPlayers[i] = "[" + listPlayerInBoard.get(i).ID + "]"
+ listPlayerInBoard.get(i).name;
Achievement achievement = mCurrentGameInfo.mHashAchievement
.get(listPlayerInBoard.get(i).name);
if (achievement != null) {
ListPlayers[i] += " - Win:" + achievement.winnumber;
}
}
mListViewPlayerInBoard.setAdapter(new ImageAdapter(
WaitingActivity.this, ListPlayers));
}
public void updateGold() {
mCurrenGold = mCurrentGameInfo.gold;
for (EnemyType enemy : listEnemyChossen) {
mCurrenGold -= enemy.cost;
}
}
private void gotoInGame() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(WaitingActivity.this,
HeroWarActivity.class);
startActivity(intent);
finish();
}
});
}
@Override
protected int getRawBackground() {
return R.raw.out_game1 + Utils.RANDOM.nextInt(4);
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/herowar/WaitingActivity.java | Java | oos | 9,270 |
package org.vn.herowar;
import org.vn.constant.CommandClientToServer;
import org.vn.custom.BoardAdapter;
import org.vn.gl.Utils;
import org.vn.model.Board;
import org.vn.network.GlobalMessageHandler.LightWeightMessage;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class BoardActivity extends CoreActiity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.board);
gridViewBoard = (GridView) findViewById(R.id.gridViewBoard);
ImageView bt_gold = (ImageView) findViewById(R.id.bt_gold);
layout_gold = (View) findViewById(R.id.layout_gold);
layout_gold.setVisibility(View.GONE);
bt_refresh = (ImageView) findViewById(R.id.bt_refresh);
bt_refresh.setVisibility(View.GONE);
bt_refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mGS.SYS_BOARD_LIST();
showProgressDialog();
bt_refresh.setVisibility(View.GONE);
}
});
bt_gold.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
layout_gold.setVisibility(View.VISIBLE);
mHandlerTurnOffBtGold.sendMessageDelayed(
mHandlerTurnOffBtGold.obtainMessage(1), 1000);
}
});
layout_gold.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
closeLayoutGold();
return true;
}
});
mGS.SYS_BOARD_LIST();
showProgressDialog();
}
ImageView bt_refresh;
View layout_gold;
Handler mHandlerTurnOffBtRefresh = new Handler() {
@Override
public void handleMessage(Message msg) {
bt_refresh.setVisibility(View.VISIBLE);
}
};
Handler mHandlerTurnOffBtGold = new Handler() {
@Override
public void handleMessage(Message msg) {
closeLayoutGold();
}
};
private static final int DLG_EXIT = 1;
GridView gridViewBoard;
@Override
public void onMessageReceived(LightWeightMessage msg) {
switch (msg.command) {
case CommandClientToServer.LOST_CONNECTION:
onDisconnect();
break;
case CommandClientToServer.SYS_BOARD_LIST:
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
mHandlerTurnOffBtRefresh.removeMessages(1);
mHandlerTurnOffBtRefresh.sendMessageDelayed(
mHandlerTurnOffBtRefresh.obtainMessage(1), 1000);
}
});
updateBoard((Board[]) msg.obj);
break;
case CommandClientToServer.JOIN_BOARD:
dismissProgressDialog();
if (msg.arg1 == 1) {
gotoWaitingActivity();
} else {
showDialogNotification(getString(R.string.JOIN_BOARD_FALL));
}
break;
}
}
public void updateBoard(final Board[] boards) {
runOnUiThread(new Runnable() {
@Override
public void run() {
gridViewBoard.setAdapter(new BoardAdapter(BoardActivity.this,
boards));
gridViewBoard.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v
.findViewById(R.id.grid_item_label))
.getText(), Toast.LENGTH_SHORT).show();
mGS.JOIN_BOARD(boards[position].id);
showProgressDialog();
}
});
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (layout_gold.getVisibility() == View.VISIBLE) {
layout_gold.setVisibility(View.GONE);
} else {
showDialog(DLG_EXIT);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DLG_EXIT:
return new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit))
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface arg0,
int arg1) {
finish();
mGS.LOGOUT();
}
}).setNegativeButton(R.string.dialog_cancel, null)
.create();
}
return super.onCreateDialog(id);
}
private void gotoWaitingActivity() {
Intent intent = new Intent(this, WaitingActivity.class);
startActivity(intent);
finish();
}
private void closeLayoutGold() {
mHandlerTurnOffBtGold.removeMessages(1);
layout_gold.setVisibility(View.GONE);
showToast(getString(R.string.Chuc_nang_cap_nhat_sau));
}
@Override
protected int getRawBackground() {
return R.raw.out_game1 + Utils.RANDOM.nextInt(4);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/herowar/BoardActivity.java | Java | oos | 5,529 |
package org.vn.herowar;
import org.vn.network.GlobalMessageHandler;
import org.vn.network.GlobalMessageHandler.MessageListener;
import org.vn.network.GlobalService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
public abstract class CoreActiity extends Activity implements MessageListener {
protected GlobalService mGS = GlobalService.getInstance();
protected ProgressDialog mDialog;
protected boolean isLoginScreen = false;
MediaPlayer mMediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalMessageHandler.getInstance().addMessageListener(this);
playSound();
}
Handler playSoundHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
playSound();
};
};
private void playSound() {
try {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
}
mMediaPlayer = MediaPlayer.create(CoreActiity.this,
getRawBackground());
mMediaPlayer.setLooping(false);
mMediaPlayer.start();
playSoundHandler.removeMessages(1);
playSoundHandler.sendMessageDelayed(
playSoundHandler.obtainMessage(1),
mMediaPlayer.getDuration());
} catch (Exception e) {
}
}
abstract protected int getRawBackground();
@Override
protected void onResume() {
super.onResume();
try {
if (!isLoginScreen && !mGS.isConnected()) {
onDisconnect();
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
playSoundHandler.removeMessages(1);
}
} else {
if (!mMediaPlayer.isPlaying()) {
playSoundHandler.removeMessages(1);
mMediaPlayer.start();
}
}
} catch (Exception e) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
playSoundHandler.removeMessages(1);
mMediaPlayer.stop();
GlobalMessageHandler.getInstance().removeMessageListener(this);
if (mDialog != null) {
mDialog.dismiss();
}
} catch (Exception e) {
}
}
protected void showDialogNotification(String content) {
new AlertDialog.Builder(this).setMessage(content)
.setPositiveButton(R.string.dialog_ok, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
}).show();
}
public void showToast(final String content) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), content,
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
}
}
protected void showProgressDialog() {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mDialog == null) {
mDialog = new ProgressDialog(CoreActiity.this);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setMessage(getText(R.string.loading));
mDialog.setIndeterminate(true);
mDialog.show();
} else if (!mDialog.isShowing()) {
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setMessage(getText(R.string.loading));
mDialog.setIndeterminate(true);
mDialog.show();
}
}
});
} catch (Exception e) {
}
}
protected void dismissProgressDialog() {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
});
} catch (Exception e) {
}
}
public void onDisconnect() {
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(CoreActiity.this)
.setMessage("Connection lost")
.setCancelable(false)
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface arg0,
int arg1) {
finish();
}
}).show();
}
});
}
@Override
protected void onPause() {
try {
playSoundHandler.removeMessages(1);
mMediaPlayer.pause();
} catch (Exception e) {
}
super.onPause();
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/herowar/CoreActiity.java | Java | oos | 4,428 |
package org.vn.herowar;
import org.vn.cache.CurrentGameInfo;
import org.vn.constant.CommandClientToServer;
import org.vn.custom.ResuftAdapter;
import org.vn.network.GlobalMessageHandler.LightWeightMessage;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ListView;
public class ResuftActivity extends CoreActiity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resuft);
ListView listResuft = (ListView) findViewById(R.id.resuft_item_list);
listResuft.setAdapter(new ResuftAdapter(ResuftActivity.this,
CurrentGameInfo.getIntance().result));
}
@Override
public void onMessageReceived(LightWeightMessage msg) {
switch (msg.command) {
case CommandClientToServer.LOST_CONNECTION:
onDisconnect();
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
runOnUiThread(new Runnable() {
public void run() {
Intent intent = new Intent(ResuftActivity.this,
WaitingActivity.class);
startActivity(intent);
finish();
}
});
return false;
}
@Override
protected int getRawBackground() {
return R.raw.sound_resuft;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/herowar/ResuftActivity.java | Java | oos | 1,286 |
package org.vn.herowar;
import org.vn.cache.CurrentGameInfo;
import org.vn.constant.CommandClientToServer;
import org.vn.constant.Constants;
import org.vn.gl.Utils;
import org.vn.model.Server;
import org.vn.network.GlobalMessageHandler.LightWeightMessage;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends CoreActiity {
private static final int DLG_EXIT = 1;
private TableLayout tableLayoutTaget;
TableLayout tableLayoutRegiter;
TableLayout tableLayoutLogin;
EditText useName;
EditText pass;
EditText useName_re;
EditText pass_re;
EditText pass_re2;
EditText btIp;
EditText btPhone_Number_re;
TextView useName_tv;
TextView pass_tv;
TextView useName_re_tv;
TextView pass_re_tv;
TextView pass_re2_tv;
TextView btIp_tv;
TextView btPhone_Number_re_tv;
TextView ngon_ngu_tv;
Button btLogin;
Button btRegiter;
SharedPreferences mCachePreferences;
String sUsername;
String sPass;
String sIp;
boolean eng;
ImageView ngon_ngu;
private static final int PORT = 12344;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isLoginScreen = true;
CurrentGameInfo.getIntance().listEnemytype.clear();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
btIp = (EditText) findViewById(R.id.editIp);
useName = (EditText) findViewById(R.id.editTextUserName);
pass = (EditText) findViewById(R.id.editTextPass);
useName_re = (EditText) findViewById(R.id.regiterUserName);
pass_re = (EditText) findViewById(R.id.regiterPass);
pass_re2 = (EditText) findViewById(R.id.regiterPass2);
btPhone_Number_re = (EditText) findViewById(R.id.regiterPhone);
btIp_tv = (TextView) findViewById(R.id.editIp_tv);
useName_tv = (TextView) findViewById(R.id.editTextUserNameTv);
pass_tv = (TextView) findViewById(R.id.editTextPassTv);
useName_re_tv = (TextView) findViewById(R.id.regiterUserNameTv);
pass_re_tv = (TextView) findViewById(R.id.regiterPassTv);
pass_re2_tv = (TextView) findViewById(R.id.regiterPass2Tv);
ngon_ngu_tv = (TextView) findViewById(R.id.ngon_nguTv);
btPhone_Number_re_tv = (TextView) findViewById(R.id.regiterPhoneTv);
ngon_ngu = (ImageView) findViewById(R.id.ngon_ngu);
LinearLayout ngon_ngu_lay_out = (LinearLayout) findViewById(R.id.ngon_ngu_layout);
final View bt_facebook = (View) findViewById(R.id.bt_facebook);
final View bt_call = (View) findViewById(R.id.bt_call);
tableLayoutRegiter = (TableLayout) findViewById(R.id.tableRe);
tableLayoutLogin = (TableLayout) findViewById(R.id.tableLogin);
View ip_layout = (View) findViewById(R.id.editIp_layout);
tableLayoutTaget = tableLayoutLogin;
tableLayoutRegiter.setVisibility(View.GONE);
btLogin = (Button) findViewById(R.id.buttonLogin);
btRegiter = (Button) findViewById(R.id.buttonRegiter);
mCachePreferences = getSharedPreferences(Constants.CACHE_PREFERENCES,
MODE_PRIVATE);
sIp = mCachePreferences.getString(Constants.CACHE_IP, "localhost");
btIp.setText(sIp);
if (true) {
sIp = "112.78.1.202";
// sIp = "192.168.0.101";
btIp.setText(sIp);
ip_layout.setVisibility(View.GONE);
}
sUsername = mCachePreferences.getString(Constants.CACHE_USER_NAME,
"test1");
useName.setText(sUsername);
sPass = mCachePreferences.getString(Constants.CACHE_PASS, "t");
pass.setText(sPass);
btLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (!checkInternet()) {
return;
}
if (tableLayoutTaget != tableLayoutLogin) {
tableLayoutTaget = tableLayoutLogin;
tableLayoutLogin.setVisibility(View.VISIBLE);
tableLayoutRegiter.setVisibility(View.GONE);
return;
}
if (sIp.compareTo(btIp.getText().toString()) != 0) {
Editor editor = mCachePreferences.edit();
editor.putString(Constants.CACHE_IP, btIp.getText()
.toString());
editor.commit();
sIp = btIp.getText().toString();
}
doLogin(btIp.getText().toString(),
useName.getText().toString(), pass.getText().toString());
}
});
btRegiter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (!checkInternet()) {
return;
}
if (tableLayoutTaget != tableLayoutRegiter) {
tableLayoutTaget = tableLayoutRegiter;
tableLayoutRegiter.setVisibility(View.VISIBLE);
tableLayoutLogin.setVisibility(View.GONE);
return;
}
doRegiter(btIp.getText().toString(), useName_re.getText()
.toString(), pass_re.getText().toString(),
btPhone_Number_re.getText().toString());
}
});
bt_facebook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showProgressDialog();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com.vn/"));
startActivity(intent);
}
});
bt_call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showProgressDialog();
Utils.callSupport(LoginActivity.this, "01218816208");
}
});
eng = mCachePreferences.getBoolean(Constants.CACHE_Lang, true);
updateNgonNgu();
ngon_ngu_lay_out.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
eng = eng == false;
Editor editor = mCachePreferences.edit();
editor.putBoolean(Constants.CACHE_Lang, eng);
editor.commit();
updateNgonNgu();
}
});
checkInternet();
}
public boolean checkInternet() {
boolean isInternetConnection = Utils
.checkInternetConnection(LoginActivity.this);
if (!isInternetConnection) {
AlertDialog alertDialog = new AlertDialog.Builder(
LoginActivity.this)
.setTitle(R.string.notification)
.setMessage(R.string.network_settings)
.setPositiveButton(R.string.dialog_yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
startActivity(new Intent(
Settings.ACTION_WIRELESS_SETTINGS));
}
}).setNegativeButton(R.string.dialog_no, null)
.create();
alertDialog.show();
}
return isInternetConnection;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showDialog(DLG_EXIT);
return true;
}
return super.onKeyDown(keyCode, event);
}
private void doLogin(final String ip, final String username,
final String pass) {
if (ip.length() == 0) {
showDialogNotification(getString(R.string.login_ip_ko_dc_trong));
} else if (username.length() == 0) {
showDialogNotification(getString(R.string.login_usename_ko_dc_trong));
} else if (pass.length() == 0) {
showDialogNotification(getString(R.string.login_pass_ko_dc_trong));
} else {
// Luu lai thong tin
if (sUsername.compareTo(username) != 0) {
Editor editor = mCachePreferences.edit();
editor.putString(Constants.CACHE_USER_NAME, username);
editor.commit();
sUsername = username;
}
if (sPass.compareTo(pass) != 0) {
Editor editor = mCachePreferences.edit();
editor.putString(Constants.CACHE_PASS, pass);
editor.commit();
sPass = pass;
}
showProgressDialog();
new Thread() {
@Override
public void run() {
Server server = new Server(ip, PORT, "Mặc định");
if (!mGS.isConnected()) {
mGS.connect(server);
}
if (mGS.isConnected()) {
// mGS.LOGIN_TRIAL(username);
mGS.GET_CLIENT_INFO("Android", "##", "0.1",
eng ? (byte) 1 : (byte) 0);
mGS.SYS_LOGIN(username, pass);
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
showDialogNotification(getString(R.string.login_ko_conect_toi_server));
}
});
}
};
}.start();
}
}
private void doRegiter(final String ip, final String username,
final String pass, final String phone_num) {
if (username.length() == 0) {
showDialogNotification(getString(R.string.login_usename_ko_dc_trong));
} else if (pass.length() == 0) {
showDialogNotification(getString(R.string.login_pass_ko_dc_trong));
} else if (pass_re2.getText().toString()
.compareTo(pass_re.getText().toString()) != 0) {
showDialogNotification(getString(R.string.login_pass_re_pass_fail));
} else {
showProgressDialog();
new Thread() {
@Override
public void run() {
Server server = new Server(ip, PORT, "Mặc định");
if (!mGS.isConnected()) {
mGS.connect(server);
}
if (mGS.isConnected()) {
mGS.SYS_REGISTER(username, pass, phone_num);
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
showDialogNotification(getString(R.string.login_ko_conect_toi_server));
}
});
}
};
}.start();
}
}
@Override
public void onMessageReceived(final LightWeightMessage msg) {
switch (msg.command) {
case CommandClientToServer.SYS_REGISTER:
final String info = (String) msg.obj;
if (msg.arg1 == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
// Chuyen tab thanh login lai
if (tableLayoutTaget != tableLayoutLogin) {
tableLayoutTaget = tableLayoutLogin;
tableLayoutLogin.setVisibility(View.VISIBLE);
tableLayoutRegiter.setVisibility(View.GONE);
}
// Luu lai thong tin login
{
useName.setText(useName_re.getText().toString());
pass.setText(pass_re.getText().toString());
}
new AlertDialog.Builder(LoginActivity.this)
.setMessage(info)
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(
DialogInterface arg0,
int arg1) {
doLogin(btIp.getText()
.toString(), useName_re
.getText().toString(),
pass_re.getText()
.toString());
}
}).show();
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(info)
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(
DialogInterface arg0,
int arg1) {
}
}).show();
}
});
}
break;
case CommandClientToServer.SYS_LOGIN:
if (msg.arg1 == 1) {
mGS.SET_GAME_TYPE((byte) 1);
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
showDialogNotification(getString(R.string.login_saipass_hoacid));
}
});
}
break;
case CommandClientToServer.SET_GAME_TYPE:
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
gotoBoard();
}
});
break;
case CommandClientToServer.LOST_CONNECTION:
runOnUiThread(new Runnable() {
@Override
public void run() {
dismissProgressDialog();
// showDialogNotification(getString(R.string.login_saipass_hoacid));
}
});
break;
case CommandClientToServer.SERVER_MESSAGE:
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), (String) msg.obj,
Toast.LENGTH_SHORT).show();
}
});
break;
default:
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DLG_EXIT:
return new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit))
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface arg0,
int arg1) {
finish();
}
}).setNegativeButton(R.string.dialog_cancel, null)
.create();
}
return super.onCreateDialog(id);
}
private void gotoBoard() {
Intent intent = new Intent(this, BoardActivity.class);
startActivity(intent);
// finish();
}
@Override
protected void onResume() {
super.onResume();
dismissProgressDialog();
}
private void updateNgonNgu() {
if (eng) {
ngon_ngu.setBackgroundResource(R.drawable.en);
Utils.setLocaleEng(this);
ngon_ngu_tv.setText(R.string.Eng);
} else {
ngon_ngu.setBackgroundResource(R.drawable.vn);
Utils.setLocaleVn(this);
ngon_ngu_tv.setText(R.string.Vn);
}
btIp.setHint(R.string.Ip);// @string/Ip
useName.setHint(R.string.login_userName);// @string/login_userName
pass.setHint(R.string.login_pass);// @string/login_pass
useName_re.setHint(R.string.login_userName);// @string/login_userName
pass_re.setHint(R.string.login_pass);// @string/login_pass
pass_re2.setHint(R.string.login_re_pass);// @string/login_re_pass
btPhone_Number_re.setHint(R.string.Phone_Number);// @string/Phone_Number
btIp_tv.setText(R.string.Ip);// @string/Ip
useName_tv.setText(R.string.login_userName);// @string/login_userName
pass_tv.setText(R.string.login_pass);// @string/login_pass
useName_re_tv.setText(R.string.login_userName);// @string/login_userName
pass_re_tv.setText(R.string.login_pass);// @string/login_pass
pass_re2_tv.setText(R.string.login_re_pass);// @string/login_re_pass
btPhone_Number_re_tv.setText(R.string.Phone_Number);// @string/Phone_Number
btLogin.setText(R.string.Login);
btRegiter.setText(R.string.Regiter);
if (mGS.isConnected()) {
mGS.GET_CLIENT_INFO("Android", "##",
getString(R.string.version_client), eng ? (byte) 1
: (byte) 0);
}
}
@Override
protected int getRawBackground() {
return R.raw.out_game1 + Utils.RANDOM.nextInt(4);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mGS.isConnected()) {
mGS.close();
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/herowar/LoginActivity.java | Java | oos | 15,242 |
package org.vn.herowar;
import org.vn.cache.CurrentGameInfo;
import org.vn.cache.CurrentUserInfo;
import org.vn.constant.CommandClientToServer;
import org.vn.gl.BaseObject;
import org.vn.gl.DebugLog;
import org.vn.gl.DeviceInfo;
import org.vn.gl.GLSurfaceView;
import org.vn.gl.Game;
import org.vn.gl.GameInfo;
import org.vn.gl.Utils;
import org.vn.model.NextTurnMessage;
import org.vn.model.PlayerModel;
import org.vn.network.GlobalMessageHandler.LightWeightMessage;
import org.vn.unit.ActionList;
import org.vn.unit.ActionServerToClient.ActionType;
import org.vn.unit.InputGameInterface.OnEndgameListener;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class HeroWarActivity extends CoreActiity {
private static final int DIALOG_GAME_CONFIRM = 1;
// public static final int QUIT_GAME_DIALOG = 0;
// public static final int VERSION = 14;
// public static final int MAGESRIKEACTIVITY = 0;
public static final int DISCONECT = 1;
public static final int BOARDLISTACTIVITY = 2;
public static final int RESULT = 3;
public static final int WAITINGACTIVITY = 4;
private GLSurfaceView mGLSurfaceView;
private Game mGame;
private long mLastTouchTime = 0L;
private OnEndgameListener onEndgameListener;
private MediaPlayer mMediaPlayer;
private LinearLayout mLayoutChat;
private Button mBtChat;
private EditText mEditTextChat;
private int mFlagActivityGoto = -1;
private CurrentGameInfo mCurrentGameInfo = CurrentGameInfo.getIntance();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
{
mLayoutChat = (LinearLayout) findViewById(R.id.layout_chat);
mBtChat = (Button) findViewById(R.id.button_chat);
mEditTextChat = (EditText) findViewById(R.id.editText_chat);
mLayoutChat.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
chatAll(mEditTextChat.getText().toString());
turnOffChat();
return false;
}
return false;
}
});
mLayoutChat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
turnOffChat();
}
});
mEditTextChat
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event != null) {
switch (event.getAction()) {
case KeyEvent.KEYCODE_ENTER:
case EditorInfo.IME_ACTION_DONE:
chatAll(mEditTextChat.getText().toString());
turnOffChat();
return false;
}
}
switch (actionId) {
case KeyEvent.KEYCODE_ENTER:
case EditorInfo.IME_ACTION_DONE:
chatAll(mEditTextChat.getText().toString());
turnOffChat();
return false;
}
return false;
}
});
mEditTextChat.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
chatAll(mEditTextChat.getText().toString());
turnOffChat();
return false;
}
return false;
}
});
mEditTextChat.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View arg0, boolean arg1) {
if (!arg1) {
chatAll(mEditTextChat.getText().toString());
turnOffChat();
}
}
});
mBtChat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chatAll(mEditTextChat.getText().toString());
turnOffChat();
}
});
}
mGLSurfaceView = (GLSurfaceView) findViewById(R.id.glsurfaceview);
configGame();
mGame = new Game();
mGame.setSurfaceView(mGLSurfaceView);
try {
/*
* Nếu là lần đầu vào màn hình này thì hiện bảng hướng dẫn lên
*/
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
DeviceInfo.DEVICE_WIDTH = dm.widthPixels;
DeviceInfo.DEVICE_HEIGHT = dm.heightPixels;
mGame.bootstrap(this, dm.widthPixels, dm.heightPixels,
GameInfo.DEFAULT_WIDTH, GameInfo.DEFAULT_HEIGHT);
} catch (Exception e) {
Toast.makeText(HeroWarActivity.this, "Game error",
Toast.LENGTH_LONG).show();
finish();
return;
}
mGLSurfaceView.setRenderer(mGame.getRenderer());
onEndgameListener = new OnEndgameListener() {
@Override
public void onEndgameListener() {
endGame(RESULT);
}
// Return back the waiting screen
@Override
public void onGLDeletedListener() {
switch (mFlagActivityGoto) {
case DISCONECT:
break;
case RESULT:
// mGS.LEAVE_BOARD();
runOnUiThread(new Runnable() {
public void run() {
Intent intent = new Intent(HeroWarActivity.this,
ResuftActivity.class);
startActivity(intent);
}
});
break;
case BOARDLISTACTIVITY:
// mGS.EXIT_BOARD(CurrentGameInfo.getIntance().boardId);
mGS.LEAVE_BOARD();
runOnUiThread(new Runnable() {
public void run() {
Intent intent = new Intent(HeroWarActivity.this,
BoardActivity.class);
startActivity(intent);
}
});
break;
case WAITINGACTIVITY:
runOnUiThread(new Runnable() {
public void run() {
Intent intent = new Intent(HeroWarActivity.this,
WaitingActivity.class);
startActivity(intent);
}
});
break;
}
mediaStop();
if (mGame != null) {
mGame.stop();
mGame = null;
}
finish();
}
@Override
public void LoadingUnitComplete() {
}
@Override
public void turnOnchat() {
runOnUiThread(new Runnable() {
public void run() {
mEditTextChat.setText("");
mLayoutChat.setVisibility(View.VISIBLE);
InputMethodManager imm = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);
mEditTextChat.requestFocus();
imm.showSoftInput(mEditTextChat, 0);
}
});
}
};
BaseObject.sSystemRegistry.inputGameInterface
.setOnSelectedItemListener(onEndgameListener);
showToast(getString(R.string.infor_before_the_game));
}
private void configGame() {
mGLSurfaceView.setEGLConfigChooser(false);
}
@Override
protected void onPause() {
super.onPause();
try {
if (mGame != null) {
mGame.onPause();
mGame.getRenderer().onPause();
}
if (mGLSurfaceView != null)
mGLSurfaceView.onPause();
// hack!
if (mMediaPlayer != null) {
mMediaPlayer.pause();
}
} catch (Exception e) {
DebugLog.e("MageStrike", "onPause()");
}
}
@Override
protected void onResume() {
super.onResume();
try {
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Preferences may have changed while we were paused.
if (mGLSurfaceView != null)
mGLSurfaceView.onResume();
if (mGame != null) {
mGame.setSoundEnabled(GameInfo.ENABLE_SOUND);
mGame.onResume(this, false);
}
// Mở nhạc nền
if (GameInfo.ENABLE_SOUND == true && mMediaPlayer != null
&& mMediaPlayer.isPlaying() == false) {
try {
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
DebugLog.e("MageStrike", "onResume()");
}
}
@Override
protected void onDestroy() {
try {
mediaStop();
} catch (Exception e) {
DebugLog.e("MageStrike", "onDestroy()");
}
super.onDestroy();
}
private void mediaStop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_GAME_CONFIRM:
return new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit))
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
endGame(BOARDLISTACTIVITY);
}
}).setNegativeButton(R.string.dialog_cancel, null)
.create();
default:
break;
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
default:
break;
}
super.onPrepareDialog(id, dialog);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mGame != null && mGame.isBootstrapComplete() && !mGame.isPaused()
&& BaseObject.sSystemRegistry != null) {
mGame.onTouchEvent(event);
if (BaseObject.sSystemRegistry.inputGameInterface != null)
BaseObject.sSystemRegistry.inputGameInterface.dumpEvent(event);
// BaseObject.sSystemRegistry.inputGameInterface.onTouchEvent(event);
final long time = System.currentTimeMillis();
if (event.getAction() == MotionEvent.ACTION_MOVE
&& time - mLastTouchTime < 32) {
// Sleep so that the main thread doesn't get flooded with UI
// events.
try {
Thread.sleep(32);
} catch (InterruptedException e) {
}
mGame.getRenderer().waitDrawingComplete();
}
mLastTouchTime = time;
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
showDialog(DIALOG_GAME_CONFIRM);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyUp(keyCode, event);
}
public void endGame(int flagActivityGoto) {
if (mGame != null && BaseObject.sSystemRegistry != null) {
mFlagActivityGoto = flagActivityGoto;
mGame.stopGL();
}
mediaStop();
}
public void turnOffChat() {
try {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditTextChat.getWindowToken(), 0);
mLayoutChat.setVisibility(View.GONE);
BaseObject.sSystemRegistry.inputGameInterface.turnOffChat();
} catch (Exception e) {
e.printStackTrace();
}
}
public void chatAll(String content) {
if (content.length() > 0) {
mGS.CHAT_BOARD(content);
}
}
@Override
public void onMessageReceived(final LightWeightMessage msg) {
switch (msg.command) {
case CommandClientToServer.LOST_CONNECTION:
onDisconnect();
break;
case CommandClientToServer.ARMY_SELECTION:
mGS.LAYOUT_ARMY(BaseObject.sSystemRegistry.characterManager.arrayCharactersMyTeam);
break;
case CommandClientToServer.LAYOUT_ARMY:
if (mCurrentGameInfo.isHost()) {
mGS.START_GAME();
} else {
mGS.READY();
}
break;
case CommandClientToServer.SOMEONE_JOIN_BOARD:
showToast(getString(R.string.join_in_game, (String) msg.obj));
// updateStatusBoard();
break;
case CommandClientToServer.SOMEONE_LEAVE_BOARD:
showToast(getString(R.string.leave_in_game, (String) msg.obj));
// updateStatusBoard();
if (msg.arg1 == 1) {
// Go to waiting
endGame(WAITINGACTIVITY);
}
break;
case CommandClientToServer.MOVE_ARMY:
// MoveMessage moveMessage = (MoveMessage) msg.obj;
break;
case CommandClientToServer.ATTACH:
// AttackMessage atackMessage = (AttackMessage) msg.obj;
break;
case CommandClientToServer.NEXT_TURN:
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
NextTurnMessage nextTurnMessage = (NextTurnMessage) msg.obj;
for (PlayerModel playerModel : mCurrentGameInfo.mListPlayerInGame) {
if (nextTurnMessage.idPlayerInTurnNext == playerModel.ID) {
if (playerModel.ID == CurrentUserInfo.mPlayerInfo.ID) {
showToast(getString(R.string.next_you_turn));
} else {
showToast(getString(R.string.next_turn,
playerModel.name));
}
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
break;
case CommandClientToServer.CHAT_BOARD:
if (mGame.isBootstrapComplete() && !mGame.isPaused()) {
if (CurrentUserInfo.mPlayerInfo.ID == msg.arg1) {
BaseObject.sSystemRegistry.unitSreen
.inputChatRight_Bot((String) msg.obj);
} else {
BaseObject.sSystemRegistry.unitSreen
.inputChatLeft_Bot((String) msg.obj);
}
}
break;
case CommandClientToServer.END_GAME:
break;
}
}
// private void updateStatusBoard() {
// if (mCurrentGameInfo.isInGame) {
// return;
// }
// if (mCurrentGameInfo.isHost()) {
// if (mCurrentGameInfo.isReadyAll()) {
// if (BaseObject.sSystemRegistry != null) {
// BaseObject.sSystemRegistry.dialogAddEnemy
// .setIsEnableReady(true);
// }
// } else {
// if (BaseObject.sSystemRegistry != null) {
// BaseObject.sSystemRegistry.dialogAddEnemy
// .setIsEnableReady(false);
// }
// }
// } else {
// if (mCurrentGameInfo.isIReady()) {
// if (BaseObject.sSystemRegistry != null) {
// BaseObject.sSystemRegistry.dialogAddEnemy
// .setIsEnableReady(true);
// }
// } else {
// if (BaseObject.sSystemRegistry != null) {
// BaseObject.sSystemRegistry.dialogAddEnemy
// .setIsEnableReady(false);
// }
// }
// }
// }
@Override
public void onDisconnect() {
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(HeroWarActivity.this)
.setMessage("Connection lost")
.setCancelable(false)
.setPositiveButton(R.string.dialog_ok,
new OnClickListener() {
@Override
public void onClick(DialogInterface arg0,
int arg1) {
endGame(DISCONECT);
}
}).show();
}
});
}
@Override
protected int getRawBackground() {
return R.raw.ingame1 + Utils.RANDOM.nextInt(3);
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/herowar/HeroWarActivity.java | Java | oos | 15,301 |
package org.vn.constant;
public class CommandClientToServer {
public static final byte LOST_CONNECTION = -1;
public static final byte SYS_LOGIN = 1;
public static final byte SYS_REGISTER = 2;
public static final byte SYS_BOARD_LIST = 3;
public static final byte JOIN_BOARD = 4;
public static final byte GET_CLIENT_INFO = 5;
public static final byte SOMEONE_JOIN_BOARD = 6;
public static final byte EXIT_BOARD = 7;
public static final byte SET_GAME_TYPE = 8;
public static final byte CHAT_BOARD = 9;
public static final byte GET_USER_INFO = 10;
public static final byte GET_ARMY_SHOP = 11;
public static final byte ARMY_SELECTION = 12;
public static final byte SOMEONE_LEAVE_BOARD = 13;
public static final byte LEAVE_BOARD = 14;
public static final byte GET_MAP = 16;
public static final byte LAYOUT_ARMY = 17;
public static final byte MOVE_ARMY = 18;
public static final byte READY = 19;
public static final byte GET_ALL_MAP = 21;
public static final byte SET_MAP = 22;
public static final byte START_GAME = 20;
public static final byte ATTACH = 23;
public static final byte NEXT_TURN = 24;
public static final byte LOGIN_TRIAL = 26;
public static final byte SERVER_MESSAGE = 27;
public static final byte END_GAME = 25;
public static final byte SET_FOG = 26;
public static final byte BUY_SOLDIER_INGAME = 33;
/** sud */
public static final byte MONEY = 35;
public static final byte MONEY_UPDATE = 0;
public final static byte ACHIEVEMENT = 36;
public final static byte LOGOUT = 15;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/constant/CommandClientToServer.java | Java | oos | 1,563 |
package org.vn.constant;
public class Constants {
public static String CACHE_PREFERENCES = "cache_pref";
public static String PREF_SETTINGS_LANGUAGE = "cache_lang";
public static String CACHE_IP = "cache_ip";
public static String CACHE_USER_NAME = "cache_user_name";
public static String CACHE_PASS = "cache_pass";
public static String CACHE_Lang = "cache_lang";
public static final String VI_LANGUAGE = "vie";
public static final String EN_LANGUAGE = "eng";
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/constant/Constants.java | Java | oos | 486 |
package org.vn.gl;
import org.vn.cache.CurrentGameInfo;
import org.vn.gl.game.CameraSystem;
import org.vn.herowar.CoreActiity;
import org.vn.herowar.R;
import org.vn.model.EnemyType;
import org.vn.unit.CharacterManager;
import org.vn.unit.DialogAddEnemy;
import org.vn.unit.InputGameInterface;
import org.vn.unit.LogicMap;
import org.vn.unit.MapTiles;
import org.vn.unit.NumberDrawable;
import org.vn.unit.SoundManager;
import org.vn.unit.Tile;
import org.vn.unit.UnitCharacterSwordmen;
import org.vn.unit.UnitEffects;
import org.vn.unit.UnitSreen;
import android.content.Context;
import android.view.MotionEvent;
/**
* High-level setup object for the AndouKun game engine. This class sets up the
* core game engine objects and threads. It also passes events to the game
* thread from the main UI thread.
*/
public class Game extends AllocationGuard {
private GameThread mGameThread;
private Thread mGame;
public MainLoop mGameRoot;
private GameRenderer mRenderer;
private GLSurfaceView mSurfaceView;
private boolean mRunning;
private boolean mBootstrapComplete;
private boolean mLoadingUnitComplete;
private boolean mGLDataLoaded;
private ContextParameters mContextParameters;
private MultiTouchFilter2 mTouchFilter2;
public Game() {
super();
if (BaseObject.sSystemRegistry == null) {
BaseObject.sSystemRegistry = new ObjectRegistry();
}
mRunning = false;
mBootstrapComplete = false;
mContextParameters = new ContextParameters();
mGLDataLoaded = false;
mLoadingUnitComplete = false;
}
/**
* Creates core game objects and constructs the game engine object graph.
* Note that the game does not actually begin running after this function is
* called (see start() below). Also note that textures are not loaded from
* the resource pack by this function, as OpenGl isn't yet available.
*
* @param context
*/
public void bootstrap(CoreActiity context, int viewWidth, int viewHeight,
int gameWidth, int gameHeight) throws Exception {
if (!mBootstrapComplete) {
mRenderer = new GameRenderer(context, this, viewWidth, viewHeight);
ContextParameters params = mContextParameters;
params.viewWidth = viewWidth;
params.viewHeight = viewHeight;
params.gameWidth = gameWidth;
params.gameHeight = gameHeight;
params.viewScaleX = (float) viewWidth / gameWidth;
params.viewScaleY = (float) viewHeight / gameHeight;
params.context = context;
BaseObject.sSystemRegistry.contextParameters = params;
mTouchFilter2 = new MultiTouchFilter2();
BaseObject.sSystemRegistry.multiTouchFilter2 = mTouchFilter2;
BaseObject.sSystemRegistry.soundSystem = new SoundSystem();
BaseObject.sSystemRegistry.soundManager = new SoundManager();
// Long-term textures persist between levels.
TextureLibrary longTermTextureLibrary = new TextureLibrary();
BaseObject.sSystemRegistry.longTermTextureLibrary = longTermTextureLibrary;
MainLoop gameRoot = new MainLoop();
mGameRoot = gameRoot;
RenderSystem renderer = new RenderSystem();
BaseObject.sSystemRegistry.renderSystem = renderer;
// InputGameInterface
{
InputGameInterface inputInterface = new InputGameInterface(
longTermTextureLibrary);
BaseObject.sSystemRegistry.inputGameInterface = inputInterface;
}
}
}
private void LoadingUnit(Context context,
final TextureLibrary longTermTextureLibrary, final MainLoop gameRoot) {
// WindowManager windowMgr = (WindowManager) context
// .getSystemService(Context.WINDOW_SERVICE);
// int rotationIndex = windowMgr.getDefaultDisplay().getOrientation();
// InputGameInterface
{
gameRoot.add(BaseObject.sSystemRegistry.inputGameInterface);
}
// CameraSystem
final CurrentGameInfo mCurrentGameInfo = CurrentGameInfo.getIntance();
int widthtTileMap;
int heightTileMap;
widthtTileMap = mCurrentGameInfo.mMapSelected.mapType.row;
heightTileMap = mCurrentGameInfo.mMapSelected.mapType.column;
float offset = GameInfo.offset;
float offsetMap = GameInfo.offsetMap;
float xMap = -MapTiles.getPosXUnit(0, heightTileMap, offset);
float widthMap = offsetMap * 2 + xMap + widthtTileMap * offset - offset
/ 2;
float heightMap = offsetMap * 2 + (heightTileMap - 1) * offset - offset
* 3 / 4;
{
CameraSystem camera = new CameraSystem(longTermTextureLibrary,
widthMap, heightMap);
BaseObject.sSystemRegistry.cameraSystem = camera;
gameRoot.add(camera);
}
{
DialogAddEnemy dialogAddEnemy = new DialogAddEnemy(
longTermTextureLibrary) {
@Override
public void addEnemyAt(Tile tile, EnemyType enemyType) {
UnitCharacterSwordmen myKing = BaseObject.sSystemRegistry.characterManager.myKing;
if (!UnitCharacterSwordmen
.isInSight(myKing.mTileTaget.xTile,
myKing.mTileTaget.yTile, tile.xTile,
tile.yTile, myKing.mEnemyType.rangeview)) {
BaseObject.sSystemRegistry.contextParameters.context
.showToast(BaseObject.sSystemRegistry.contextParameters.context
.getString(R.string.dat_linh_trong_vung_sang));
} else {
if (mMoney - enemyType.cost >= 0) {
setVisible(false);
if (!BaseObject.sSystemRegistry.logicMap.mArrayMap[tile.yTile][tile.xTile]) {
BaseObject.sSystemRegistry.mGS
.BUY_SOLDIER_INGAME(enemyType.armyType,
tile.xTile, tile.yTile);
BaseObject.sSystemRegistry.contextParameters.context
.showToast(BaseObject.sSystemRegistry.contextParameters.context
.getString(R.string.Request_buy_enemy));
} else {
DebugLog.e("DUC",
"Khoi tao character tai 1 vi tri ko di chuyen dc");
}
} else {
BaseObject.sSystemRegistry.contextParameters.context
.showToast(BaseObject.sSystemRegistry.contextParameters.context
.getString(R.string.Dont_enought_money));
}
}
}
};
BaseObject.sSystemRegistry.dialogAddEnemy = dialogAddEnemy;
gameRoot.add(dialogAddEnemy);
}
// Map
{
// Khoi tao vi tri hien thi cua map
BaseObject.sSystemRegistry.mapTiles = new MapTiles(
longTermTextureLibrary, widthtTileMap, heightTileMap,
offset, offsetMap + xMap, offsetMap + offset / 2);
gameRoot.add(BaseObject.sSystemRegistry.mapTiles);
// Khoi tao viec cho phep di hay khong tren logic map
BaseObject.sSystemRegistry.logicMap = new LogicMap(widthtTileMap,
heightTileMap,
mCurrentGameInfo.mMapSelected.mapType.mapType,
R.drawable.back_ground_alpha);
}
// Effect
{
UnitEffects unitEffects = new UnitEffects(longTermTextureLibrary);
BaseObject.sSystemRegistry.unitEffects = unitEffects;
gameRoot.add(unitEffects);
}
// Character
BaseObject.sSystemRegistry.characterManager = new CharacterManager();
gameRoot.add(BaseObject.sSystemRegistry.characterManager);
// for (Enemy enemy : mCurrentGameInfo.listIdEnemyInMap) {
// if
// (!BaseObject.sSystemRegistry.logicMap.mArrayMap[enemy.yTile][enemy.xTile])
// {
// UnitCharacter character = new UnitCharacterSwordmen(
// longTermTextureLibrary,
// BaseObject.sSystemRegistry.mapTiles.arrayMap[enemy.yTile][enemy.xTile],
// enemy.playerId == CurrentUserInfo.mPlayerInfo.ID,
// enemy.getEnemyType(), enemy.armyId);
// } else {
// DebugLog.e("DUC",
// "Khoi tao character tai 1 vi tri ko di chuyen dc");
// }
// }
// Add My King
for (EnemyType enemyType : mCurrentGameInfo.listEnemytype) {
if (enemyType.armyType == GameInfo.idTypeKing) {
BaseObject.sSystemRegistry.mGS.BUY_SOLDIER_INGAME(
enemyType.armyType, mCurrentGameInfo.xTileKing,
mCurrentGameInfo.yTileKing);
break;
}
}
{
BaseObject.sSystemRegistry.numberDrawableTime = new NumberDrawable(
longTermTextureLibrary, 256, 256, 256, 256, 40, 40,
NumberDrawable.idDrawableNumber2);
BaseObject.sSystemRegistry.numberDrawableTimeInTurn = new NumberDrawable(
longTermTextureLibrary, 256, 256, 256, 256, 60, 60,
NumberDrawable.idDrawableNumber2);
BaseObject.sSystemRegistry.numberDrawableTakeDame = new NumberDrawable(
longTermTextureLibrary, 256, 256, 256, 256, 34, 34,
NumberDrawable.idDrawableNumber2);
BaseObject.sSystemRegistry.numberDrawableCostInDialogAddEnemy = new NumberDrawable(
longTermTextureLibrary, 256, 256, 256, 256, 30, 30,
NumberDrawable.idDrawableNumber2);
}
// Sreen
{
UnitSreen unitSreen = new UnitSreen(longTermTextureLibrary);
BaseObject.sSystemRegistry.unitSreen = unitSreen;
gameRoot.add(unitSreen);
}
// GameThread
{
mGameThread = new GameThread(mRenderer);
mGameThread.setGameRoot(mGameRoot);
}
mBootstrapComplete = true;
}
/** Starts the game running. */
public void start() {
if (!mRunning) {
assert mGame == null;
// 11072011, ChinhQT: reclaim the memory
System.gc();
mGame = new Thread(mGameThread);
mGame.setName("Game");
mGame.start();
mRunning = true;
AllocationGuard.sGuardActive = false;
} else {
mGameThread.resumeGame();
}
}
public void stop() {
try {
BaseObject.sSystemRegistry.soundSystem.stopAll();
if (mGameThread != null) {
mGameThread.stopGame();
}
mRunning = false;
AllocationGuard.sGuardActive = false;
BaseObject.sSystemRegistry.longTermTextureLibrary.removeAll();
mSurfaceView.flushAll();
mSurfaceView.destroyDrawingCache();
mSurfaceView = null;
BaseObject.sSystemRegistry.onDestroy();
BaseObject.sSystemRegistry = null;
// if (mGame != null) {
// try {
// mGame.join();
// mGame.interrupt();
// } catch (InterruptedException e) {
// mGame.interrupt();
// }
// }
mGame = null;
} catch (Exception error) {
} finally {
System.gc();
}
}
public void CallbackRequested() {
mSurfaceView
.flushTextures(BaseObject.sSystemRegistry.longTermTextureLibrary);
}
public void stopGL() {
mRenderer.requestCallback();
BaseObject.sSystemRegistry.soundSystem.stopAll();
}
public GameRenderer getRenderer() {
return mRenderer;
}
public void onPause() {
if (mRunning) {
mGameThread.pauseGame();
}
}
public void onResume(CoreActiity context, boolean force) {
if (force && mRunning) {
mGameThread.resumeGame();
} else {
mRenderer.setContext(context);
// Don't explicitly resume the game here. We'll do that in
// the SurfaceReady() callback, which will prevent the game
// starting before the render thread is ready to go.
BaseObject.sSystemRegistry.contextParameters.context = context;
}
}
public void onSurfaceReady() {
DebugLog.d("DUC", "onSurfaceReady");
if (mLoadingUnitComplete == false) {
LoadingUnit(BaseObject.sSystemRegistry.contextParameters.context,
BaseObject.sSystemRegistry.longTermTextureLibrary,
mGameRoot);
mLoadingUnitComplete = true;
}
start();
mGameThread.pauseGame();
if (!mGLDataLoaded && mGameThread.getPaused() && mRunning) {
mRenderer.setContext(mContextParameters.context);
mSurfaceView
.loadTextures(BaseObject.sSystemRegistry.longTermTextureLibrary);
TimeSystem time = BaseObject.sSystemRegistry.timeSystem;
time.reset();
mGLDataLoaded = true;
}
mGameThread.resumeGame();
ContextParameters params = mContextParameters;
params.viewWidth = mSurfaceView.getWidth();
params.viewHeight = mSurfaceView.getHeight();
params.viewScaleX = (float) params.viewWidth / params.gameWidth;
params.viewScaleY = (float) params.viewHeight / params.gameHeight;
BaseObject.sSystemRegistry.cameraSystem.setScaleNow();
mRenderer.setWidthHeight(params.viewWidth, params.viewHeight);
BaseObject.sSystemRegistry.inputGameInterface.sendLoadingDone();
}
public void setSurfaceView(GLSurfaceView view) {
mSurfaceView = view;
}
public void onSurfaceLost() {
mSurfaceView
.flushTextures(BaseObject.sSystemRegistry.longTermTextureLibrary);
BaseObject.sSystemRegistry.longTermTextureLibrary.invalidateAll();
mGLDataLoaded = false;
}
public void onSurfaceCreated() {
}
public void setSoundEnabled(boolean soundEnabled) {
BaseObject.sSystemRegistry.soundSystem.setSoundEnabled(soundEnabled);
}
public void setSafeMode(boolean safe) {
mSurfaceView.setSafeMode(safe);
}
public float getGameTime() {
return BaseObject.sSystemRegistry.timeSystem.getGameTime();
}
public boolean isPaused() {
return (mRunning && mGameThread != null && mGameThread.getPaused());
}
public boolean onTouchEvent(MotionEvent event) {
if (mRunning) {
mTouchFilter2.onTouchEvent(event);
}
return true;
}
public boolean isBootstrapComplete() {
return mBootstrapComplete;
}
private void addMyKing(TextureLibrary textureLibrary, int xTile, int yTile,
EnemyType enemyType) {
if (!BaseObject.sSystemRegistry.logicMap.mArrayMap[yTile][xTile]) {
BaseObject.sSystemRegistry.characterManager.myKing = new UnitCharacterSwordmen(
textureLibrary,
BaseObject.sSystemRegistry.mapTiles.arrayMap[yTile][xTile],
true, enemyType, -1);
} else {
DebugLog.e("DUC",
"Khoi tao character tai 1 vi tri ko di chuyen dc");
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Game.java | Java | oos | 13,427 |
package org.vn.gl;
/**
* A general-purpose pool of objects. Objects in the pool are allocated up front
* and then passed out to requesting objects until the pool is exhausted (at
* which point an error is thrown). Code that requests objects from the pool
* should return them to the pool when they are finished. This class is
* abstract; derivations need to implement the fill() function to fill the pool,
* and may wish to override release() to clear state on objects as they are
* returned to the pool.
*/
public abstract class ObjectPool extends BaseObject {
private FixedSizeArray<Object> mAvailable;
private int mSize;
private static final int DEFAULT_SIZE = 32;
public ObjectPool() {
super();
setSize(DEFAULT_SIZE);
}
public ObjectPool(int size) {
super();
setSize(size);
}
@Override
public void reset() {
}
/** Allocates an object from the pool */
protected Object allocate() {
Object result = mAvailable.removeLast();
assert result != null : "Object pool of type "
+ this.getClass().getSimpleName() + " exhausted!!";
return result;
}
/** Returns an object to the pool. */
public void release(Object entry) {
mAvailable.add(entry);
}
/**
* Returns the number of pooled elements that have been allocated but not
* released.
*/
public int getAllocatedCount() {
return mAvailable.getCapacity() - mAvailable.getCount();
}
private void setSize(int size) {
mSize = size;
mAvailable = new FixedSizeArray<Object>(mSize);
fill();
}
protected abstract void fill();
protected FixedSizeArray<Object> getAvailable() {
return mAvailable;
}
protected int getSize() {
return mSize;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/ObjectPool.java | Java | oos | 1,735 |
package org.vn.gl;
import java.util.Arrays;
import java.util.Comparator;
/**
* FixedSizeArray is an alternative to a standard Java collection like
* ArrayList. It is designed to provide a contiguous array of fixed length which
* can be accessed, sorted, and searched without requiring any runtime
* allocation. This implementation makes a distinction between the "capacity" of
* an array (the maximum number of objects it can contain) and the "count" of an
* array (the current number of objects inserted into the array). Operations
* such as set() and remove() can only operate on objects that have been
* explicitly add()-ed to the array; that is, indexes larger than getCount() but
* smaller than getCapacity() can't be used on their own.
*
* @param <T>
* The type of object that this array contains.
*/
public class FixedSizeArray<T> extends AllocationGuard {
private final static int LINEAR_SEARCH_CUTOFF = 16;
private final T[] mContents;
private int mCount;
private Comparator<T> mComparator;
private boolean mSorted;
private Sorter<T> mSorter;
public FixedSizeArray(int size) {
super();
assert size > 0;
// Ugh! No generic array construction in Java.
mContents = (T[]) new Object[size];
mCount = 0;
mSorted = false;
mSorter = new StandardSorter<T>();
}
public FixedSizeArray(int size, Comparator<T> comparator) {
super();
assert size > 0;
mContents = (T[]) new Object[size];
mCount = 0;
mComparator = comparator;
mSorted = false;
mSorter = new StandardSorter<T>();
}
/**
* Inserts a new object into the array. If the array is full, an assert is
* thrown and the object is ignored.
*/
public final void add(T object) {
assert mCount < mContents.length : "Array exhausted!";
if (mCount < mContents.length) {
mContents[mCount] = object;
mSorted = false;
mCount++;
}
}
/**
* Searches for an object and removes it from the array if it is found.
* Other indexes in the array are shifted up to fill the space left by the
* removed object. Note that if ignoreComparator is set to true, a linear
* search of object references will be performed. Otherwise, the comparator
* set on this array (if any) will be used to find the object.
*/
public void remove(T object, boolean ignoreComparator) {
final int index = find(object, ignoreComparator);
if (index != -1) {
remove(index);
}
}
/**
* Removes the specified index from the array. Subsequent entries in the
* array are shifted up to fill the space.
*/
public void remove(int index) {
assert index < mCount;
// ugh
if (index < mCount) {
for (int x = index; x < mCount; x++) {
if (x + 1 < mContents.length && x + 1 < mCount) {
mContents[x] = mContents[x + 1];
} else {
mContents[x] = null;
}
}
mCount--;
}
}
/**
* Removes the last element in the array and returns it. This method is
* faster than calling remove(count -1);
*
* @return The contents of the last element in the array.
*/
public T removeLast() {
T object = null;
if (mCount > 0) {
object = mContents[mCount - 1];
mContents[mCount - 1] = null;
mCount--;
}
return object;
}
/**
* Swaps the element at the passed index with the element at the end of the
* array. When followed by removeLast(), this is useful for quickly removing
* array elements.
*/
public void swapWithLast(int index) {
if (mCount > 0 && index < mCount - 1) {
T object = mContents[mCount - 1];
mContents[mCount - 1] = mContents[index];
mContents[index] = object;
mSorted = false;
}
}
/**
* Sets the value of a specific index in the array. An object must have
* already been added to the array at that index for this command to
* complete.
*/
public void set(int index, T object) {
assert index < mCount;
if (index < mCount) {
mContents[index] = object;
}
}
/**
* Clears the contents of the array, releasing all references to objects it
* contains and setting its count to zero.
*/
public void clear() {
for (int x = 0; x < mCount; x++) {
mContents[x] = null;
}
mCount = 0;
mSorted = false;
}
/**
* Returns an entry from the array at the specified index.
*/
public T get(int index) {
assert index < mCount;
T result = null;
if (index < mCount && index >= 0) {
result = mContents[index];
}
return result;
}
/**
* Returns the raw internal array. Exposed here so that tight loops can
* cache this array and walk it without the overhead of repeated function
* calls. Beware that changing this array can leave FixedSizeArray in an
* undefined state, so this function is potentially dangerous and should be
* used in read-only cases.
*
* @return The internal storage array.
*/
public final Object[] getArray() {
return mContents;
}
/**
* Searches the array for the specified object. If the array has been sorted
* with sort(), and if no other order-changing events have occurred since
* the sort (e.g. add()), a binary search will be performed. If a comparator
* has been specified with setComparator(), it will be used to perform the
* search. If not, the default comparator for the object type will be used.
* If the array is unsorted, a linear search is performed. Note that if
* ignoreComparator is set to true, a linear search of object references
* will be performed. Otherwise, the comparator set on this array (if any)
* will be used to find the object.
*
* @param object
* The object to search for.
* @return The index of the object in the array, or -1 if the object is not
* found.
*/
public int find(T object, boolean ignoreComparator) {
int index = -1;
final int count = mCount;
final boolean sorted = mSorted;
final Comparator comparator = mComparator;
final T[] contents = mContents;
if (sorted && !ignoreComparator && count > LINEAR_SEARCH_CUTOFF) {
if (comparator != null) {
index = Arrays.binarySearch(contents, object, comparator);
} else {
index = Arrays.binarySearch(contents, object);
}
// Arrays.binarySearch() returns a negative insertion index if the
// object isn't found,
// but we just want a boolean.
if (index < 0) {
index = -1;
}
} else {
// unsorted, linear search
if (comparator != null && !ignoreComparator) {
for (int x = 0; x < count; x++) {
final int result = comparator.compare(contents[x], object);
if (result == 0) {
index = x;
break;
} else if (result > 0 && sorted) {
// we've passed the object, early out
break;
}
}
} else {
for (int x = 0; x < count; x++) {
if (contents[x] == object) {
index = x;
break;
}
}
}
}
return index;
}
/**
* Sorts the array. If the array is already sorted, no work will be
* performed unless the forceResort parameter is set to true. If a
* comparator has been specified with setComparator(), it will be used for
* the sort; otherwise the object's natural ordering will be used.
*
* @param forceResort
* If set to true, the array will be resorted even if the order
* of the objects in the array has not changed since the last
* sort.
*/
public void sort(boolean forceResort) {
if (!mSorted || forceResort) {
if (mComparator != null) {
mSorter.sort(mContents, mCount, mComparator);
} else {
DebugLog.d("FixedSizeArray",
"No comparator specified for this type, using Arrays.sort().");
Arrays.sort(mContents, 0, mCount);
}
mSorted = true;
}
}
/** Returns the number of objects in the array. */
public int getCount() {
return mCount;
}
/**
* Returns the maximum number of objects that can be inserted inot this
* array.
*/
public int getCapacity() {
return mContents.length;
}
/** Sets a comparator to use for sorting and searching. */
public void setComparator(Comparator<T> comparator) {
mComparator = comparator;
mSorted = false;
}
public void setSorter(Sorter<T> sorter) {
mSorter = sorter;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/FixedSizeArray.java | Java | oos | 8,355 |
package org.vn.gl;
/**
* AllocationGuard is a utility class for tracking down memory leaks. It
* implements a "checkpoint" memory scheme. After the static sGuardActive flag
* has been set, any further allocation of AllocationGuard or its derivatives
* will cause an error log entry. Note that AllocationGuard requires all of its
* derivatives to call super() in their constructor.
*/
public class AllocationGuard {
public static boolean sGuardActive = false;
public AllocationGuard() {
if (sGuardActive) {
// An allocation has occurred while the guard is active! Report it.
DebugLog.e("AllocGuard", "An allocation of type "
+ this.getClass().getName()
+ " occurred while the AllocGuard is active.");
}
}
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/AllocationGuard.java | Java | oos | 758 |
package org.vn.gl;
public class WorldMap extends BaseObject {
public float mWidthWord;
public float mHeightWord;
public WorldMap(float widthWord, float heightWord) {
mWidthWord = widthWord;
mHeightWord = heightWord;
}
@Override
public void reset() {
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/WorldMap.java | Java | oos | 289 |
package org.vn.gl;
public final class Lerp {
public static float lerp(float start, float target, float duration,
float timeSinceStart) {
float value = start;
if (timeSinceStart > 0.0f && timeSinceStart < duration) {
final float range = target - start;
final float percent = timeSinceStart / duration;
value = start + (range * percent);
} else if (timeSinceStart >= duration) {
value = target;
}
return value;
}
public static float ease(float start, float target, float duration,
float timeSinceStart) {
float value = start;
if (timeSinceStart > 0.0f && timeSinceStart < duration) {
final float range = target - start;
final float percent = timeSinceStart / (duration / 2.0f);
if (percent < 1.0f) {
value = start + ((range / 2.0f) * percent * percent * percent);
} else {
final float shiftedPercent = percent - 2.0f;
value = start
+ ((range / 2.0f) * ((shiftedPercent * shiftedPercent * shiftedPercent) + 2.0f));
}
} else if (timeSinceStart >= duration) {
value = target;
}
return value;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Lerp.java | Java | oos | 1,108 |
package org.vn.gl;
import org.vn.gl.game.CameraSystem;
import org.vn.network.GlobalService;
import org.vn.unit.CharacterManager;
import org.vn.unit.DialogAddEnemy;
import org.vn.unit.InputGameInterface;
import org.vn.unit.LogicMap;
import org.vn.unit.MapTiles;
import org.vn.unit.NumberDrawable;
import org.vn.unit.SoundManager;
import org.vn.unit.UnitEffects;
import org.vn.unit.UnitSreen;
/**
* The object registry manages a collection of global singleton objects.
* However, it differs from the standard singleton pattern in a few important
* ways: - The objects managed by the registry have an undefined lifetime. They
* may become invalid at any time, and they may not be valid at the beginning of
* the program. - The only object that is always guaranteed to be valid is the
* ObjectRegistry itself. - There may be more than one ObjectRegistry, and there
* may be more than one instance of any of the systems managed by ObjectRegistry
* allocated at once. For example, separate threads may maintain their own
* separate ObjectRegistry instances.
*/
public class ObjectRegistry extends BaseObject {
public CameraSystem cameraSystem;
public ContextParameters contextParameters;
public InputGameInterface inputGameInterface;
public OpenGLSystem openGLSystem;
public TextureLibrary longTermTextureLibrary;
public TimeSystem timeSystem;
public RenderSystem renderSystem;
public SoundSystem soundSystem;
public MultiTouchFilter2 multiTouchFilter2;
public NumberDrawable numberDrawableTime;
public NumberDrawable numberDrawableTimeInTurn;
public NumberDrawable numberDrawableCostInDialogAddEnemy;
public NumberDrawable numberDrawableTakeDame;
public UnitEffects unitEffects;
public MapTiles mapTiles;
public LogicMap logicMap;
public CharacterManager characterManager;
public GlobalService mGS = GlobalService.getInstance();
public UnitSreen unitSreen;
public DialogAddEnemy dialogAddEnemy;
public SoundManager soundManager;
public ObjectRegistry() {
super();
}
@Override
public void reset() {
}
public void onDestroy() {
cameraSystem = null;
contextParameters = null;
inputGameInterface = null;
openGLSystem = null;
longTermTextureLibrary = null;
timeSystem = null;
renderSystem = null;
characterManager.arrayCharactersMyTeam.clear();
characterManager.arrayCharactersOtherTeam.clear();
characterManager.mapEnemyInGame.clear();
characterManager = null;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/ObjectRegistry.java | Java | oos | 2,497 |
package org.vn.gl;
import java.util.Arrays;
import java.util.Comparator;
public class StandardSorter<T> extends Sorter {
@Override
public void sort(Object[] array, int count, Comparator comparator) {
Arrays.sort(array, 0, count, comparator);
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/StandardSorter.java | Java | oos | 268 |
package org.vn.gl;
/**
* Main game loop. Updates the time system and passes the result down to the
* rest of the game graph. This object is effectively the root of the game
* graph.
*/
public class MainLoop extends ObjectManager {
// Ensures that time updates before everything else.
public MainLoop() {
super();
mTimeSystem = new TimeSystem();
sSystemRegistry.timeSystem = mTimeSystem;
}
@Override
public void update(float timeDelta, BaseObject parent) {
mTimeSystem.update(timeDelta, parent);
final float newTimeDelta = mTimeSystem.getFrameDelta(); // The time
// system may
// warp time.
super.update(newTimeDelta, parent);
}
private TimeSystem mTimeSystem;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/MainLoop.java | Java | oos | 751 |
package org.vn.gl;
/**
* ObjectManagers are "group nodes" in the game graph. They contain child
* objects, and updating an object manager invokes update on its children.
* ObjectManagers themselves are derived from BaseObject, so they may be strung
* together into a hierarchy of objects. ObjectManager may be specialized to
* implement special types of traversals (e.g. PhasedObjectManager sorts its
* children).
*/
public class ObjectManager extends BaseObject {
protected static final int DEFAULT_ARRAY_SIZE = 64;
private FixedSizeArray<BaseObject> mObjects;
private FixedSizeArray<BaseObject> mPendingAdditions;
private FixedSizeArray<BaseObject> mPendingRemovals;
public ObjectManager() {
super();
mObjects = new FixedSizeArray<BaseObject>(DEFAULT_ARRAY_SIZE);
mPendingAdditions = new FixedSizeArray<BaseObject>(DEFAULT_ARRAY_SIZE);
mPendingRemovals = new FixedSizeArray<BaseObject>(DEFAULT_ARRAY_SIZE);
}
public ObjectManager(int arraySize) {
super();
mObjects = new FixedSizeArray<BaseObject>(arraySize);
mPendingAdditions = new FixedSizeArray<BaseObject>(arraySize);
mPendingRemovals = new FixedSizeArray<BaseObject>(arraySize);
}
@Override
public void reset() {
commitUpdates();
final int count = mObjects.getCount();
for (int i = 0; i < count; i++) {
BaseObject object = mObjects.get(i);
object.reset();
}
}
public void commitUpdates() {
final int additionCount = mPendingAdditions.getCount();
if (additionCount > 0) {
final Object[] additionsArray = mPendingAdditions.getArray();
for (int i = 0; i < additionCount; i++) {
BaseObject object = (BaseObject) additionsArray[i];
mObjects.add(object);
}
mPendingAdditions.clear();
}
final int removalCount = mPendingRemovals.getCount();
if (removalCount > 0) {
final Object[] removalsArray = mPendingRemovals.getArray();
for (int i = 0; i < removalCount; i++) {
BaseObject object = (BaseObject) removalsArray[i];
mObjects.remove(object, true);
}
mPendingRemovals.clear();
}
}
@Override
public void update(float timeDelta, BaseObject parent) {
commitUpdates();
final int count = mObjects.getCount();
if (count > 0) {
final Object[] objectArray = mObjects.getArray();
for (int i = 0; i < count; i++) {
BaseObject object = (BaseObject) objectArray[i];
object.update(timeDelta, this);
}
sSystemRegistry.inputGameInterface.endLoop();
}
}
public final FixedSizeArray<BaseObject> getObjects() {
return mObjects;
}
public final int getCount() {
return mObjects.getCount();
}
/** Returns the count after the next commitUpdates() is called. */
public final int getConcreteCount() {
return mObjects.getCount() + mPendingAdditions.getCount()
- mPendingRemovals.getCount();
}
public final BaseObject get(int index) {
return mObjects.get(index);
}
public void add(BaseObject object) {
mPendingAdditions.add(object);
}
public void remove(BaseObject object) {
mPendingRemovals.add(object);
}
public void removeAll() {
final int count = mObjects.getCount();
final Object[] objectArray = mObjects.getArray();
for (int i = 0; i < count; i++) {
mPendingRemovals.add((BaseObject) objectArray[i]);
}
mPendingAdditions.clear();
}
/**
* Finds a child object by its type. Note that this may invoke the class
* loader and therefore may be slow.
*
* @param classObject
* The class type to search for (e.g. BaseObject.class).
* @return
*/
public <T> T findByClass(Class<T> classObject) {
T object = null;
final int count = mObjects.getCount();
for (int i = 0; i < count; i++) {
BaseObject currentObject = mObjects.get(i);
if (currentObject.getClass() == classObject) {
object = classObject.cast(currentObject);
break;
}
}
return object;
}
protected FixedSizeArray<BaseObject> getPendingObjects() {
return mPendingAdditions;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/ObjectManager.java | Java | oos | 4,050 |
package org.vn.gl;
public class DeviceInfo {
public static int DEVICE_WIDTH = 800;
public static int DEVICE_HEIGHT = 480;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/DeviceInfo.java | Java | oos | 133 |
package org.vn.gl;
/**
* Manages input from a roller wheel and touch screen. Reduces frequent UI
* messages to an average direction over a short period of time.
*/
public class InputSystem extends BaseObject {
private InputTouchScreen mTouchScreen = new InputTouchScreen();
public InputSystem() {
super();
reset();
}
public InputTouchScreen getTouchScreen() {
return mTouchScreen;
}
// Thanks to NVIDIA for this useful canonical-to-screen orientation
// function.
// More here:
// http://developer.download.nvidia.com/tegra/docs/tegra_android_accelerometer_v5f.pdf
static void canonicalOrientationToScreenOrientation(int displayRotation,
float[] canVec, float[] screenVec) {
final int axisSwap[][] = { { 1, -1, 0, 1 }, // ROTATION_0
{ -1, -1, 1, 0 }, // ROTATION_90
{ -1, 1, 0, 1 }, // ROTATION_180
{ 1, 1, 1, 0 } }; // ROTATION_270
final int[] as = axisSwap[displayRotation];
screenVec[0] = (float) as[0] * canVec[as[2]];
screenVec[1] = (float) as[1] * canVec[as[3]];
screenVec[2] = canVec[2];
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/InputSystem.java | Java | oos | 1,170 |
package org.vn.gl;
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.PointF;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured. This version is
* modified from the original Grid.java (found in the SpriteText package in the
* APIDemos Android sample) to support hardware vertex buffers and to insert
* edges between grid squares for tiling.
*/
public class Mesh {
private float red;
private float green;
private float blue;
private float alpha;
private boolean isSetColorExpress;
private boolean ONE_MINUS_SRC_ALPHA = true;
public Mesh(Texture texture, float width, float height) {
float textureCoordinates[] = { 0.0f, 1.0f, //
1.0f, 1.0f, //
0.0f, 0.0f, //
1.0f, 0.0f, //
};
// short[] indices = new short[] { 0, 1, 2, 1, 3, 2 };
// setIndices(indices);
setVerticesMain(BitmapVertices(width, height));
setTextureCoordinatesMain(textureCoordinates);
mTexture = texture;
isSetColorExpress = false;
red = 1;
green = 1;
blue = 1;
alpha = 1;
}
private float[] BitmapVertices(float width, float height) {
float Vertices[] = { 0.0f, 0.0f, 0.0f,//
width, 0.0f, 0.0f,//
0.0f, height, 0.0f, //
width, height, 0.0f //
};
return Vertices;
}
public void setWidthHeight(float width, float height) {
setVerticesMain(BitmapVertices(width, height));
}
/**
* C-D<br>
* |---|<br>
* A-B
*
* @param A
* @param B
* @param C
* @param D
*/
public void setVertices(PointF A, PointF B, PointF C, PointF D) {
setVerticesMain(BitmapVertices(A, B, C, D));
}
private float[] BitmapVertices(PointF A, PointF B, PointF C, PointF D) {
float Vertices[] = { A.x, A.y, 0.0f,//
B.x, B.y, 0.0f,//
C.x, C.y, 0.0f, //
D.x, D.y, 0.0f //
};
return Vertices;
}
private Texture mTexture;
// Our vertex buffer.
private FloatBuffer mVerticesBuffer = null;
// The number of indices.
private int mNumOfIndices = 4;
// Our index buffer.
// private ShortBuffer mIndicesBuffer = null;
// Our UV texture buffer.
private FloatBuffer mTextureBuffer = null; // New variable.
private int mNumOfTextureBuffer = 4;
/**
* Render the mesh.
*
* @param gl
* the OpenGL context to render to.
*/
public void draw(GL10 gl, float mX, float mY, float mAngle, float mXRotate,
float mYRotate, float mPriority, float scaleX, float scaleY) {
if (mTexture != null) {
if (mTexture.resource != -1 && mTexture.loaded == false) {
BaseObject.sSystemRegistry.longTermTextureLibrary.loadBitmap(
BaseObject.sSystemRegistry.contextParameters.context,
gl, mTexture);
}
// Enabled the vertices buffer for writing and to be used during
// rendering.
gl.glLoadIdentity();
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
// Specifies the location and data format of an array of vertex
// coordinates to use when rendering.
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVerticesBuffer);
// Enable the texture state
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
// Point to our buffers
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTexture.name);
gl.glScalef(scaleX, scaleY, 0);
gl.glTranslatef(mX + mXRotate, mY + mYRotate, mPriority);
gl.glRotatef(mAngle, 0, 0, 1);
gl.glTranslatef(-mXRotate, -mYRotate, 0);
if (isSetColorExpress) {
if (!ONE_MINUS_SRC_ALPHA) {
gl.glColor4f(red * alpha, green * alpha, blue * alpha,
alpha);
} else {
gl.glColor4f(red, green, blue, alpha);
}
}
// gl.glDrawElements(GL10.GL_TRIANGLES, mNumOfIndices,
// GL10.GL_UNSIGNED_SHORT, mIndicesBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mNumOfIndices);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
if (isSetColorExpress) {
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
}
}
/**
* Set the vertices.
*
* @param vertices
*/
private void setVerticesMain(float[] vertices) {
int numOfIndices = vertices.length / 3;
if (mVerticesBuffer == null || mNumOfIndices != numOfIndices) {
// a float is 4 bytes, therefore we multiply the number if
// vertices with 4.
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
mVerticesBuffer = vbb.asFloatBuffer();
mNumOfIndices = numOfIndices;
}
mVerticesBuffer.clear();
mVerticesBuffer.put(vertices);
mVerticesBuffer.position(0);
}
public void setVertices(float[][] pVertices) {
float[] vertices = new float[pVertices.length * 3];
int indexV = 0;
for (int i = 0; i < pVertices.length; i++) {
vertices[indexV++] = pVertices[i][0];
vertices[indexV++] = pVertices[i][1];
vertices[indexV++] = 0;
}
setVerticesMain(vertices);
}
public void setTextureCoordinates(float[][] pTextureCoordinates) {
float textureCoordinates[] = new float[pTextureCoordinates.length * 2];
int indexT = 0;
for (int i = 0; i < pTextureCoordinates.length; i++) {
textureCoordinates[indexT++] = pTextureCoordinates[i][0];
textureCoordinates[indexT++] = pTextureCoordinates[i][1];
}
setTextureCoordinatesMain(textureCoordinates);
}
// /**
// * Set the indices.
// *
// * @param indices
// */
// private void setIndices(short[] indices) {
// short is 2 bytes, therefore we multiply the number if
// vertices with 2.
// ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
// ibb.order(ByteOrder.nativeOrder());
// mIndicesBuffer = ibb.asShortBuffer();
// mIndicesBuffer.put(indices);
// mIndicesBuffer.position(0);
// mNumOfIndices = indices.length;
// }
/**
* Set the texture coordinates.
*
* @param textureCoords
*/
private void setTextureCoordinatesMain(float[] textureCoords) { // New
// function.
// float is 4 bytes, therefore we multiply the number if
// vertices with 4.
int numOfTextureBuffer = textureCoords.length / 2;
if (mTextureBuffer == null || mNumOfTextureBuffer != numOfTextureBuffer) {
ByteBuffer byteBuf = ByteBuffer
.allocateDirect(textureCoords.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
mTextureBuffer = byteBuf.asFloatBuffer();
mNumOfTextureBuffer = numOfTextureBuffer;
}
mTextureBuffer.clear();
mTextureBuffer.put(textureCoords);
mTextureBuffer.position(0);
}
public void setTextureCoordinates(float scaleX1, float scaleX2,
float scaleY1, float scaleY2) {
float textureCoordinates[] = { scaleX1, scaleY2, //
scaleX2, scaleY2, //
scaleX1, scaleY1, //
scaleX2, scaleY1, //
};
setTextureCoordinatesMain(textureCoordinates);
}
public void setOpacity(float _opacity) {
alpha = _opacity;
isSetColorExpress = true;
}
public void setColorExpress(float r, float g, float b, float a) {
red = r;
green = g;
blue = b;
alpha = a;
isSetColorExpress = true;
}
public void setONE_MINUS_SRC_ALPHA(boolean b) {
ONE_MINUS_SRC_ALPHA = b;
}
public void setTexture(Texture pTexture) {
mTexture = pTexture;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Mesh.java | Java | oos | 8,009 |
package org.vn.gl;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.util.Log;
/**
* The Texture Library manages all textures in the game. Textures are pooled and
* handed out to requesting parties via allocateTexture(). However, the texture
* data itself is not immediately loaded at that time; it may have already been
* loaded or it may be loaded in the future via a call to loadTexture() or
* loadAllTextures(). This allows Texture objects to be dispersed to various
* game systems and while the texture data itself is streamed in or loaded as
* necessary.
*/
public class TextureLibrary extends BaseObject {
// Textures are stored in a simple hash. This class implements its own
// array-based hash rather
// than using HashMap for performance.
Texture[] mTextureHash;
int[] mTextureNameWorkspace;
int[] mCropWorkspace;
static final int DEFAULT_SIZE = 256;
public TextureLibrary() {
super();
mTextureHash = new Texture[DEFAULT_SIZE];
for (int x = 0; x < mTextureHash.length; x++) {
mTextureHash[x] = new Texture();
}
mTextureNameWorkspace = new int[1];
mCropWorkspace = new int[4];
}
@Override
public void reset() {
removeAll();
}
/**
* Creates a Texture object that is mapped to the passed resource id. If a
* texture has already been allocated for this id, the previously allocated
* Texture object is returned.
*
* @param resourceID
* @return
*/
public Texture allocateTexture(int resourceID, String string) {
Texture texture = getTextureByResource(resourceID);
if (texture == null) {
texture = addTexture(resourceID);
texture.name_bitmap = string;
}
return texture;
}
public Texture allocateTextureNotHash(int resourceID, String string) {
Texture texture = addTexture(resourceID);
texture.name_bitmap = string;
return texture;
}
/**
* Mac dinh la se khong cast anh lai
*
* @param bitmapCache
* @param isRecyle
* @param string
* @return
*/
public Texture allocateBitmapCache(iBitmapInImageCache bitmapCache,
boolean isRecyle, String string) {
Texture texture = addTexture(0);
texture.bitmapInImageCache = bitmapCache;
texture.setIsRecyle(isRecyle);
texture.name_bitmap = string;
return texture;
}
/**
* Loads a single texture into memory. Does nothing if the texture is
* already loaded.
*/
public Texture loadTexture(Context context, GL10 gl, int resourceID) {
Texture texture = allocateTexture(resourceID, "Loads a single texture");
texture = loadBitmap(context, gl, texture);
return texture;
}
/**
* Loads all unloaded textures into OpenGL memory. Already-loaded textures
* are ignored.
*/
public void loadAll(Context context, GL10 gl) {
for (int x = 0; x < mTextureHash.length; x++) {
if (mTextureHash[x].resource != -1
&& mTextureHash[x].loaded == false) {
loadBitmap(context, gl, mTextureHash[x]);
}
}
}
/** Flushes all textures from OpenGL memory */
public void deleteAll(GL10 gl) {
int countTextureDeleted = 0;
for (int x = 0; x < mTextureHash.length; x++) {
if (mTextureHash[x].resource != -1 && mTextureHash[x].loaded) {
assert mTextureHash[x].name != -1;
mTextureNameWorkspace[0] = mTextureHash[x].name;
mTextureHash[x].name = -1;
mTextureHash[x].loaded = false;
gl.glDeleteTextures(1, mTextureNameWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
DebugLog.d("Texture Delete", "GLError: " + error + " ("
+ GLU.gluErrorString(error) + "): "
+ mTextureNameWorkspace[0]);
} else {
DebugLog.d("Texture Delete succeed", "ID resource: "
+ mTextureNameWorkspace[0]);
countTextureDeleted++;
}
assert error == GL10.GL_NO_ERROR;
}
}
DebugLog.d("GL", "Num texture Delete succeed:" + countTextureDeleted);
DebugLog.d("GL", "**************************");
}
/** Marks all textures as unloaded */
public void invalidateAll() {
for (int x = 0; x < mTextureHash.length; x++) {
if (mTextureHash[x].resource != -1 && mTextureHash[x].loaded) {
mTextureHash[x].name = -1;
mTextureHash[x].loaded = false;
}
}
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for 2D
* texture maps.
*/
protected Texture loadBitmap(Context context, GL10 gl, Texture texture) {
assert gl != null;
assert context != null;
assert texture != null;
if (texture.loaded == false && texture.resource != -1) {
// Tìm texture name trống
gl.glGenTextures(1, mTextureNameWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
DebugLog.d("Texture Load 1",
"GLError: " + error + " (" + GLU.gluErrorString(error)
+ "): " + texture.resource);
}
assert error == GL10.GL_NO_ERROR;
int textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
DebugLog.d("Texture Load 2",
"GLError: " + error + " (" + GLU.gluErrorString(error)
+ "): " + texture.resource);
}
assert error == GL10.GL_NO_ERROR;
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE); // GL10.GL_REPLACE);
Log.d("GL", "Load bit map " + textureName + ":"
+ texture.name_bitmap + "|" + texture.resource);
Bitmap bitmap = null;
if (texture.bitmapInImageCache != null) {
bitmap = texture.bitmapInImageCache.getBitMapResourcesItem();
}
if (bitmap == null && texture.resource != 0) {
InputStream is = context.getResources().openRawResource(
texture.resource);
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
// Ignore.
}
}
if (GameInfo.SCALE_BITMAP != 1) {
Bitmap tamp = bitmap;
bitmap = Utils.scaleBitmap(tamp, tamp.getWidth()
/ GameInfo.SCALE_BITMAP, tamp.getHeight()
/ GameInfo.SCALE_BITMAP);
if (texture.isRecycleBitMap) {
tamp.recycle();
tamp = null;
} else {
texture.isRecycleBitMap = true;
}
}
}
if (bitmap == null) {
return texture;
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
DebugLog.d("Texture Load 3",
"GLError: " + error + " (" + GLU.gluErrorString(error)
+ "): " + texture.resource);
}
assert error == GL10.GL_NO_ERROR;
mCropWorkspace[0] = 0;
mCropWorkspace[1] = bitmap.getHeight();
mCropWorkspace[2] = bitmap.getWidth();
mCropWorkspace[3] = -bitmap.getHeight();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
texture.name = textureName;
texture.width = bitmap.getWidth();
texture.height = bitmap.getHeight();
if (texture.isRecycleBitMap) {
bitmap.recycle();
bitmap = null;
}
texture.bitmapInImageCache = null;
error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
DebugLog.d("Texture Load 4",
"GLError: " + error + " (" + GLU.gluErrorString(error)
+ "): " + texture.resource);
}
assert error == GL10.GL_NO_ERROR;
texture.loaded = true;
}
return texture;
}
public boolean isTextureLoaded(int resourceID) {
return getTextureByResource(resourceID) != null;
}
/**
* Returns the texture associated with the passed Android resource ID.
*
* @param resourceID
* The resource ID of a bitmap defined in R.java.
* @return An associated Texture object, or null if there is no associated
* texture in the library.
*/
public Texture getTextureByResource(int resourceID) {
int index = getHashIndex(resourceID);
int realIndex = findFirstKey(index, resourceID);
Texture texture = null;
if (realIndex != -1) {
texture = mTextureHash[realIndex];
}
return texture;
}
private int getHashIndex(int id) {
return id % mTextureHash.length;
}
/**
* Locates the texture in the hash. This hash uses a simple linear probe
* chaining mechanism: if the hash slot is occupied by some other entry, the
* next empty array index is used. This is O(n) for the worst case (every
* slot is a cache miss) but the average case is constant time.
*
* @param startIndex
* @param key
* @return
*/
private int findFirstKey(int startIndex, int key) {
int index = -1;
for (int x = 0; x < mTextureHash.length; x++) {
final int actualIndex = (startIndex + x) % mTextureHash.length;
if (mTextureHash[actualIndex].resource == key) {
index = actualIndex;
break;
} else if (mTextureHash[actualIndex].resource == -1) {
break;
}
}
return index;
}
/** Inserts a texture into the hash */
protected Texture addTexture(int id) {
int index = findFirstKey(getHashIndex(id), -1);
Texture texture = null;
assert index != -1;
if (index != -1) {
mTextureHash[index].resource = id;
texture = mTextureHash[index];
}
return texture;
}
public void removeAll() {
for (int x = 0; x < mTextureHash.length; x++) {
mTextureHash[x].reset();
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/TextureLibrary.java | Java | oos | 10,180 |
package org.vn.gl;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.vn.gl.GLSurfaceView.Renderer;
import org.vn.gl.RenderSystem.RenderElement;
import android.content.Context;
import android.os.Build;
import android.os.SystemClock;
/**
* GameRenderer the top-level rendering interface for the game engine. It is
* called by GLSurfaceView and is responsible for submitting commands to OpenGL.
* GameRenderer receives a queue of renderable objects from the thread and uses
* that to draw the scene every frame. If no queue is available then no drawing
* is performed. If the queue is not changed from frame to frame, the same scene
* will be redrawn every frame. The GameRenderer also invokes texture loads when
* it is activated.
*/
public class GameRenderer implements Renderer {
private static final int PROFILE_REPORT_DELAY = 2 * 1000;
private int mWidth;
private int mHeight;
// private int mHalfWidth;
// private int mHalfHeight;
// private float mScaleX;
// private float mScaleY;
private Context mContext;
private long mLastTime;
private int mProfileFrames;
private long mProfileWaitTime;
private long mProfileFrameTime;
private long mProfileSubmitTime;
private int mProfileObjectCount;
private long mTimeLastDraw;
private ObjectManager mDrawQueue;
private boolean mDrawQueueChanged;
private Game mGame;
private Object mDrawLock;
private float mCameraX;
private float mCameraY;
private boolean mCallbackRequested;
public static boolean isDeleteGLDone;
public static long averageFramePerSecond;
public static long averageWaitTime;
public GameRenderer(Context context, Game game, int gameWidth,
int gameHeight) {
mContext = context;
mGame = game;
setWidthHeight(gameWidth, gameHeight);
// mScaleX = 1.0f;
// mScaleY = 1.0f;
mDrawQueueChanged = false;
mDrawLock = new Object();
mCameraX = 0.0f;
mCameraY = 0.0f;
mCallbackRequested = false;
isDeleteGLDone = false;
}
public void setWidthHeight(int gameWidth, int gameHeight) {
mWidth = gameWidth;
mHeight = gameHeight;
// mHalfWidth = gameWidth / 2;
// mHalfHeight = gameHeight / 2;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.0f, 0.0f, 0.0f, 1);
gl.glShadeModel(GL10.GL_FLAT);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* By default, OpenGL enables features that improve quality but reduce
* performance. One might want to tweak that especially on software
* renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
String extensions = gl.glGetString(GL10.GL_EXTENSIONS);
String version = gl.glGetString(GL10.GL_VERSION);
String renderer = gl.glGetString(GL10.GL_RENDERER);
boolean isSoftwareRenderer = renderer.contains("PixelFlinger");
boolean isOpenGL10 = version.contains("1.0");
boolean supportsDrawTexture = extensions.contains("draw_texture");
// VBOs are standard in GLES1.1
// No use using VBOs when software renderering, esp. since older
// versions of the software renderer
// had a crash bug related to freeing VBOs.
boolean supportsVBOs = !isSoftwareRenderer
&& (!isOpenGL10 || extensions.contains("vertex_buffer_object"));
ContextParameters params = BaseObject.sSystemRegistry.contextParameters;
params.supportsDrawTexture = supportsDrawTexture;
params.supportsVBOs = supportsVBOs;
hackBrokenDevices();
DebugLog.i("Graphics Support", version + " (" + renderer + "): "
+ (supportsDrawTexture ? "draw texture," : "")
+ (supportsVBOs ? "vbos" : ""));
mGame.onSurfaceCreated();
}
private void hackBrokenDevices() {
// Some devices are broken. Fix them here. This is pretty much the only
// device-specific code in the whole project. Ugh.
ContextParameters params = BaseObject.sSystemRegistry.contextParameters;
if (Build.PRODUCT.contains("morrison")) {
// This is the Motorola Cliq. This device LIES and says it supports
// VBOs, which it actually does not (or, more likely, the extensions
// string
// is correct and the GL JNI glue is broken).
params.supportsVBOs = false;
// TODO: if Motorola fixes this, I should switch to using the
// fingerprint
// (blur/morrison/morrison/morrison:1.5/CUPCAKE/091007:user/ota-rel-keys,release-keys)
// instead of the product name so that newer versions use VBOs.
}
}
public void loadTextures(GL10 gl, TextureLibrary library) {
if (gl != null) {
library.loadAll(mContext, gl);
}
}
public void flushTextures(GL10 gl, TextureLibrary library) {
if (gl != null) {
library.deleteAll(gl);
}
}
public void onSurfaceLost() {
mGame.onSurfaceLost();
}
public void requestCallback() {
mCallbackRequested = true;
}
/**
* Draws the scene. Note that the draw queue is locked for the duration of
* this function.
*/
public void onDrawFrame(GL10 gl) {
long time = SystemClock.uptimeMillis();
long time_delta = (time - mLastTime);
synchronized (mDrawLock) {
if (!mDrawQueueChanged) {
while (!mDrawQueueChanged) {
try {
mDrawLock.wait();
} catch (InterruptedException e) {
// No big deal if this wait is interrupted.
}
}
}
mDrawQueueChanged = false;
}
final long wait = SystemClock.uptimeMillis();
if (!isDeleteGLDone) {
if (mCallbackRequested) {
mGame.CallbackRequested();
isDeleteGLDone = true;
} else {
DrawableBitmap.beginDrawing(gl, mWidth, mHeight);
synchronized (this) {
if (mDrawQueue != null
&& mDrawQueue.getObjects().getCount() > 0) {
OpenGLSystem.setGL(gl);
FixedSizeArray<BaseObject> objects = mDrawQueue
.getObjects();
Object[] objectArray = objects.getArray();
final int count = objects.getCount();
mProfileObjectCount += count;
float scaleX = BaseObject.sSystemRegistry.contextParameters.viewScaleX;
float scaleY = BaseObject.sSystemRegistry.contextParameters.viewScaleY;
float scaleXAfter = BaseObject.sSystemRegistry.contextParameters.viewScaleXAfter;
float scaleYAfter = BaseObject.sSystemRegistry.contextParameters.viewScaleYAfter;
for (int i = 0; i < count; i++) {
RenderElement element = (RenderElement) objectArray[i];
float x = element.x;
float y = element.y;
if (element.cameraRelative) {
x = (x - mCameraX);
y = (y - mCameraY);
element.mDrawable.draw(x, y, scaleXAfter,
scaleYAfter);
} else {
element.mDrawable.draw(x, y, scaleX, scaleY);
}
}
OpenGLSystem.setGL(null);
} else if (mDrawQueue == null) {
// If we have no draw queue, clear the screen. If we
// have a
// draw
// queue that
// is empty, we'll leave the frame buffer alone.
gl.glClear(GL10.GL_COLOR_BUFFER_BIT
| GL10.GL_DEPTH_BUFFER_BIT);
}
}
DrawableBitmap.endDrawing(gl);
}
}
long time2 = SystemClock.uptimeMillis();
mLastTime = time2;
mProfileFrameTime = time2 - mTimeLastDraw;
mProfileSubmitTime += time2 - time;
mProfileWaitTime += wait - time;
mProfileFrames++;
if (mProfileFrameTime > PROFILE_REPORT_DELAY) {
final int validFrames = mProfileFrames;
final long averageFrameTime = mProfileFrameTime / validFrames;
final long averageSubmitTime = mProfileSubmitTime / validFrames;
final float averageObjectsPerFrame = (float) mProfileObjectCount
/ validFrames;
averageFramePerSecond = 1000 / averageFrameTime;
averageWaitTime = mProfileWaitTime / validFrames;
DebugLog.d("Render Profile", "Average Submit: " + averageSubmitTime
+ " Average Draw: " + averageFrameTime
+ " Objects/Frame: " + averageObjectsPerFrame
+ " Wait Time: " + averageWaitTime
+ "AverageFramePerSecond: " + averageFramePerSecond);
mProfileFrameTime = 0;
mProfileSubmitTime = 0;
mProfileFrames = 0;
mProfileObjectCount = 0;
mTimeLastDraw = time2;
mProfileWaitTime = 0;
}
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
// mWidth = w;0
// mHeight = h;
// ensure the same aspect ratio as the game
float scaleX = (float) w / mWidth;
float scaleY = (float) h / mHeight;
final int viewportWidth = (int) (mWidth * scaleX);
final int viewportHeight = (int) (mHeight * scaleY);
gl.glViewport(0, 0, viewportWidth, viewportHeight);
// mScaleX = scaleX;
// mScaleY = scaleY;
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
float ratio = (float) mWidth / mHeight;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
mGame.onSurfaceReady();
}
public synchronized void setDrawQueue(ObjectManager queue, float cameraX,
float cameraY) {
mDrawQueue = queue;
mCameraX = cameraX;
mCameraY = cameraY;
synchronized (mDrawLock) {
mDrawQueueChanged = true;
mDrawLock.notify();
}
}
public synchronized void onPause() {
// Stop waiting to avoid deadlock.
// TODO: this is a hack. Probably this renderer
// should just use GLSurfaceView's non-continuious render
// mode.
synchronized (mDrawLock) {
mDrawQueueChanged = true;
mDrawLock.notify();
}
}
/**
* This function blocks while drawFrame() is in progress, and may be used by
* other threads to determine when drawing is occurring.
*/
public synchronized void waitDrawingComplete() {
}
public void setContext(Context newContext) {
mContext = newContext;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/GameRenderer.java | Java | oos | 10,287 |
package org.vn.gl;
import org.vn.gl.game.CameraSystem;
import android.os.SystemClock;
/**
* The GameThread contains the main loop for the game engine logic. It invokes
* the game graph, manages synchronization of input events, and handles the draw
* queue swap with the rendering thread.
*/
public class GameThread implements Runnable {
private long mLastTime;
private ObjectManager mGameRoot;
private GameRenderer mRenderer;
private Object mPauseLock;
private boolean mFinished;
private boolean mPaused = false;
private int mProfileFrames;
private long mProfileTime;
private static final float PROFILE_REPORT_DELAY = 2.0f;
public GameThread(GameRenderer renderer) {
mLastTime = SystemClock.uptimeMillis();
mRenderer = renderer;
mPauseLock = new Object();
mFinished = false;
mPaused = false;
}
public void run() {
mLastTime = SystemClock.elapsedRealtime();
mFinished = false;
long averageFrameTime = 1;
while (!mFinished) {
if (mGameRoot != null) {
mRenderer.waitDrawingComplete();
if (GameRenderer.isDeleteGLDone) {
// Make sure our dependence on the render system is cleaned
// up.
if (BaseObject.sSystemRegistry != null) {
BaseObject.sSystemRegistry.renderSystem
.emptyQueues(mRenderer);
BaseObject.sSystemRegistry.inputGameInterface
.glDeleteGLDone();
}
mFinished = true;
} else {
final long time = SystemClock.elapsedRealtime();
final long timeDelta = time - mLastTime;
if (timeDelta > 32) {
float secondsDelta = 0.001f * timeDelta;
// if (secondsDelta > 0.1f) {
// secondsDelta = 0.1f;
// }
mLastTime = time;
mGameRoot.update(secondsDelta, null);
CameraSystem camera = BaseObject.sSystemRegistry.cameraSystem;
float x = 0.0f;
float y = 0.0f;
if (camera != null) {
x = camera.getX();
y = camera.getY();
}
BaseObject.sSystemRegistry.renderSystem.swap(mRenderer,
x, y);
mProfileTime += timeDelta;
mProfileFrames++;
if (mProfileTime > PROFILE_REPORT_DELAY * 1000) {
averageFrameTime = mProfileTime / mProfileFrames;
DebugLog.d("Game Profile", "Average: "
+ averageFrameTime);
mProfileTime = 0;
mProfileFrames = 0;
// mGameRoot.sSystemRegistry.hudSystem
// .setFPS(1000 / (int) averageFrameTime);
}
// if (BaseObject.sSystemRegistry.numberDrawableTime !=
// null) {
// BaseObject.sSystemRegistry.numberDrawableTime
// .drawNumberWithAlpha(30, 20,
// (int) GameRenderer.averageWaitTime,
// 1, false, false, Priority.Help);
// }
} else {
// If the game logic completed in less than 16ms, that
// means
// it's running
// faster than 60fps, which is our target frame rate. In
// that
// case we should
// yield to the rendering thread, at least for the
// remaining
// frame.
try {
Thread.sleep(32 - timeDelta);
} catch (InterruptedException e) {
// Interruptions here are no big deal.
}
}
synchronized (mPauseLock) {
if (mPaused) {
// SoundSystem sound =
// BaseObject.sSystemRegistry.soundSystem;
// if (sound != null) {
// sound.pauseAll();
// BaseObject.sSystemRegistry.inputSystem
// .releaseAllKeys();
// }
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// No big deal if this wait is interrupted.
}
}
}
}
}
}
if (mFinished) {
DebugLog.d("DUC", "END GameThread :)");
}
}
// Make sure our dependence on the render system is cleaned up.
if (BaseObject.sSystemRegistry != null
&& BaseObject.sSystemRegistry.renderSystem != null)
BaseObject.sSystemRegistry.renderSystem.emptyQueues(mRenderer);
}
public void stopGame() {
synchronized (mPauseLock) {
mPaused = false;
mFinished = true;
mPauseLock.notifyAll();
}
}
public void pauseGame() {
synchronized (mPauseLock) {
mPaused = true;
}
}
public void resumeGame() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
public boolean getPaused() {
return mPaused;
}
public void setGameRoot(ObjectManager gameRoot) {
mGameRoot = gameRoot;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/GameThread.java | Java | oos | 4,543 |
package org.vn.gl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.zip.ZipInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.vn.constant.Constants;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ConfigurationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
public class Utils {
public static Random RANDOM = new Random();
public static Paint PAINT = new Paint();
public static Canvas CANVAS = new Canvas();
public static String convertStreamToString(InputStream is)
throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
public static void writeToFile(String fileName, InputStream iStream)
throws IOException {
writeToFile(fileName, iStream, true);
}
/**
* Writes InputStream to a given <code>fileName<code>.
* And, if directory for this file does not exists,
* if createDir is true, creates it, otherwice throws OMDIOexception.
*
* @param fileName
* - filename save to.
* @param iStream
* - InputStream with data to read from.
* @param createDir
* (false by default)
* @throws IOException
* in case of any error.
*
*/
public static void writeToFile(String fileName, InputStream iStream,
boolean createDir) throws IOException {
String me = "FileUtils.WriteToFile";
if (fileName == null) {
throw new IOException(me + ": filename is null");
}
if (iStream == null) {
throw new IOException(me + ": InputStream is null");
}
File theFile = new File(fileName);
// Check if a file exists.
if (theFile.exists()) {
String msg = theFile.isDirectory() ? "directory" : (!theFile
.canWrite() ? "not writable" : null);
if (msg != null) {
throw new IOException(me + ": file '" + fileName + "' is "
+ msg);
}
}
// Create directory for the file, if requested.
if (createDir && theFile.getParentFile() != null) {
theFile.getParentFile().mkdirs();
if (theFile.exists()) {
theFile.delete();
theFile.createNewFile();
}
}
// Save InputStream to the file.
BufferedOutputStream fOut = null;
try {
fOut = new BufferedOutputStream(new FileOutputStream(theFile));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
while ((bytesRead = iStream.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
throw new IOException(me + " failed, got: " + e.toString());
} finally {
close(iStream, fOut);
}
}
public static InputStream getImageFromNetwork(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity.getContentLength() > 0) {
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
entity);
return bufferedHttpEntity.getContent();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String getMd5Digest(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
return number.toString(16);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static boolean isSDCardPresent() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
public static void showDialogWhenLostConnection(final Context context,
List<RunningTaskInfo> runningTaskList, String currentClass) {
String packageName = context.getPackageName();
}
/** Decode a bitmap from resource */
public static Bitmap decodeRawResource(Resources resources, int resourceID) {
InputStream is = resources.openRawResource(resourceID);
Bitmap temp = null;
Bitmap bitmap = null;
try {
temp = BitmapFactory.decodeStream(is);
if (temp != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
bitmap = temp.copy(Config.ARGB_8888, true);
temp.recycle();
temp = null;
}
} catch (OutOfMemoryError error) {
DebugLog.e("Utils", "OutOfMemoryError");
temp.recycle();
temp = null;
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
System.gc();
temp = BitmapFactory.decodeStream(is);
if (temp != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
bitmap = temp.copy(Config.ARGB_8888, true);
temp.recycle();
temp = null;
}
}
return bitmap;
}
/**
* gGet the ids list of views inside a view which may cover on the cordinate
*
*/
public static ArrayList<Integer> getClickedViewIds(View mainView, int posX,
int posY) {
ArrayList<Integer> ids = new ArrayList<Integer>();
if (mainView instanceof ViewGroup) {
// get all the children in the view hierarchy
ArrayList<View> allChildren = new ArrayList<View>();
allChildren.add(mainView);
for (int i = 0; i < allChildren.size(); i++) {
if (allChildren.get(i) instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) allChildren.get(i);
for (int j = viewGroup.getChildCount() - 1; j >= 0; j--) {
allChildren.add(viewGroup.getChildAt(j));
}
}
}
for (int i = allChildren.size() - 1; i >= 0; i--) {
View view = allChildren.get(i);
// check if the click position is inside a child view
// or not
if (view.getLeft() <= posX && view.getRight() >= posX
&& view.getTop() <= posY && view.getBottom() >= posY
&& view.getId() >= 0) {
ids.add(view.getId());
}
}
} else {
if (mainView.getId() >= 0)
ids.add(mainView.getId());
}
return ids;
}
/**
* @return string la so them dau cham
*/
public static String formatNumber(long n) {
String moneyString = "";
String temp = "" + n;
while (temp.length() > 3) {
if (moneyString.length() == 0) {
moneyString = temp.substring(temp.length() - 3, temp.length());
} else {
moneyString = temp.substring(temp.length() - 3, temp.length())
+ "." + moneyString;
}
temp = temp.substring(0, temp.length() - 3);
}
if (moneyString.length() == 0) {
return temp;
}
moneyString = temp + "." + moneyString;
return moneyString;
}
/**
* Checking the status of network
*
* @param context
* @return is true if the device is connected. Otherwise, is false
*/
public static boolean checkInternetConnection(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// Check for connection
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
public static void clearData(SharedPreferences mSettingsPreferences,
String[] deleteKeys) {
Editor editor = mSettingsPreferences.edit();
for (int i = 0; i < deleteKeys.length; i++) {
editor.remove(deleteKeys[i]);
}
editor.commit();
}
/**
* Closes InputStream and/or OutputStream. It makes sure that both streams
* tried to be closed, even first throws an exception.
*
* @throw IOException if stream (is not null and) cannot be closed.
*
*/
protected static void close(InputStream iStream, OutputStream oStream)
throws IOException {
try {
if (iStream != null) {
iStream.close();
}
} finally {
if (oStream != null) {
oStream.close();
}
}
}
public static boolean checkFileExistent(String path) {
File f = new File(path);
if (f.exists()) {
return true;
}
return false;
}
public static float toDegreesUnit(Vector2 vector2) {
float direction = 0;
if (vector2.x == 0 && vector2.y == 0) {
return direction;
}
direction = (float) Math.toDegrees(Math.acos(vector2.x));
if (vector2.y > 0)
return direction;
else
return -direction;
}
public static double toRadiansUnit(Vector2 vector2) {
double direction = 0;
if (vector2.x == 0 && vector2.y == 0) {
return direction;
}
direction = Math.acos(vector2.x);
if (vector2.y > 0)
return direction;
else
return -direction;
}
/**
* Ham chuyen doi vecto thanh goc
*
* @param x
* @param y
* @return
*/
public static float toDegrees(double x, double y) {
float f = (float) Math.toDegrees(Math.atan2(y, x));
return f;
}
public static String getDataFromNetwork(String urlLink) {
try {
String str = "";
URL url = new URL(urlLink);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "//text plain");
connection.setRequestProperty("Connection", "close");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputstream = connection.getInputStream();
int length = connection.getContentLength();
if (length != -1) {
str = convertStreamToString(inputstream);
}
}
return str;
} catch (IOException e) {
return null;
}
}
public static String readFileToString(String path) {
StringBuilder content = new StringBuilder();
try {
File fileDir = new File(path);
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir), "UTF-8"));
String str;
String NL = System.getProperty("line.separator");
while ((str = in.readLine()) != null) {
content.append(str).append(NL);
}
in.close();
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return (content == null ? null : content.toString());
}
public static boolean isFileExist(String path) {
File file = new File(path);
return file.exists();
}
public static void setText(Bitmap bitmap, String string, int size,
int color, int maxTextInLine) {
setText(bitmap, string, size, color, maxTextInLine, 0, 0, size / 4,
bitmap.getWidth(), bitmap.getHeight());
}
/**
*
* @param bitmap
* @param string
* @param size
* @param color
* @param maxTextInLine
* @param pX
* @param pY
* @param pWidth
* @param pHeight
* @return HeightDrawText
*/
public static int setText(Bitmap bitmap, String string, int size,
int color, int maxTextInLine, int pStroke, int pX, int pY,
int pWidth, int pHeight) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Style.FILL_AND_STROKE);
paint.setTextSize(size);
// paint.setLinearText(true);
Canvas canvas = new Canvas(bitmap);
// paint.setStrokeWidth(pStroke);
final int widthBm = pWidth;
final int length = string.length();
int indext = 0;
int x = size;
float[] widths = new float[length];
char[] characters = string.toCharArray();
paint.getTextWidths(string, widths);
// int lengthMaxInline = (int) ((bitmap.getWidth() - size * 2) /
// widths[0]);
ArrayList<String> mListCardItems = new ArrayList<String>();
while (indext < length) {
int lengthMaxInline = 0;
int lengthMaxInlineNospace = -1;
int tamp = x * 2;
for (int i = indext; i < length; i++) {
tamp += widths[i];
if (tamp > widthBm)
break;
lengthMaxInline++;
if (i + 1 < length) {
if (characters[i] != ' ' && characters[i + 1] == ' ')
lengthMaxInlineNospace = lengthMaxInline;
} else {
lengthMaxInlineNospace = lengthMaxInline;
}
}
if (lengthMaxInlineNospace != -1)
lengthMaxInline = lengthMaxInlineNospace;
String s = string.substring(indext,
Math.min(indext + lengthMaxInline, length));
indext += lengthMaxInline;
mListCardItems.add(s);
for (int i = indext; i < length; i++) {
if (characters[i] == ' ')
indext++;
else
break;
}
}
int y = size;
int colorStroke = Color.argb(255, 0, 0, 0);
for (String cardItem : mListCardItems) {
// canvas.drawText(cardItem,
// (widthBm - paint.measureText(cardItem)) / 2, y, paint);]
paint.setColor(colorStroke);
paint.setStrokeWidth(pStroke);
canvas.drawText(cardItem, pX + x, pY + y, paint);
paint.setColor(color);
paint.setStrokeWidth(0);
canvas.drawText(cardItem, pX + x, pY + y, paint);
y += size;
}
return y - size / 2;
}
public static void setText(Bitmap bitmap, String string, int size,
int color, int colorStroke, int Stroke) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Style.FILL_AND_STROKE);
paint.setTextSize(size);
// paint.setLinearText(true);
// paint.setTextSkewX(-0.3f);
// paint.setTextSkewX(-0.3f);
float scaleX = 1f;
// paint.setTextScaleX(scaleX);
Canvas canvas = new Canvas(bitmap);
// paint.setColor(colorStroke);
// paint.setStrokeWidth(Stroke);
// canvas.drawText(string, bitmap.getWidth() / 2
// - (string.length() * size / 4) * scaleX, bitmap.getHeight() / 2
// + size / 4, paint);
Rect rect = new Rect();
paint.getTextBounds(string, 0, string.length(), rect);
paint.setStrokeWidth(Stroke);
paint.setColor(colorStroke);
canvas.drawText(string, bitmap.getWidth() / 2 - (rect.width() / 2)
* scaleX, bitmap.getHeight() / 2 + rect.height() / 2, paint);
paint.setStrokeWidth(0);
paint.setColor(color);
canvas.drawText(string, bitmap.getWidth() / 2 - (rect.width() / 2)
* scaleX, bitmap.getHeight() / 2 + rect.height() / 2, paint);
}
public static void setText(Bitmap bitmap, float x, float y, String string,
int size, int color, int Stroke) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Style.FILL_AND_STROKE);
paint.setTextSize(size);
Canvas canvas = new Canvas(bitmap);
paint.setColor(color);
paint.setStrokeWidth(Stroke);
canvas.drawText(string, x, y, paint);
}
public static Bitmap scaleBitmap(Bitmap bitmap, float width, float height) {
Matrix matrix = new Matrix();
float sx = width / bitmap.getWidth();
float sy = height / bitmap.getHeight();
matrix.setScale(sx, sy);
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
return bitmap2;
}
public static void addBitmapInBitmapFixSize(Bitmap bitmap, Bitmap bitmapAdd) {
CANVAS.setBitmap(bitmap);
PAINT.setAntiAlias(true);
CANVAS.drawBitmap(bitmapAdd, null, new Rect(0, 0, bitmap.getWidth(),
bitmap.getHeight()), PAINT);
}
public static void addBitmapInBitmapFixSize(Bitmap bitmap, Rect rect,
Bitmap bitmapAdd, Rect rectAdd) {
PAINT.setAntiAlias(true);
CANVAS.setBitmap(bitmap);
CANVAS.drawBitmap(bitmapAdd, rectAdd, rect, PAINT);
}
public static void vibrate(Context context, long[] pattern) {
if (GameInfo.ENABLE_VIBRATE) {
Vibrator vibrator = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, -1);
}
}
public static void getPositionClickHasCamera(MotionEvent ev, Vector2 vector2) {
ContextParameters params = BaseObject.sSystemRegistry.contextParameters;
vector2.x = BaseObject.sSystemRegistry.cameraSystem.getX()
+ ev.getRawX() * (1.0f / params.viewScaleXAfter);
vector2.y = BaseObject.sSystemRegistry.cameraSystem.getY()
+ params.gameHeightAfter - ev.getRawY()
* (1.0f / params.viewScaleYAfter);
}
public static void getPositionClickNonCamera(MotionEvent ev, Vector2 vector2) {
ContextParameters params = BaseObject.sSystemRegistry.contextParameters;
vector2.x = ev.getRawX() * (1.0f / params.viewScaleX);
vector2.y = params.gameHeight - ev.getRawY()
* (1.0f / params.viewScaleY);
}
public static double CosineInterpolateD(double y1, double y2, double mu) {
double mu2;
mu2 = (1 - Math.cos(mu * Math.PI)) / 2;
return (y1 * (1 - mu2) + y2 * mu2);
}
public static float CosineInterpolateF(float y1, float y2, float mu) {
float mu2;
mu2 = (float) ((1 - Math.cos(mu * Math.PI)) / 2);
return (y1 * (1 - mu2) + y2 * mu2);
}
public static boolean checkIn(float x, float y, float left, float right,
float bot, float top) {
if (x < left)
return false;
if (x > right)
return false;
if (y < bot)
return false;
if (y > top)
return false;
return true;
}
public static Bitmap transform(Matrix scaler, Bitmap source,
int targetWidth, int targetHeight, boolean scaleUp, boolean recycle) {
int deltaX = source.getWidth() - targetWidth;
int deltaY = source.getHeight() - targetHeight;
if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
/*
* In this case the bitmap is smaller, at least in one dimension,
* than the target. Transform it by placing as much of the image as
* possible into the target and leaving the top/bottom or left/right
* (or both) black.
*/
Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b2);
int deltaXHalf = Math.max(0, deltaX / 2);
int deltaYHalf = Math.max(0, deltaY / 2);
Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf
+ Math.min(targetWidth, source.getWidth()), deltaYHalf
+ Math.min(targetHeight, source.getHeight()));
int dstX = (targetWidth - src.width()) / 2;
int dstY = (targetHeight - src.height()) / 2;
Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight
- dstY);
c.drawBitmap(source, src, dst, null);
if (recycle) {
source.recycle();
}
return b2;
}
float bitmapWidthF = source.getWidth();
float bitmapHeightF = source.getHeight();
float bitmapAspect = bitmapWidthF / bitmapHeightF;
float viewAspect = (float) targetWidth / targetHeight;
if (bitmapAspect > viewAspect) {
float scale = targetHeight / bitmapHeightF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
} else {
float scale = targetWidth / bitmapWidthF;
if (scale < .9F || scale > 1F) {
scaler.setScale(scale, scale);
} else {
scaler = null;
}
}
Bitmap b1;
if (scaler != null) {
// this is used for minithumb and crop, so we want to filter here.
b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), scaler, true);
} else {
b1 = source;
}
if (recycle && b1 != source) {
source.recycle();
}
int dx1 = Math.max(0, b1.getWidth() - targetWidth);
int dy1 = Math.max(0, b1.getHeight() - targetHeight);
Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth,
targetHeight);
if (b2 != b1) {
if (recycle || b1 != source) {
b1.recycle();
}
}
return b2;
}
/**
* Kiểm tra xem user có phải là dùng sim tại Việt Nam hay không
*
* @param context
* @author Tran Vu Tat Binh (tvtbinh.bino@gmail.com)
*/
public static boolean isVietnameseNetwork(Context context) {
TelephonyManager tel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
if (!TextUtils.isEmpty(networkOperator)) {
try {
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
if (mcc == 452) {
return true;
}
} catch (Exception e) {
// lambt Không parse được mcc từ networkOperator (đối với máy
// không có sim)
}
}
return false;
}
/**
* Ghi chuỗi text xuống file trên sdcard.
*
* @param path
* @param value
* @throws IOException
*/
public static void writeStringToFile(String path, String value)
throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(path));
bufferedWriter.write(value);
bufferedWriter.flush();
bufferedWriter.close();
}
public static JSONObject getJSONObject(String data) {
JSONObject producedObject = null;
try {
if (!TextUtils.isEmpty(data)) {
producedObject = new JSONObject(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
return producedObject;
}
/**
* Lấy inputstream của file text từ server.
*
* @param urlStr
* @return
* @throws IOException
*/
public static InputStream getTextInputStream(String urlStr)
throws IOException {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "//text plain");
connection.setRequestProperty("Connection", "close");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputstream = connection.getInputStream();
int length = connection.getContentLength();
if (length != -1) {
return inputstream;
}
}
return null;
}
public static int[] mu2 = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 };
public static int get_2MuNGanNhat(final int number) {
if (number >= 2048)
return 2048;
for (int i = mu2.length - 1; i >= 0; i--) {
if (number >= mu2[i]) {
return mu2[i];
}
}
return 1;
}
/**
* Kiểm tra version của openGL trong máy có đủ đáp ứng để start app hay
* không.
*
* @author lambt
*/
public static boolean isGLAvailable(Activity activity, String minVersion) {
ActivityManager am = (ActivityManager) activity
.getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = am.getDeviceConfigurationInfo();
String eglVersion = info.getGlEsVersion();
if (minVersion.compareToIgnoreCase(eglVersion) <= 0) {
return true;
}
return false;
}
public static float smoothXToY(float x, float y, float smooth) {
float offset = y - x;
if (Math.abs(offset) > 0.1f * smooth)
return (x += smooth * offset);
else
return y;
}
public static String format(float val, int n, int w) {
String ZEROES = "000000000000";
String BLANKS = " ";
// rounding
double incr = 0.5;
for (int j = n; j > 0; j--)
incr /= 10;
val += incr;
String s = Float.toString(val);
int n1 = s.indexOf('.');
int n2 = s.length() - n1 - 1;
if (n > n2)
s = s + ZEROES.substring(0, n - n2);
else if (n2 > n)
s = s.substring(0, n1 + n + 1);
if (w > 0 & w > s.length())
s = BLANKS.substring(0, w - s.length()) + s;
else if (w < 0 & (-w) > s.length()) {
w = -w;
s = s + BLANKS.substring(0, w - s.length());
}
return s;
}
public static String unzipTextFile(InputStream inputStream) {
ZipInputStream zipInputStream = null;
try {
zipInputStream = new ZipInputStream(new BufferedInputStream(
inputStream));
zipInputStream.getNextEntry();
return convertStreamToString(zipInputStream);
} catch (Exception e) {
//
} finally {
if (zipInputStream != null) {
try {
zipInputStream.close();
} catch (IOException e) {
//
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//
}
}
}
return null;
}
public static void split(ArrayList<String> ArrayListResult, String content,
String regularExpression, int maxLength) {
ArrayList<String> arrayListWords = new ArrayList<String>();
String[] listsWord = content.split(regularExpression);
for (String string : listsWord) {
if (string.length() > maxLength) {
while (string.length() > maxLength) {
arrayListWords.add("" + string.substring(0, maxLength));
string = string.substring(maxLength, string.length());
}
if (string.length() > 0)
arrayListWords.add(string);
} else {
if (string.length() > 0)
arrayListWords.add(string);
}
}
final int length = arrayListWords.size();
int indext = 0;
while (indext < length) {
String item = "";
int daudong = indext;
while (indext < length
&& item.length() + arrayListWords.get(indext).length() <= maxLength) {
if (arrayListWords.get(indext).length() == 0) {
indext++;
} else {
if (indext != daudong)
item += " ";
item += arrayListWords.get(indext);
indext++;
}
}
ArrayListResult.add(item);
}
}
/**
* Call to other device. Only support VietNam network.
*/
public static boolean callSupport(Context context, String phoneNumber) {
try {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + phoneNumber));
context.startActivity(intent);
return true;
} catch (Exception e) {
//
}
return false;
}
public static void setLocale(Context context, String language) {
Locale locale2 = new Locale(language);
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;
context.getResources().updateConfiguration(config2,
context.getResources().getDisplayMetrics());
// Editor editor = preferences.edit();
// editor.putString(Constants.PREF_SETTINGS_LANGUAGE, language);
// editor.commit();
}
public static void setLocaleVn(Context context) {
setLocale(context, Constants.VI_LANGUAGE);
}
public static void setLocaleEng(Context context) {
setLocale(context, Constants.EN_LANGUAGE);
}
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Utils.java | Java | oos | 28,389 |
package org.vn.gl.game;
import org.vn.gl.BaseObject;
import org.vn.gl.ContextParameters;
import org.vn.gl.DrawableBitmap;
import org.vn.gl.Priority;
import org.vn.gl.RenderSystem;
import org.vn.gl.TextureLibrary;
import org.vn.gl.Vector2;
import org.vn.gl.WorldMap;
import org.vn.herowar.R;
/**
* Manages the position of the camera based on a target game object.
*/
public class CameraSystem extends BaseObject {
private float mX, mY, mXNext, mYNext, mXNext_ToaDoThuc, mYNext_ToaDoThuc;
public WorldMap worldMap;
private ContextParameters mContextParameters;
public boolean canSetNext;
public float timeDelayBeforeMove;
public float mScale;
public float mScaleNext;
public float scaleX = 0;
public float scaleY = 0;
public float scaleMax;
public float scaleMin = 4f;
private float mHeightBackground;
private float mWidthBackground;
private DrawableBitmap mDrawableBitmapBackGround;
private DrawableBitmap mDrawableBitmapBackGroundBefore;
public CameraSystem(TextureLibrary textureLibrary, float widthWorld,
float heightWord) {
mContextParameters = sSystemRegistry.contextParameters;
worldMap = new WorldMap(widthWorld, heightWord);
mX = (mContextParameters.gameWidthAfter - mContextParameters.viewWidth) / 2;
mY = (mContextParameters.gameHeightAfter - mContextParameters.viewHeight) / 3;
mXNext = mX;
mYNext = mY;
mXNext_ToaDoThuc = mXNext + mContextParameters.gameWidthAfter / 2;
mYNext_ToaDoThuc = mYNext + mContextParameters.gameHeightAfter / 2;
canSetNext = true;
timeDelayBeforeMove = 0;
mScale = 2.8f;
mScaleNext = 2.8f;
scaleMax = Math.max(
((float) mContextParameters.gameWidth) / widthWorld,
((float) mContextParameters.gameHeight) / heightWord);
scaleMax *= 1.1f;
// if (mScale < scaleMax)
{
mScale = scaleMax;
mScaleNext = scaleMax;
}
setScaleNow();
mWidthBackground = sSystemRegistry.contextParameters.gameWidthAfter * 3 / 2;
mHeightBackground = sSystemRegistry.contextParameters.gameHeightAfter * 3 / 2;
mDrawableBitmapBackGround = new DrawableBitmap(
textureLibrary.allocateTexture(R.drawable.back_ground,
"back_ground"), (int) mWidthBackground,
(int) mHeightBackground);
mDrawableBitmapBackGroundBefore = new DrawableBitmap(
textureLibrary.allocateTexture(R.drawable.batdau_ingame,
"batdau_ingame"), (int) mWidthBackground,
(int) mHeightBackground);
setNext(worldMap.mWidthWord / 2, worldMap.mHeightWord / 2, 0);
}
@Override
public void update(float timeDelta, BaseObject parent) {
if (mScale != mScaleNext) {
float tocdo = timeDelta * 100;
mScale += (mScaleNext - mScale) / tocdo;
if (Math.abs(mScale - mScaleNext) < 0.01f) {
mScale = mScaleNext;
}
setScaleNow();
}
if (timeDelayBeforeMove <= 0) {
// float tocdo = timeDelta * 400;
if (mX < mXNext) {
mX = mX + (mXNext - mX) * 12 * timeDelta;
if (mX > mXNext) {
mX = mXNext;
}
} else {
mX = mX + (mXNext - mX) * 12 * timeDelta;
if (mX < mXNext) {
mX = mXNext;
}
}
if (mY < mYNext) {
mY = mY + (mYNext - mY) * 12 * timeDelta;
if (mY > mYNext) {
mY = mYNext;
}
} else {
mY = mY + (mYNext - mY) * 12 * timeDelta;
if (mY < mYNext) {
mY = mYNext;
}
}
} else {
timeDelayBeforeMove -= timeDelta;
}
// RenderSystem render = sSystemRegistry.renderSystem;
// drawBackGround(render, mDrawableBitmapBackGround, 0.125f,
// worldMap.mWidthWord, worldMap.mHeightWord, 1);
// if (mDrawableBitmapBackGroundBefore != null) {
// drawBackGround(render, mDrawableBitmapBackGroundBefore, 0.2f,
// worldMap.mWidthWord, worldMap.mHeightWord, 1f);
// }
}
private void drawBackGround(RenderSystem render,
DrawableBitmap drawableBitmapBackGround, float a,
final float widthWord, final float heightWord, float scaleY) {
float xScale = widthWord
/ sSystemRegistry.contextParameters.gameWidthAfter;
float yScale = heightWord
/ sSystemRegistry.contextParameters.gameHeightAfter;
float scaleMin = Math.min(xScale, yScale);
scaleMin = a * scaleMin * scaleMin + (1 - a);
mWidthBackground = sSystemRegistry.contextParameters.gameWidth
* scaleMin;
mHeightBackground = sSystemRegistry.contextParameters.gameHeight
* scaleMin;
drawableBitmapBackGround.setWidth((int) mWidthBackground);
drawableBitmapBackGround.setHeight((int) (scaleY * mHeightBackground));
float TiLeX;
if (widthWord - sSystemRegistry.contextParameters.gameWidthAfter == 0) {
TiLeX = 0;
} else {
TiLeX = getX()
/ (widthWord - sSystemRegistry.contextParameters.gameWidthAfter);
}
float TiLeY = 0;
if (heightWord - sSystemRegistry.contextParameters.gameHeightAfter == 0) {
TiLeY = 0;
} else {
TiLeY = getY()
/ (heightWord - sSystemRegistry.contextParameters.gameHeightAfter);
}
float x = TiLeX
* (mWidthBackground - sSystemRegistry.contextParameters.gameWidth);
float y = TiLeY
* (mHeightBackground - sSystemRegistry.contextParameters.gameHeight);
render.scheduleForDraw(drawableBitmapBackGround, new Vector2(-x, -y),
Priority.BackGround, false);
}
public void setScaleNow() {
BaseObject.sSystemRegistry.contextParameters.setScale(mScale);
mXNext = mXNext_ToaDoThuc - mContextParameters.gameWidthAfter * scaleX;
mYNext = mYNext_ToaDoThuc - mContextParameters.gameHeightAfter * scaleY;
canhLe();
mXNext_ToaDoThuc = mXNext + mContextParameters.gameWidthAfter / 2;
mYNext_ToaDoThuc = mYNext + mContextParameters.gameHeightAfter / 2;
mX = mXNext;
mY = mYNext;
// mWidthBackground = sSystemRegistry.contextParameters.gameWidthAfter *
// 3 / 2;
// mHeightBackground = sSystemRegistry.contextParameters.gameHeightAfter
// * 3 / 2;
// mDrawableBitmapBackGround.setWidth((int) (mWidthBackground));
// mDrawableBitmapBackGround.setHeight((int) (mHeightBackground));
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
public float getX() {
return mX;
}
public float getY() {
return mY;
}
public void setX(float x) {
mX = x;
}
public void setY(float y) {
mY = y;
}
public void touchDown() {
mXNext = mX;
mYNext = mY;
timeDelayBeforeMove = 0;
canSetNext = false;
}
public void touchUp() {
canSetNext = true;
}
public void scale(float scaleOffset, float x, float y) {
mScaleNext *= scaleOffset;
scaleX = x;
scaleY = y;
if (mScaleNext > scaleMin) {
mScaleNext = scaleMin;
}
if (mScaleNext < scaleMax) {
mScaleNext = scaleMax;
}
}
public void offset(float xOffset, float yOffset) {
if (mScale == mScaleNext) {
mXNext += xOffset / mContextParameters.gameWidth
* mContextParameters.gameWidthAfter;
mYNext += yOffset / mContextParameters.gameHeight
* mContextParameters.gameHeightAfter;
canhLe();
mXNext_ToaDoThuc = mXNext + mContextParameters.gameWidthAfter / 2;
mYNext_ToaDoThuc = mYNext + mContextParameters.gameHeightAfter / 2;
}
}
private void canhLe() {
if (mXNext + mContextParameters.gameWidthAfter > worldMap.mWidthWord) {
mXNext = worldMap.mWidthWord - mContextParameters.gameWidthAfter;
}
if (mXNext < 0) {
mXNext = 0;
}
if (mYNext + mContextParameters.gameHeightAfter > worldMap.mHeightWord) {
mYNext = worldMap.mHeightWord - mContextParameters.gameHeightAfter;
}
if (mYNext < 0) {
mYNext = 0;
}
}
public void setNext(float x, float y, float timeDelay) {
if (canSetNext && timeDelayBeforeMove <= 0 && mScale == mScaleNext) {
mXNext_ToaDoThuc = x;
mYNext_ToaDoThuc = y;
mXNext = x - mContextParameters.gameWidthAfter / 2;
mYNext = y - mContextParameters.gameHeightAfter / 2;
timeDelayBeforeMove = timeDelay;
canhLe();
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/game/CameraSystem.java | Java | oos | 7,928 |
package org.vn.gl;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured. This version is
* modified from the original Grid.java (found in the SpriteText package in the
* APIDemos Android sample) to support hardware vertex buffers and to insert
* edges between grid squares for tiling.
*/
class Grid {
private static final int FLOAT_SIZE = 4;
private static final int FIXED_SIZE = 4;
private static final int CHAR_SIZE = 2;
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mVertsAcross;
private int mVertsDown;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
public Grid(int quadsAcross, int quadsDown, boolean useFixedPoint) {
final int vertsAcross = quadsAcross * 2;
final int vertsDown = quadsDown * 2;
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("quadsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("quadsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException(
"quadsAcross * quadsDown >= 32768");
}
mUseHardwareBuffers = false;
mVertsAcross = vertsAcross;
mVertsDown = vertsDown;
int size = vertsAcross * vertsDown;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer
.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer
.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer
.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer
.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadCount = quadsAcross * quadsDown;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]------[1] [2]------[3] ... | / | | / | | / | | / | | / | | / |
* [w]-----[w+1] [w+2]----[w+3]... | |
*/
{
int i = 0;
for (int y = 0; y < quadsDown; y++) {
final int indexY = y * 2;
for (int x = 0; x < quadsAcross; x++) {
final int indexX = x * 2;
char a = (char) (indexY * mVertsAcross + indexX);
char b = (char) (indexY * mVertsAcross + indexX + 1);
char c = (char) ((indexY + 1) * mVertsAcross + indexX);
char d = (char) ((indexY + 1) * mVertsAcross + indexX + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
public void set(int quadX, int quadY, float[][] positions, float[][] uvs) {
if (quadX < 0 || quadX * 2 >= mVertsAcross) {
throw new IllegalArgumentException("quadX");
}
if (quadY < 0 || quadY * 2 >= mVertsDown) {
throw new IllegalArgumentException("quadY");
}
if (positions.length < 4) {
throw new IllegalArgumentException("positions");
}
if (uvs.length < 4) {
throw new IllegalArgumentException("quadY");
}
int i = quadX * 2;
int j = quadY * 2;
setVertex(i, j, positions[0][0], positions[0][1], positions[0][2],
uvs[0][0], uvs[0][1]);
setVertex(i + 1, j, positions[1][0], positions[1][1], positions[1][2],
uvs[1][0], uvs[1][1]);
setVertex(i, j + 1, positions[2][0], positions[2][1], positions[2][2],
uvs[2][0], uvs[2][1]);
setVertex(i + 1, j + 1, positions[3][0], positions[3][1],
positions[3][2], uvs[3][0], uvs[3][1]);
}
private void setVertex(int i, int j, float x, float y, float z, float u,
float v) {
if (i < 0 || i >= mVertsAcross) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mVertsDown) {
throw new IllegalArgumentException("j");
}
final int index = mVertsAcross * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
} else {
mFixedVertexBuffer.put(posIndex, (int) (x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int) (y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int) (z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int) (u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int) (v * (1 << 16)));
}
}
public static void beginDrawing(GL10 gl, boolean useTexture) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
}
public void beginDrawingStrips(GL10 gl, boolean useTexture) {
beginDrawing(gl, useTexture);
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
} else {
GL11 gl11 = (GL11) gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
}
}
// Assumes beginDrawingStrips() has been called before this.
public void drawStrip(GL10 gl, boolean useTexture, int startIndex,
int indexCount) {
int count = indexCount;
if (startIndex + indexCount >= mIndexCount) {
count = mIndexCount - startIndex;
}
if (!mUseHardwareBuffers) {
gl.glDrawElements(GL10.GL_TRIANGLES, count, GL10.GL_UNSIGNED_SHORT,
mIndexBuffer.position(startIndex));
} else {
GL11 gl11 = (GL11) gl;
gl11.glDrawElements(GL11.GL_TRIANGLES, count,
GL11.GL_UNSIGNED_SHORT, startIndex * CHAR_SIZE);
}
}
public void draw(GL10 gl, boolean useTexture) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11) gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated. In that
* case, we just want to "forget" the old handles (without explicitly
* deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11) gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with data
* if a buffer has not already been previously allocated. Note that this
* function uses the GL_OES_vertex_buffer_object extension, which is not
* guaranteed to be supported on every device.
*
* @param gl
* A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
DebugLog.i("Grid", "Using Hardware Buffers");
if (gl instanceof GL11) {
GL11 gl11 = (GL11) gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity()
* mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize = mTexCoordBuffer.capacity()
* mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize,
mIndexBuffer, GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Grid.java | Java | oos | 11,580 |
package org.vn.gl;
public class GameInfo {
public static final int DEFAULT_WIDTH = 800;
public static final int DEFAULT_HEIGHT = 480;
public static float GIA_TOC_TRONG_TRUONG = 200;
public static float GIA_TOC_GIO = GIA_TOC_TRONG_TRUONG * 0.25f;
public static float V_MAX = (float) Math.sqrt(0.75f * DEFAULT_WIDTH
* GIA_TOC_TRONG_TRUONG);
public static float RADIUS_XET_VA_CHAM_CUA_PLAYER = 12;
public static int SCALE_BITMAP = 1;
public static boolean ENABLE_SOUND = true;
public static boolean ENABLE_VIBRATE = true;
public static boolean isLanguageEng;
public static float offset = 60;
public static float offsetMap = 100;
public static int idTypeKing = -1;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/GameInfo.java | Java | oos | 700 |
package org.vn.gl;
import android.view.MotionEvent;
public class MultiTouchFilter {
private InputXY[] pointFs = new InputXY[10];
public MultiTouchFilter() {
for (int i = 0; i < pointFs.length; i++) {
pointFs[i] = new InputXY();
}
}
public InputXY[] getPointFTouch() {
return pointFs;
}
public void onTouchEvent(MotionEvent event) {
int pointerCount = event.getPointerCount();
// if (event.getAction() != MotionEvent.ACTION_MOVE) {
// Log.e("DUC", "MotionEvent " + event.getAction());
// Log.d("DUC", "pointerCount " + pointerCount);
// for (int i = 0; i < pointerCount; i++) {
// float x = event.getX(i);
// float y = event.getY(i);
// Log.d("DUC", "pointer " + i + ": " + x + " - " + y);
// }
// }
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_MOVE:
touchMove(pointerCount, event);
break;
case MotionEvent.ACTION_DOWN:
touchDown(pointerCount, event, 0);
break;
case MotionEvent.ACTION_UP:
touchUp(pointerCount, event, 0);
break;
case MotionEvent.ACTION_POINTER_1_DOWN:
touchDown(pointerCount, event, 0);
break;
case MotionEvent.ACTION_POINTER_1_UP:
touchUp(pointerCount, event, 0);
break;
case MotionEvent.ACTION_POINTER_2_DOWN:// 261
touchDown(pointerCount, event, 1);
break;
case MotionEvent.ACTION_POINTER_2_UP:// 262
touchUp(pointerCount, event, 1);
break;
case MotionEvent.ACTION_POINTER_3_DOWN:// 517
touchDown(pointerCount, event, 2);
break;
case MotionEvent.ACTION_POINTER_3_UP:// 518
touchUp(pointerCount, event, 2);
break;
default:
int actionMash = action % 256;
switch (actionMash) {
case 5:// touch down
{
int indext = action / 256;
if (indext < pointFs.length) {
touchDown(pointerCount, event, indext);
}
break;
}
case 6:// touch up
{
int indext = action / 256;
if (indext < pointFs.length) {
touchUp(pointerCount, event, indext);
}
break;
}
default:
break;
}
break;
}
}
/**
*
* @param pointerCount
* @param event
* @param indextDown
* là vị trí point touch trong mảng
*/
private void touchDown(int pointerCount, MotionEvent event, int indextDown) {
changeToLocationScreen(pointFs[indextDown], event.getX(indextDown),
event.getY(indextDown));
}
/**
*
* @param pointerCount
* @param event
* @param indextUp
* là vị trí point touch trong mảng, nhưng chỉ tính những pointf
* enable
*/
private void touchUp(int pointerCount, MotionEvent event, int indextUp) {
int indextMash = 0;
for (int i = 0; i < pointFs.length; i++) {
if (!pointFs[i].isDisable()) {
if (indextMash == indextUp) {
indextMash = i;
break;
}
indextMash++;
}
}
pointFs[indextMash].disable();
}
/**
*
* @param pointerCount
* @param event
*/
private void touchMove(int pointerCount, MotionEvent event) {
int j = 0;
for (int i = 0; i < pointFs.length; i++) {
if (!pointFs[i].isDisable()) {
if (j < pointerCount) {
changeToLocationScreen(pointFs[i], event.getX(j),
event.getY(j));
j++;
}
}
}
}
private static void changeToLocationScreen(InputXY inputXY, float x, float y) {
ContextParameters params = BaseObject.sSystemRegistry.contextParameters;
inputXY.x = x * (1.0f / params.viewScaleX);
inputXY.y = params.gameHeight - (y * (1.0f / params.viewScaleY));
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/MultiTouchFilter.java | Java | oos | 3,590 |
package org.vn.gl;
import java.util.Comparator;
public abstract class Sorter<Type> {
public abstract void sort(Type[] array, int count,
Comparator<Type> comparator);
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Sorter.java | Java | oos | 182 |
package org.vn.gl;
/**
* DrawableObject is the base object interface for objects that can be rendered
* to the screen. Note that objects derived from DrawableObject are passed
* between threads, and that care must be taken when modifying drawable
* parameters to avoid side-effects (for example, the DrawableFactory class can
* be used to generate fire-and-forget drawables).
*/
public abstract class DrawableObject extends AllocationGuard {
private float mPriority;
private ObjectPool mParentPool;
public abstract void draw(float x, float y, float scaleX, float scaleY);
public DrawableObject() {
super();
}
public void setPriority(float f) {
mPriority = f;
}
public float getPriority() {
return mPriority;
}
public void setParentPool(ObjectPool pool) {
mParentPool = pool;
}
public ObjectPool getParentPool() {
return mParentPool;
}
// Override to allow drawables to be sorted by texture.
public Texture getTexture() {
return null;
}
// Function to allow drawables to specify culling rules.
public boolean visibleAtPosition(Vector2 position) {
return true;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/DrawableObject.java | Java | oos | 1,160 |
package org.vn.gl;
/**
* Manages a double-buffered queue of renderable objects. The game thread
* submits drawable objects to the the active render queue while the render
* thread consumes drawables from the alternate queue. When both threads
* complete a frame the queues are swapped. Note that this class can manage any
* number (>=2) of render queues, but increasing the number over two means that
* the game logic will be running significantly ahead of the rendering thread,
* which may make the user feel that the controls are "loose."
*/
public class RenderSystem extends BaseObject {
private static final int TEXTURE_SORT_BUCKET_SIZE = 1000;
private RenderElementPool mElementPool;
private ObjectManager[] mRenderQueues;
private int mQueueIndex;
private final static int DRAW_QUEUE_COUNT = 2;
private final static int MAX_RENDER_OBJECTS_PER_FRAME = 512;
private final static int MAX_RENDER_OBJECTS = MAX_RENDER_OBJECTS_PER_FRAME
* DRAW_QUEUE_COUNT;
public RenderSystem() {
super();
mElementPool = new RenderElementPool(MAX_RENDER_OBJECTS);
mRenderQueues = new ObjectManager[DRAW_QUEUE_COUNT];
for (int x = 0; x < DRAW_QUEUE_COUNT; x++) {
mRenderQueues[x] = new PhasedObjectManager(
MAX_RENDER_OBJECTS_PER_FRAME);
}
mQueueIndex = 0;
}
@Override
public void reset() {
}
public void scheduleForDraw(DrawableObject object, Vector2 position,
int priority, boolean cameraRelative) {
RenderElement element = mElementPool.allocate();
if (element != null) {
element.set(object, position, priority, cameraRelative);
mRenderQueues[mQueueIndex].add(element);
}
}
private void clearQueue(FixedSizeArray<BaseObject> objects) {
final int count = objects.getCount();
final Object[] objectArray = objects.getArray();
final RenderElementPool elementPool = mElementPool;
for (int i = count - 1; i >= 0; i--) {
RenderElement element = (RenderElement) objectArray[i];
elementPool.release(element);
objects.removeLast();
}
}
public void swap(GameRenderer renderer, float cameraX, float cameraY) {
mRenderQueues[mQueueIndex].commitUpdates();
// This code will block if the previous queue is still being executed.
renderer.setDrawQueue(mRenderQueues[mQueueIndex], cameraX, cameraY);
final int lastQueue = (mQueueIndex == 0) ? DRAW_QUEUE_COUNT - 1
: mQueueIndex - 1;
// Clear the old queue.
FixedSizeArray<BaseObject> objects = mRenderQueues[lastQueue]
.getObjects();
clearQueue(objects);
mQueueIndex = (mQueueIndex + 1) % DRAW_QUEUE_COUNT;
}
/*
* Empties all draw queues and disconnects the game thread from the
* renderer.
*/
public void emptyQueues(GameRenderer renderer) {
renderer.setDrawQueue(null, 0.0f, 0.0f);
for (int x = 0; x < DRAW_QUEUE_COUNT; x++) {
mRenderQueues[x].commitUpdates();
FixedSizeArray<BaseObject> objects = mRenderQueues[x].getObjects();
clearQueue(objects);
}
}
public class RenderElement extends PhasedObject {
public RenderElement() {
super();
}
public void set(DrawableObject drawable, Vector2 position,
int priority, boolean isCameraRelative) {
mDrawable = drawable;
x = position.x;
y = position.y;
cameraRelative = isCameraRelative;
final int sortBucket = priority * TEXTURE_SORT_BUCKET_SIZE;
int sortOffset = 0;
if (drawable != null) {
Texture tex = drawable.getTexture();
if (tex != null) {
sortOffset = (tex.resource % TEXTURE_SORT_BUCKET_SIZE)
* GLUtils.sign(priority);
}
}
setPhase(sortBucket + sortOffset);
}
public void reset() {
mDrawable = null;
x = 0.0f;
y = 0.0f;
cameraRelative = false;
}
public DrawableObject mDrawable;
public float x;
public float y;
public boolean cameraRelative;
}
protected class RenderElementPool extends TObjectPool<RenderElement> {
RenderElementPool(int max) {
super(max);
}
@Override
public void release(Object element) {
RenderElement renderable = (RenderElement) element;
// if this drawable came out of a pool, make sure it is returned to
// that pool.
final ObjectPool pool = renderable.mDrawable.getParentPool();
if (pool != null) {
pool.release(renderable.mDrawable);
}
// reset on release
renderable.reset();
super.release(element);
}
@Override
protected void fill() {
for (int x = 0; x < getSize(); x++) {
getAvailable().add(new RenderElement());
}
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/RenderSystem.java | Java | oos | 4,579 |
package org.vn.gl;
/**
* Simple 2D vector class. Handles basic vector math for 2D vectors.
*/
public final class Vector2 extends AllocationGuard {
public float x;
public float y;
public static final Vector2 ZERO = new Vector2(0, 0);
public static final Vector2 TAMP = new Vector2(0, 0);
public Vector2() {
super();
}
public Vector2(float xValue, float yValue) {
set(xValue, yValue);
}
public Vector2(Vector2 other) {
set(other);
}
public final void add(Vector2 other) {
x += other.x;
y += other.y;
}
public final void add(float otherX, float otherY) {
x += otherX;
y += otherY;
}
public final void subtract(Vector2 other) {
x -= other.x;
y -= other.y;
}
public final void multiply(float magnitude) {
x *= magnitude;
y *= magnitude;
}
public final void multiply(Vector2 other) {
x *= other.x;
y *= other.y;
}
public final void divide(float magnitude) {
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
}
}
public final void set(Vector2 other) {
x = other.x;
y = other.y;
}
public Vector2 set(float xValue, float yValue) {
x = xValue;
y = yValue;
return this;
}
public final float dot(Vector2 other) {
return (x * other.x) + (y * other.y);
}
public final float length() {
return (float) Math.sqrt(length2());
}
public final float length2() {
return (x * x) + (y * y);
}
public final float distance2(Vector2 other) {
float dx = x - other.x;
float dy = y - other.y;
return (dx * dx) + (dy * dy);
}
public final float normalize() {
final float magnitude = length();
// TODO: I'm choosing safety over speed here.
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
}
return magnitude;
}
public final void zero() {
set(0.0f, 0.0f);
}
public final void flipHorizontal(float aboutWidth) {
x = (aboutWidth - x);
}
public final void flipVertical(float aboutHeight) {
y = (aboutHeight - y);
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Vector2.java | Java | oos | 2,052 |
package org.vn.gl;
import android.util.Log;
public final class DebugLog {
private static boolean isLog = true;
private DebugLog() {
}
public static int v(String tag, String msg) {
int result = 0;
if (isLog) {
result = Log.v(tag, msg);
}
return result;
}
public static int v(String tag, String msg, Throwable tr) {
int result = 0;
if (isLog) {
result = Log.v(tag, msg, tr);
}
return result;
}
public static int d(String tag, String msg) {
int result = 0;
if (isLog) {
result = Log.d(tag, msg);
}
return result;
}
public static int d(String tag, String msg, Throwable tr) {
int result = 0;
if (isLog) {
result = Log.d(tag, msg, tr);
}
return result;
}
public static int i(String tag, String msg) {
int result = 0;
if (isLog) {
result = Log.i(tag, msg);
}
return result;
}
public static int i(String tag, String msg, Throwable tr) {
int result = 0;
if (isLog) {
result = Log.i(tag, msg, tr);
}
return result;
}
public static int w(String tag, String msg) {
int result = 0;
if (isLog) {
result = Log.w(tag, msg);
}
return result;
}
public static int w(String tag, String msg, Throwable tr) {
int result = 0;
if (isLog) {
result = Log.w(tag, msg, tr);
}
return result;
}
public static int w(String tag, Throwable tr) {
int result = 0;
if (isLog) {
result = Log.w(tag, tr);
}
return result;
}
public static int e(String tag, String msg) {
int result = 0;
if (isLog) {
result = Log.e(tag, msg);
}
return result;
}
public static int e(String tag, String msg, Throwable tr) {
int result = 0;
if (isLog) {
result = Log.e(tag, msg, tr);
}
return result;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/DebugLog.java | Java | oos | 1,807 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vn.gl;
import java.util.Comparator;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundSystem extends BaseObject {
private static final int MAX_STREAMS = 12;
private static final int MAX_SOUNDS = 32;
private static final SoundComparator sSoundComparator = new SoundComparator();
public static final int PRIORITY_LOW = 0;
public static final int PRIORITY_NORMAL = 1;
public static final int PRIORITY_HIGH = 2;
public static final int PRIORITY_MUSIC = 3;
private SoundPool mSoundPool;
private FixedSizeArray<Sound> mSounds;
private Sound mSearchDummy;
private boolean mSoundEnabled;
private int[] mLoopingStreams;
public SoundSystem() {
super();
mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
mSounds = new FixedSizeArray<Sound>(MAX_SOUNDS, sSoundComparator);
mSearchDummy = new Sound();
mLoopingStreams = new int[MAX_STREAMS];
for (int x = 0; x < mLoopingStreams.length; x++) {
mLoopingStreams[x] = -1;
}
}
@Override
public void reset() {
mSoundPool.release();
mSounds.clear();
mSoundEnabled = true;
for (int x = 0; x < mLoopingStreams.length; x++) {
mLoopingStreams[x] = -1;
}
}
public Sound load(int resource) {
final int index = findSound(resource);
Sound result = null;
if (index < 0) {
// new sound.
if (sSystemRegistry.contextParameters != null) {
Context context = sSystemRegistry.contextParameters.context;
result = new Sound();
result.resource = resource;
result.soundId = mSoundPool.load(context, resource, 1);
mSounds.add(result);
mSounds.sort(false);
}
} else {
result = mSounds.get(index);
}
return result;
}
public Sound load(String path) {
final int index = findSound(path.hashCode());
Sound result = null;
if (index < 0) {
// new sound.
if (sSystemRegistry.contextParameters != null) {
result = new Sound();
result.resource = path.hashCode();
result.soundId = mSoundPool.load(path, 1);
mSounds.add(result);
mSounds.sort(false);
}
} else {
result = mSounds.get(index);
}
return result;
}
synchronized public final int play(Sound sound, boolean loop, int priority) {
int stream = -1;
if (mSoundEnabled) {
stream = mSoundPool.play(sound.soundId, 1.0f, 1.0f, priority,
loop ? -1 : 0, 1.0f);
if (loop) {
addLoopingStream(stream);
}
}
return stream;
}
synchronized public final int play(Sound sound, boolean loop, int priority,
float volume, float rate) {
int stream = -1;
if (mSoundEnabled) {
stream = mSoundPool.play(sound.soundId, volume, volume, priority,
loop ? -1 : 0, rate);
if (loop) {
addLoopingStream(stream);
}
}
return stream;
}
public final void stop(int stream) {
mSoundPool.stop(stream);
removeLoopingStream(stream);
}
public final void pause(int stream) {
mSoundPool.pause(stream);
}
public final void resume(int stream) {
mSoundPool.resume(stream);
}
public final void stopAll() {
final int count = mLoopingStreams.length;
for (int x = count - 1; x >= 0; x--) {
if (mLoopingStreams[x] >= 0) {
stop(mLoopingStreams[x]);
}
}
reset();
}
// HACK: There's no way to pause an entire sound pool, but if we
// don't do something when our parent activity is paused, looping
// sounds will continue to play. Rather that reproduce all the bookkeeping
// that SoundPool does internally here, I've opted to just pause looping
// sounds when the Activity is paused.
public void pauseAll() {
final int count = mLoopingStreams.length;
for (int x = 0; x < count; x++) {
if (mLoopingStreams[x] >= 0) {
pause(mLoopingStreams[x]);
}
}
}
private void addLoopingStream(int stream) {
final int count = mLoopingStreams.length;
for (int x = 0; x < count; x++) {
if (mLoopingStreams[x] < 0) {
mLoopingStreams[x] = stream;
break;
}
}
}
private void removeLoopingStream(int stream) {
final int count = mLoopingStreams.length;
for (int x = 0; x < count; x++) {
if (mLoopingStreams[x] == stream) {
mLoopingStreams[x] = -1;
break;
}
}
}
private final int findSound(int resource) {
mSearchDummy.resource = resource;
return mSounds.find(mSearchDummy, false);
}
synchronized public final void setSoundEnabled(boolean soundEnabled) {
mSoundEnabled = soundEnabled;
}
public final boolean getSoundEnabled() {
return mSoundEnabled;
}
public class Sound extends AllocationGuard {
public int resource;
public int soundId;
}
/** Comparator for sounds. */
private final static class SoundComparator implements Comparator<Sound> {
public int compare(final Sound object1, final Sound object2) {
int result = 0;
if (object1 == null && object2 != null) {
result = 1;
} else if (object1 != null && object2 == null) {
result = -1;
} else if (object1 != null && object2 != null) {
result = object1.resource - object2.resource;
}
return result;
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/SoundSystem.java | Java | oos | 5,854 |
package org.vn.gl;
import java.util.Comparator;
/**
* A derivation of ObjectManager that sorts its children if they are of type
* PhasedObject. Sorting is performed on add.
*/
public class PhasedObjectManager extends ObjectManager {
private final static PhasedObjectComparator sPhasedObjectComparator = new PhasedObjectComparator();
private boolean mDirty;
private PhasedObject mSearchDummy; // A dummy object allocated up-front for
// searching by phase.
public PhasedObjectManager() {
super();
mDirty = false;
getObjects().setComparator(sPhasedObjectComparator);
getPendingObjects().setComparator(sPhasedObjectComparator);
mSearchDummy = new PhasedObject();
}
public PhasedObjectManager(int arraySize) {
super(arraySize);
mDirty = false;
getObjects().setComparator(sPhasedObjectComparator);
getPendingObjects().setComparator(sPhasedObjectComparator);
mSearchDummy = new PhasedObject();
}
@Override
public void commitUpdates() {
super.commitUpdates();
if (mDirty) {
getObjects().sort(true);
mDirty = false;
}
}
@Override
public void add(BaseObject object) {
if (object instanceof PhasedObject) {
super.add(object);
mDirty = true;
} else {
// The only reason to restrict PhasedObjectManager to PhasedObjects
// is so that
// the PhasedObjectComparator can assume all of its contents are
// PhasedObjects and
// avoid calling instanceof every time.
assert false : "Can't add a non-PhasedObject to a PhasedObjectManager!";
}
}
public BaseObject find(int phase) {
mSearchDummy.setPhase(phase);
int index = getObjects().find(mSearchDummy, false);
BaseObject result = null;
if (index != -1) {
result = getObjects().get(index);
} else {
index = getPendingObjects().find(mSearchDummy, false);
if (index != -1) {
result = getPendingObjects().get(index);
}
}
return result;
}
/** Comparator for phased objects. */
private static class PhasedObjectComparator implements
Comparator<BaseObject> {
public int compare(BaseObject object1, BaseObject object2) {
int result = 0;
if (object1 != null && object2 != null) {
result = ((PhasedObject) object1).phase
- ((PhasedObject) object2).phase;
} else if (object1 == null && object2 != null) {
result = 1;
} else if (object2 == null && object1 != null) {
result = -1;
}
return result;
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/PhasedObjectManager.java | Java | oos | 2,488 |
package org.vn.gl;
import javax.microedition.khronos.opengles.GL10;
import org.vn.unit.AnimationCharacter;
import android.graphics.PointF;
public class DrawableMesh extends DrawableObject {
private Mesh mMesh;
private float mAngle, mXRotate, mYRotate;
private float mWidth, mHeight;
public DrawableMesh(Texture texture, float width, float height) {
mMesh = new Mesh(texture, width, height);
mAngle = 0;
mXRotate = width / 2;
mYRotate = height / 2;
mWidth = width;
mHeight = height;
}
public float getWidth() {
return mWidth;
}
public float getHeight() {
return mHeight;
}
public void setWidth(float width) {
mWidth = width;
mMesh.setWidthHeight(mWidth, mHeight);
}
public void setHeight(float height) {
mHeight = height;
mMesh.setWidthHeight(mWidth, mHeight);
}
public void setangle(float angle) {
mAngle = angle;
}
public void setPositionRotateInBitmap(float xRotate, float yRotate) {
mXRotate = xRotate;
mYRotate = yRotate;
}
public void setCoordinates(AnimationCharacter animation) {
mMesh.setTextureCoordinates(animation.getScaleX1(),
animation.getScaleX2(), animation.getScaleY1(),
animation.getScaleY2());
}
public void setCoordinates(float scaleX1, float scaleX2, float scaleY1,
float scaleY2) {
mMesh.setTextureCoordinates(scaleX1, scaleX2, scaleY1, scaleY2);
}
@Override
public void draw(float x, float y, float scaleX, float scaleY) {
GL10 gl = OpenGLSystem.getGL();
mMesh.draw(gl, x, y, mAngle, mXRotate, mYRotate, getPriority(), scaleX,
scaleY);
}
public void setOpacity(float _opacity) {
mMesh.setOpacity(_opacity);
}
public void setColorExpress(float r, float g, float b, float a) {
mMesh.setColorExpress(r, g, b, a);
}
/**
* C-D<br>
* |---|<br>
* A-B
*
* @param A
* @param B
* @param C
* @param D
*/
public void setVertices(PointF A, PointF B, PointF C, PointF D) {
mMesh.setVertices(A, B, C, D);
}
public void setVerticesFloat(float[][] vertices) {
mMesh.setVertices(vertices);
}
public void setTextureCoordinates(float[][] pTextureCoordinates) {
mMesh.setTextureCoordinates(pTextureCoordinates);
}
public void setONE_MINUS_SRC_ALPHA(boolean b) {
mMesh.setONE_MINUS_SRC_ALPHA(b);
}
public void setTexture(Texture pTexture) {
mMesh.setTexture(pTexture);
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/DrawableMesh.java | Java | oos | 2,425 |
package org.vn.gl;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.graphics.Bitmap;
import android.opengl.GLUtils;
/**
* Draws a screen-aligned bitmap to the screen.
*/
public class DrawableBitmap extends DrawableObject {
private Texture mTexture;
private float mWidth;
private float mHeight;
private int mCrop[];
private int mViewWidth;
private int mViewHeight;
private iBitmapInImageCache mBitmapInImageCacheeBitmapChange;
private boolean isChangeBitmap;
private boolean isRemoveBitmapAffterChange;
private boolean isSetColorExpress;
private float red;
private float green;
private float blue;
private float alpha;
private boolean ONE_MINUS_SRC_ALPHA = false;
private boolean IsEnableGlBlend = false;
private int glBlend1 = GL10.GL_ONE;
private int glBlend2 = GL10.GL_ONE_MINUS_SRC_ALPHA;
public void setGlBlendFun(int scrColour, int destColour) {
glBlend1 = scrColour;
glBlend2 = destColour;
IsEnableGlBlend = true;
}
public DrawableBitmap(Texture texture, float width, float height) {
super();
mTexture = texture;
mWidth = width;
mHeight = height;
mCrop = new int[4];
mViewWidth = 0;
mViewHeight = 0;
isSetColorExpress = false;
red = 1;
green = 1;
blue = 1;
alpha = 1;
setCrop(0, 0, 1, 1);
isChangeBitmap = false;
isRemoveBitmapAffterChange = false;
}
public void reset() {
mTexture = null;
mViewWidth = 0;
mViewHeight = 0;
}
public void setViewSize(int width, int height) {
mViewHeight = height;
mViewWidth = width;
}
public void setOpacity(float opacity) {
alpha = opacity;
isSetColorExpress = true;
}
public float getOpacity() {
return alpha;
}
/**
* Begins drawing bitmaps. Sets the OpenGL state for rapid drawing.
*
* @param gl
* A pointer to the OpenGL context.
* @param viewWidth
* The width of the screen.
* @param viewHeight
* The height of the screen.
*/
public static void beginDrawing(GL10 gl, float viewWidth, float viewHeight) {
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPushMatrix();
gl.glLoadIdentity();
// TODO: nho xoa
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glEnable(GL10.GL_TEXTURE_2D);
}
/**
* Draw the bitmap at a given x,y position, expressed in pixels, with the
* lower-left-hand-corner of the view being (0,0).
*
* @param gl
* A pointer to the OpenGL context
* @param x
* The number of pixels to offset this drawable's origin in the
* x-axis.
* @param y
* The number of pixels to offset this drawable's origin in the
* y-axis
* @param scaleX
* The horizontal scale factor between the bitmap resolution and
* the display resolution.
* @param scaleY
* The vertical scale factor between the bitmap resolution and
* the display resolution.
*/
@Override
public void draw(float x, float y, float scaleX, float scaleY) {
final Texture texture = mTexture;
if (texture != null) {
GL10 gl = OpenGLSystem.getGL();
if (isChangeBitmap) {
setBitmapChange(gl);
}
if (gl != null) {
if (texture.resource != -1 && texture.loaded == false) {
BaseObject.sSystemRegistry.longTermTextureLibrary
.loadBitmap(
BaseObject.sSystemRegistry.contextParameters.context,
gl, texture);
}
assert texture.loaded;
final float snappedX = x;
final float snappedY = y;
final float opacity = alpha;
final float width = mWidth;
final float height = mHeight;
final float viewWidth = mViewWidth;
final float viewHeight = mViewHeight;
boolean cull = false;
if (viewWidth > 0) {
if (snappedX + width < 0.0f || snappedX > viewWidth
|| snappedY + height < 0.0f
|| snappedY > viewHeight || opacity == 0.0f
|| !texture.loaded) {
cull = true;
}
}
if (!cull) {
OpenGLSystem.bindTexture(GL10.GL_TEXTURE_2D, texture.name);
// This is necessary because we could be drawing the same
// texture with different
// crop (say, flipped horizontally) on the same frame.
OpenGLSystem.setTextureCrop(mCrop);
if (isSetColorExpress) {
if (!ONE_MINUS_SRC_ALPHA) {
gl.glColor4f(red * alpha, green * alpha, blue
* alpha, alpha);
} else {
gl.glColor4f(red, green, blue, alpha);
}
}
if (IsEnableGlBlend) {
gl.glBlendFunc(glBlend1, glBlend2);
// gl.glEnable(GL10.GL_STENCIL_TEST);
// gl.glStencilFunc(GL10.GL_ALWAYS, 0x1, 0x1);
// gl.glStencilFunc(GL10.GL_EQUAL, 0x0, 0x1);
// IntBuffer intBuffer = IntBuffer.allocate(1);
}
((GL11Ext) gl).glDrawTexfOES(snappedX * scaleX, snappedY
* scaleY, getPriority(), width * scaleX, height
* scaleY);
if (isSetColorExpress) {
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}
if (IsEnableGlBlend) {
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
// gl.glDisable(GL10.GL_STENCIL_TEST);
}
}
}
}
}
/**
* Ends the drawing and restores the OpenGL state.
*
* @param gl
* A pointer to the OpenGL context.
*/
public static void endDrawing(GL10 gl) {
gl.glDisable(GL10.GL_BLEND);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPopMatrix();
}
public void resize(int width, int height) {
mWidth = width;
mHeight = height;
setCrop(0, height, width, height);
}
public float getWidth() {
return mWidth;
}
public void setWidth(float width) {
mWidth = width;
}
public float getHeight() {
return mHeight;
}
public void setHeight(float height) {
mHeight = height;
}
/**
* Changes the crop parameters of this bitmap. Note that the underlying
* OpenGL texture's parameters are not changed immediately The crop is
* updated on the next call to draw(). Note that the image may be flipped by
* providing a negative width or height.
*
* @param left
* @param bottom
* @param width
* @param height
*/
public void setCrop(int left, int bottom, int width, int height) {
// Negative width and height values will flip the image.
mCrop[0] = left;
mCrop[1] = bottom;
mCrop[2] = width;
mCrop[3] = -height;
}
public int[] getCrop() {
return mCrop;
}
public void setTexture(Texture texture) {
mTexture = texture;
}
@Override
public Texture getTexture() {
return mTexture;
}
@Override
public boolean visibleAtPosition(Vector2 position) {
boolean cull = false;
if (mViewWidth > 0) {
if (position.x + mWidth < 0 || position.x > mViewWidth
|| position.y + mHeight < 0 || position.y > mViewHeight) {
cull = true;
}
}
return !cull;
}
public final void setFlip(boolean horzFlip, boolean vertFlip) {
setCrop(horzFlip ? (int) mWidth : 0, vertFlip ? 0 : (int) mHeight,
horzFlip ? -(int) mWidth : (int) mWidth,
vertFlip ? -(int) mHeight : (int) mHeight);
}
public void changeBitmap(iBitmapInImageCache bitmap, boolean isRemove) {
mBitmapInImageCacheeBitmapChange = bitmap;
isRemoveBitmapAffterChange = isRemove;
isChangeBitmap = true;
}
private void setBitmapChange(GL10 gl) {
int[] mTextureNameWorkspace = new int[1];
mTextureNameWorkspace[0] = mTexture.name;
gl.glDeleteTextures(1, mTextureNameWorkspace, 0);
Bitmap mBitmapChange = null;
if (mBitmapInImageCacheeBitmapChange != null) {
mBitmapChange = mBitmapInImageCacheeBitmapChange
.getBitMapResourcesItem();
}
if (mBitmapChange != null) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTexture.name);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE); // GL10.GL_REPLACE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmapChange, 0);
int[] mCropWorkspace = new int[4];
mCropWorkspace[0] = 0;
mCropWorkspace[1] = mBitmapChange.getHeight();
mCropWorkspace[2] = mBitmapChange.getWidth();
mCropWorkspace[3] = -mBitmapChange.getHeight();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
mTexture.width = mBitmapChange.getWidth();
mTexture.height = mBitmapChange.getHeight();
if (isRemoveBitmapAffterChange) {
mBitmapChange.recycle();
}
mBitmapChange = null;
isChangeBitmap = false;
} else {
// Delete
mTexture.reset();
mTexture = null;
}
}
public void setCoordinates(float x1, float y1, float x2, float y2) {
setCrop((int) (x1 * mTexture.width),//
(int) (y2 * mTexture.height)//
, (int) (mTexture.width * (x2 - x1)), //
(int) (mTexture.height * (y2 - y1)));
}
public void setColorExpress(int r, int g, int b, int a) {
float tamp = 1.0f / 255;
red = tamp * r;
green = tamp * g;
blue = tamp * b;
alpha = tamp * a;
isSetColorExpress = true;
}
public void setColorExpressF(float r, float g, float b, float a) {
red = r;
green = g;
blue = b;
alpha = a;
isSetColorExpress = true;
}
public void setDefaultColour() {
isSetColorExpress = false;
}
public void setONE_MINUS_SRC_ALPHA(boolean b) {
ONE_MINUS_SRC_ALPHA = b;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/DrawableBitmap.java | Java | oos | 10,288 |
package org.vn.gl;
import android.graphics.Bitmap;
public interface iBitmapInImageCache {
public Bitmap getBitMapResourcesItem();
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/iBitmapInImageCache.java | Java | oos | 144 |
package org.vn.gl;
import java.io.Writer;
import java.util.ArrayList;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLDebugHelper;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GLSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private final static boolean LOG_THREADS = false;
private final static boolean LOG_SURFACE = true;
private final static boolean LOG_RENDERER = false;
// Work-around for bug 2263168
private final static boolean DRAW_TWICE_AFTER_SIZE_CHANGED = true;
/**
* The renderer only renders when the surface is created, or when
* {@link #requestRender} is called.
*
* @see #getRenderMode()
* @see #setRenderMode(int)
*/
public final static int RENDERMODE_WHEN_DIRTY = 0;
/**
* The renderer is called continuously to re-render the scene.
*
* @see #getRenderMode()
* @see #setRenderMode(int)
* @see #requestRender()
*/
public final static int RENDERMODE_CONTINUOUSLY = 1;
/**
* Check glError() after every GL call and throw an exception if glError
* indicates that an error has occurred. This can be used to help track down
* which OpenGL ES call is causing an error.
*
* @see #getDebugFlags
* @see #setDebugFlags
*/
public final static int DEBUG_CHECK_GL_ERROR = 1;
/**
* Log GL calls to the system log at "verbose" level with tag
* "GLSurfaceView".
*
* @see #getDebugFlags
* @see #setDebugFlags
*/
public final static int DEBUG_LOG_GL_CALLS = 2;
/**
* Standard View constructor. In order to render something, you must call
* {@link #setRenderer} to register a renderer.
*/
public GLSurfaceView(Context context) {
super(context);
init();
}
/**
* Standard View constructor. In order to render something, you must call
* {@link #setRenderer} to register a renderer.
*/
public GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
SurfaceHolder holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
/**
* Set the glWrapper. If the glWrapper is not null, its
* {@link GLWrapper#wrap(GL)} method is called whenever a surface is
* created. A GLWrapper can be used to wrap the GL object that's passed to
* the renderer. Wrapping a GL object enables examining and modifying the
* behavior of the GL calls made by the renderer.
* <p>
* Wrapping is typically used for debugging purposes.
* <p>
* The default value is null.
*
* @param glWrapper
* the new GLWrapper
*/
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
/**
* Set the debug flags to a new value. The value is constructed by
* OR-together zero or more of the DEBUG_CHECK_* constants. The debug flags
* take effect whenever a surface is created. The default value is zero.
*
* @param debugFlags
* the new debug flags
* @see #DEBUG_CHECK_GL_ERROR
* @see #DEBUG_LOG_GL_CALLS
*/
public void setDebugFlags(int debugFlags) {
mDebugFlags = debugFlags;
}
/**
* Get the current value of the debug flags.
*
* @return the current value of the debug flags.
*/
public int getDebugFlags() {
return mDebugFlags;
}
/**
* Set the renderer associated with this view. Also starts the thread that
* will call the renderer, which in turn causes the rendering to start.
* <p>
* This method should be called once and only once in the life-cycle of a
* GLSurfaceView.
* <p>
* The following GLSurfaceView methods can only be called <em>before</em>
* setRenderer is called:
* <ul>
* <li>{@link #setEGLConfigChooser(boolean)}
* <li>{@link #setEGLConfigChooser(EGLConfigChooser)}
* <li>{@link #setEGLConfigChooser(int, int, int, int, int, int)}
* </ul>
* <p>
* The following GLSurfaceView methods can only be called <em>after</em>
* setRenderer is called:
* <ul>
* <li>{@link #getRenderMode()}
* <li>{@link #onPause()}
* <li>{@link #onResume()}
* <li>{@link #queueEvent(Runnable)}
* <li>{@link #requestRender()}
* <li>{@link #setRenderMode(int)}
* </ul>
*
* @param renderer
* the renderer to use to perform OpenGL drawing.
*/
public void setRenderer(Renderer renderer) {
checkRenderThreadState();
if (mEGLConfigChooser == null) {
mEGLConfigChooser = new SimpleEGLConfigChooser(true);
}
if (mEGLContextFactory == null) {
mEGLContextFactory = new DefaultContextFactory();
}
if (mEGLWindowSurfaceFactory == null) {
mEGLWindowSurfaceFactory = new DefaultWindowSurfaceFactory();
}
mGLThread = new GLThread(renderer);
mGLThread.setName("GLThread_InGame");
mGLThread.start();
}
/**
* Install a custom EGLContextFactory.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* If this method is not called, then by default a context will be created
* with no shared context and with a null attribute list.
*/
public void setEGLContextFactory(EGLContextFactory factory) {
checkRenderThreadState();
mEGLContextFactory = factory;
}
/**
* Install a custom EGLWindowSurfaceFactory.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* If this method is not called, then by default a window surface will be
* created with a null attribute list.
*/
public void setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory factory) {
checkRenderThreadState();
mEGLWindowSurfaceFactory = factory;
}
/**
* Install a custom EGLConfigChooser.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* If no setEGLConfigChooser method is called, then by default the view will
* choose a config as close to 16-bit RGB as possible, with a depth buffer
* as close to 16 bits as possible.
*
* @param configChooser
*/
public void setEGLConfigChooser(EGLConfigChooser configChooser) {
checkRenderThreadState();
mEGLConfigChooser = configChooser;
}
/**
* Install a config chooser which will choose a config as close to 16-bit
* RGB as possible, with or without an optional depth buffer as close to
* 16-bits as possible.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* If no setEGLConfigChooser method is called, then by default the view will
* choose a config as close to 16-bit RGB as possible, with a depth buffer
* as close to 16 bits as possible.
*
* @param needDepth
*/
public void setEGLConfigChooser(boolean needDepth) {
setEGLConfigChooser(new SimpleEGLConfigChooser(needDepth));
}
/**
* Install a config chooser which will choose a config with at least the
* specified component sizes, and as close to the specified component sizes
* as possible.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* If no setEGLConfigChooser method is called, then by default the view will
* choose a config as close to 16-bit RGB as possible, with a depth buffer
* as close to 16 bits as possible.
*
*/
public void setEGLConfigChooser(int redSize, int greenSize, int blueSize,
int alphaSize, int depthSize, int stencilSize) {
setEGLConfigChooser(new ComponentSizeChooser(redSize, greenSize,
blueSize, alphaSize, depthSize, stencilSize));
}
/**
* Inform the default EGLContextFactory and default EGLConfigChooser which
* EGLContext client version to pick.
* <p>
* Use this method to create an OpenGL ES 2.0-compatible context. Example:
*
* <pre class="prettyprint">
* public MyView(Context context) {
* super(context);
* setEGLContextClientVersion(2); // Pick an OpenGL ES 2.0 context.
* setRenderer(new MyRenderer());
* }
* </pre>
* <p>
* Note: Activities which require OpenGL ES 2.0 should indicate this by
* setting @lt;uses-feature android:glEsVersion="0x00020000" /> in the
* activity's AndroidManifest.xml file.
* <p>
* If this method is called, it must be called before
* {@link #setRenderer(Renderer)} is called.
* <p>
* This method only affects the behavior of the default EGLContexFactory and
* the default EGLConfigChooser. If
* {@link #setEGLContextFactory(EGLContextFactory)} has been called, then
* the supplied EGLContextFactory is responsible for creating an OpenGL ES
* 2.0-compatible context. If {@link #setEGLConfigChooser(EGLConfigChooser)}
* has been called, then the supplied EGLConfigChooser is responsible for
* choosing an OpenGL ES 2.0-compatible config.
*
* @param version
* The EGLContext client version to choose. Use 2 for OpenGL ES
* 2.0
*/
public void setEGLContextClientVersion(int version) {
checkRenderThreadState();
mEGLContextClientVersion = version;
}
/**
* Set the rendering mode. When renderMode is RENDERMODE_CONTINUOUSLY, the
* renderer is called repeatedly to re-render the scene. When renderMode is
* RENDERMODE_WHEN_DIRTY, the renderer only rendered when the surface is
* created, or when {@link #requestRender} is called. Defaults to
* RENDERMODE_CONTINUOUSLY.
* <p>
* Using RENDERMODE_WHEN_DIRTY can improve battery life and overall system
* performance by allowing the GPU and CPU to idle when the view does not
* need to be updated.
* <p>
* This method can only be called after {@link #setRenderer(Renderer)}
*
* @param renderMode
* one of the RENDERMODE_X constants
* @see #RENDERMODE_CONTINUOUSLY
* @see #RENDERMODE_WHEN_DIRTY
*/
public void setRenderMode(int renderMode) {
mGLThread.setRenderMode(renderMode);
}
/**
* Get the current rendering mode. May be called from any thread. Must not
* be called before a renderer has been set.
*
* @return the current rendering mode.
* @see #RENDERMODE_CONTINUOUSLY
* @see #RENDERMODE_WHEN_DIRTY
*/
public int getRenderMode() {
return mGLThread.getRenderMode();
}
/**
* Request that the renderer render a frame. This method is typically used
* when the render mode has been set to {@link #RENDERMODE_WHEN_DIRTY}, so
* that frames are only rendered on demand. May be called from any thread.
* Must not be called before a renderer has been set.
*/
public void requestRender() {
mGLThread.requestRender();
}
/**
* This method is part of the SurfaceHolder.Callback interface, and is not
* normally called or subclassed by clients of GLSurfaceView.
*/
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
/**
* This method is part of the SurfaceHolder.Callback interface, and is not
* normally called or subclassed by clients of GLSurfaceView.
*/
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
/**
* This method is part of the SurfaceHolder.Callback interface, and is not
* normally called or subclassed by clients of GLSurfaceView.
*/
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused. The owner of this view must
* call this method when the activity is paused. Calling this method will
* pause the rendering thread. Must not be called before a renderer has been
* set.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed. The owner of this view must
* call this method when the activity is resumed. Calling this method will
* recreate the OpenGL display and resume the rendering thread. Must not be
* called before a renderer has been set.
*/
public void onResume() {
mGLThread.onResume();
}
public void flushTextures(TextureLibrary library) {
mGLThread.flushTextures(library);
}
public void flushAll() {
mGLThread.flushAll();
}
public void loadTextures(TextureLibrary library) {
mGLThread.loadTextures(library);
}
public void setSafeMode(boolean safeMode) {
mGLThread.setSafeMode(safeMode);
}
/**
* Queue a runnable to be run on the GL rendering thread. This can be used
* to communicate with the Renderer on the rendering thread. Must not be
* called before a renderer has been set.
*
* @param r
* the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
mGLThread.queueEvent(r);
}
/**
* Inform the view that the window focus has changed.
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* This method is used as part of the View class and is not normally called
* or subclassed by clients of GLSurfaceView. Must not be called before a
* renderer has been set.
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
/**
* An interface used to wrap a GL interface.
* <p>
* Typically used for implementing debugging and tracing on top of the
* default GL interface. You would typically use this by creating your own
* class that implemented all the GL methods by delegating to another GL
* instance. Then you could add your own behavior before or after calling
* the delegate. All the GLWrapper would do was instantiate and return the
* wrapper GL instance:
*
* <pre class="prettyprint">
* class MyGLWrapper implements GLWrapper {
* GL wrap(GL gl) {
* return new MyGLImplementation(gl);
* }
* static class MyGLImplementation implements GL,GL10,GL11,... {
* ...
* }
* }
* </pre>
*
* @see #setGLWrapper(GLWrapper)
*/
public interface GLWrapper {
/**
* Wraps a gl interface in another gl interface.
*
* @param gl
* a GL interface that is to be wrapped.
* @return either the input argument or another GL object that wraps the
* input argument.
*/
GL wrap(GL gl);
}
/**
* A generic renderer interface.
* <p>
* The renderer is responsible for making OpenGL calls to render a frame.
* <p>
* GLSurfaceView clients typically create their own classes that implement
* this interface, and then call {@link GLSurfaceView#setRenderer} to
* register the renderer with the GLSurfaceView.
* <p>
* <h3>Threading</h3>
* The renderer will be called on a separate thread, so that rendering
* performance is decoupled from the UI thread. Clients typically need to
* communicate with the renderer from the UI thread, because that's where
* input events are received. Clients can communicate using any of the
* standard Java techniques for cross-thread communication, or they can use
* the {@link GLSurfaceView#queueEvent(Runnable)} convenience method.
* <p>
* <h3>EGL Context Lost</h3>
* There are situations where the EGL rendering context will be lost. This
* typically happens when device wakes up after going to sleep. When the EGL
* context is lost, all OpenGL resources (such as textures) that are
* associated with that context will be automatically deleted. In order to
* keep rendering correctly, a renderer must recreate any lost resources
* that it still needs. The {@link #onSurfaceCreated(GL10, EGLConfig)}
* method is a convenient place to do this.
*
*
* @see #setRenderer(Renderer)
*/
public interface Renderer {
/**
* Called when the surface is created or recreated.
* <p>
* Called when the rendering thread starts and whenever the EGL context
* is lost. The context will typically be lost when the Android device
* awakes after going to sleep.
* <p>
* Since this method is called at the beginning of rendering, as well as
* every time the EGL context is lost, this method is a convenient place
* to put code to create resources that need to be created when the
* rendering starts, and that need to be recreated when the EGL context
* is lost. Textures are an example of a resource that you might want to
* create here.
* <p>
* Note that when the EGL context is lost, all OpenGL resources
* associated with that context will be automatically deleted. You do
* not need to call the corresponding "glDelete" methods such as
* glDeleteTextures to manually delete these lost resources.
* <p>
*
* @param gl
* the GL interface. Use <code>instanceof</code> to test if
* the interface supports GL11 or higher interfaces.
* @param config
* the EGLConfig of the created surface. Can be used to
* create matching pbuffers.
*/
void onSurfaceCreated(GL10 gl, EGLConfig config);
/**
* Called when the surface changed size.
* <p>
* Called after the surface is created and whenever the OpenGL ES
* surface size changes.
* <p>
* Typically you will set your viewport here. If your camera is fixed
* then you could also set your projection matrix here:
*
* <pre class="prettyprint">
* void onSurfaceChanged(GL10 gl, int width, int height) {
* gl.glViewport(0, 0, width, height);
* // for a fixed camera, set the projection too
* float ratio = (float) width / height;
* gl.glMatrixMode(GL10.GL_PROJECTION);
* gl.glLoadIdentity();
* gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
* }
* </pre>
*
* @param gl
* the GL interface. Use <code>instanceof</code> to test if
* the interface supports GL11 or higher interfaces.
* @param width
* @param height
*/
void onSurfaceChanged(GL10 gl, int width, int height);
/**
* Called when the OpenGL context has been lost is about to be
* recreated. onSurfaceCreated() will be called after onSurfaceLost().
* */
void onSurfaceLost();
/**
* Called to draw the current frame.
* <p>
* This method is responsible for drawing the current frame.
* <p>
* The implementation of this method typically looks like this:
*
* <pre class="prettyprint">
* void onDrawFrame(GL10 gl) {
* gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
* // ... other gl calls to render the scene ...
* }
* </pre>
*
* @param gl
* the GL interface. Use <code>instanceof</code> to test if
* the interface supports GL11 or higher interfaces.
*/
void onDrawFrame(GL10 gl);
void loadTextures(GL10 gl, TextureLibrary library);
void flushTextures(GL10 gl, TextureLibrary library);
}
/**
* An interface for customizing the eglCreateContext and eglDestroyContext
* calls.
* <p>
* This interface must be implemented by clients wishing to call
* {@link GLSurfaceView#setEGLContextFactory(EGLContextFactory)}
*/
public interface EGLContextFactory {
EGLContext createContext(EGL10 egl, EGLDisplay display,
EGLConfig eglConfig);
void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context);
}
private class DefaultContextFactory implements EGLContextFactory {
private int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
public EGLContext createContext(EGL10 egl, EGLDisplay display,
EGLConfig config) {
int[] attrib_list = { EGL_CONTEXT_CLIENT_VERSION,
mEGLContextClientVersion, EGL10.EGL_NONE };
return egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT,
mEGLContextClientVersion != 0 ? attrib_list : null);
}
public void destroyContext(EGL10 egl, EGLDisplay display,
EGLContext context) {
egl.eglDestroyContext(display, context);
}
}
/**
* An interface for customizing the eglCreateWindowSurface and
* eglDestroySurface calls.
* <p>
* This interface must be implemented by clients wishing to call
* {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
*/
public interface EGLWindowSurfaceFactory {
EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
EGLConfig config, Object nativeWindow);
void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
}
private static class DefaultWindowSurfaceFactory implements
EGLWindowSurfaceFactory {
public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
EGLConfig config, Object nativeWindow) {
return egl.eglCreateWindowSurface(display, config, nativeWindow,
null);
}
public void destroySurface(EGL10 egl, EGLDisplay display,
EGLSurface surface) {
egl.eglDestroySurface(display, surface);
}
}
/**
* An interface for choosing an EGLConfig configuration from a list of
* potential configurations.
* <p>
* This interface must be implemented by clients wishing to call
* {@link GLSurfaceView#setEGLConfigChooser(EGLConfigChooser)}
*/
public interface EGLConfigChooser {
/**
* Choose a configuration from the list. Implementors typically
* implement this method by calling {@link EGL10#eglChooseConfig} and
* iterating through the results. Please consult the EGL specification
* available from The Khronos Group to learn how to call
* eglChooseConfig.
*
* @param egl
* the EGL10 for the current display.
* @param display
* the current display.
* @return the chosen configuration.
*/
EGLConfig chooseConfig(EGL10 egl, EGLDisplay display);
}
private abstract class BaseConfigChooser implements EGLConfigChooser {
public BaseConfigChooser(int[] configSpec) {
mConfigSpec = filterConfigSpec(configSpec);
}
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display) {
int[] num_config = new int[1];
if (!egl.eglChooseConfig(display, mConfigSpec, null, 0, num_config)) {
throw new IllegalArgumentException("eglChooseConfig failed");
}
int numConfigs = num_config[0];
if (numConfigs <= 0) {
throw new IllegalArgumentException(
"No configs match configSpec");
}
EGLConfig[] configs = new EGLConfig[numConfigs];
if (!egl.eglChooseConfig(display, mConfigSpec, configs, numConfigs,
num_config)) {
throw new IllegalArgumentException("eglChooseConfig#2 failed");
}
EGLConfig config = chooseConfig(egl, display, configs);
if (config == null) {
throw new IllegalArgumentException("No config chosen");
}
return config;
}
abstract EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs);
protected int[] mConfigSpec;
private int[] filterConfigSpec(int[] configSpec) {
if (mEGLContextClientVersion != 2) {
return configSpec;
}
/*
* We know none of the subclasses define EGL_RENDERABLE_TYPE. And we
* know the configSpec is well formed.
*/
int len = configSpec.length;
int[] newConfigSpec = new int[len + 2];
System.arraycopy(configSpec, 0, newConfigSpec, 0, len - 1);
newConfigSpec[len - 1] = EGL10.EGL_RENDERABLE_TYPE;
newConfigSpec[len] = 4; /* EGL_OPENGL_ES2_BIT */
newConfigSpec[len + 1] = EGL10.EGL_NONE;
return newConfigSpec;
}
}
private class ComponentSizeChooser extends BaseConfigChooser {
public ComponentSizeChooser(int redSize, int greenSize, int blueSize,
int alphaSize, int depthSize, int stencilSize) {
super(new int[] { EGL10.EGL_RED_SIZE, redSize,
EGL10.EGL_GREEN_SIZE, greenSize, EGL10.EGL_BLUE_SIZE,
blueSize, EGL10.EGL_ALPHA_SIZE, alphaSize,
EGL10.EGL_DEPTH_SIZE, depthSize, EGL10.EGL_STENCIL_SIZE,
stencilSize, EGL10.EGL_NONE });
mValue = new int[1];
mRedSize = redSize;
mGreenSize = greenSize;
mBlueSize = blueSize;
mAlphaSize = alphaSize;
mDepthSize = depthSize;
mStencilSize = stencilSize;
}
@Override
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs) {
EGLConfig closestConfig = null;
int closestDistance = 1000;
for (EGLConfig config : configs) {
int d = findConfigAttrib(egl, display, config,
EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config,
EGL10.EGL_STENCIL_SIZE, 0);
if (d >= mDepthSize && s >= mStencilSize) {
int r = findConfigAttrib(egl, display, config,
EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config,
EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config,
EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config,
EGL10.EGL_ALPHA_SIZE, 0);
int distance = Math.abs(r - mRedSize)
+ Math.abs(g - mGreenSize)
+ Math.abs(b - mBlueSize)
+ Math.abs(a - mAlphaSize);
if (distance < closestDistance) {
closestDistance = distance;
closestConfig = config;
}
}
}
return closestConfig;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue) {
if (egl.eglGetConfigAttrib(display, config, attribute, mValue)) {
return mValue[0];
}
return defaultValue;
}
private int[] mValue;
// Subclasses can adjust these values:
protected int mRedSize;
protected int mGreenSize;
protected int mBlueSize;
protected int mAlphaSize;
protected int mDepthSize;
protected int mStencilSize;
}
/**
* This class will choose a supported surface as close to RGB565 as
* possible, with or without a depth buffer.
*
*/
private class SimpleEGLConfigChooser extends ComponentSizeChooser {
public SimpleEGLConfigChooser(boolean withDepthBuffer) {
super(4, 4, 4, 0, withDepthBuffer ? 16 : 0, 0);
// Adjust target values. This way we'll accept a 4444 or
// 555 buffer if there's no 565 buffer available.
mRedSize = 5;
mGreenSize = 6;
mBlueSize = 5;
}
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
*
* @param configSpec
*/
public void start() {
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (mEglDisplay == EGL10.EGL_NO_DISPLAY) {
throw new RuntimeException("eglGetDisplay failed");
}
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
if (!mEgl.eglInitialize(mEglDisplay, version)) {
throw new RuntimeException("eglInitialize failed");
}
mEglConfig = mEGLConfigChooser.chooseConfig(mEgl, mEglDisplay);
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEGLContextFactory.createContext(mEgl, mEglDisplay,
mEglConfig);
if (mEglContext == null || mEglContext == EGL10.EGL_NO_CONTEXT) {
throwEglException("createContext");
}
mEglSurface = null;
}
/*
* React to the creation of a new surface by creating and returning an
* OpenGL interface that renders to that surface.
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new surface.
*/
if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
/*
* Unbind and destroy the old EGL surface, if there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay,
mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEGLWindowSurfaceFactory.createWindowSurface(mEgl,
mEglDisplay, mEglConfig, holder);
if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
throwEglException("createWindowSurface");
}
/*
* Before we can issue GL commands, we need to make sure the context
* is current and bound to a surface.
*/
if (!mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext)) {
throwEglException("eglMakeCurrent");
}
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) {
int configFlags = 0;
Writer log = null;
if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
configFlags |= GLDebugHelper.CONFIG_CHECK_GL_ERROR;
}
if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
log = new LogWriter();
}
gl = GLDebugHelper.wrap(gl, configFlags, log);
}
return gl;
}
/**
* Display the current render surface.
*
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context and
* all associated data were lost (For instance because the device
* went to sleep). We need to sleep until we get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void destroySurface() {
if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEGLWindowSurfaceFactory.destroySurface(mEgl, mEglDisplay,
mEglSurface);
mEglSurface = null;
}
}
public void finish() {
if (mEglContext != null) {
mEGLContextFactory.destroyContext(mEgl, mEglDisplay,
mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
private void throwEglException(String function) {
throw new RuntimeException(function + " failed: "
+ mEgl.eglGetError());
}
/** Checks to see if the current context is valid. **/
public boolean verifyContext() {
EGLContext currentContext = mEgl.eglGetCurrentContext();
return currentContext != EGL10.EGL_NO_CONTEXT
&& mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates to
* a Renderer instance to do the actual drawing. Can be configured to render
* continuously or on request.
*
* All potentially blocking synchronization is done through the
* sGLThreadManager object. This avoids multiple-lock ordering issues.
*
*/
private class GLThread extends Thread {
public GLThread(Renderer renderer) {
super();
mWidth = 0;
mHeight = 0;
mRequestRender = true;
mRenderMode = RENDERMODE_CONTINUOUSLY;
mRenderer = renderer;
}
@Override
public void run() {
setName("GLThread " + getId());
if (LOG_THREADS) {
DebugLog.i("GLThread", "starting tid=" + getId());
}
GameRenderer.isDeleteGLDone = false;
try {
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sGLThreadManager.threadExiting(this);
}
}
/*
* This private method should only be called inside a
* synchronized(sGLThreadManager) block.
*/
private void stopEglLocked() {
if (mHaveEglSurface) {
mHaveEglSurface = false;
mEglHelper.destroySurface();
sGLThreadManager.releaseEglSurfaceLocked(this);
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
mHaveEglContext = false;
mHaveEglSurface = false;
try {
GL10 gl = null;
boolean createEglSurface = false;
boolean sizeChanged = false;
boolean wantRenderNotification = false;
boolean doRenderNotification = false;
int w = 0;
int h = 0;
Runnable event = null;
int framesSinceResetHack = 0;
boolean finish = false;
while (!finish) {
synchronized (sGLThreadManager) {
while (true) {
if (mShouldExit) {
return;
}
if (!mEventQueue.isEmpty()) {
event = mEventQueue.remove(0);
break;
}
// Do we need to release the EGL surface?
if (mHaveEglSurface && mPaused) {
if (LOG_SURFACE) {
DebugLog.i("GLThread",
"releasing EGL surface because paused tid="
+ getId());
}
stopEglLocked();
}
// Have we lost the surface view surface?
if ((!mHasSurface) && (!mWaitingForSurface)) {
if (LOG_SURFACE) {
DebugLog.i("GLThread",
"noticed surfaceView surface lost tid="
+ getId());
}
if (mHaveEglSurface) {
stopEglLocked();
}
mWaitingForSurface = true;
sGLThreadManager.notifyAll();
}
// Have we acquired the surface view surface?
if (mHasSurface && mWaitingForSurface) {
if (LOG_SURFACE) {
DebugLog.i("GLThread",
"noticed surfaceView surface acquired tid="
+ getId());
}
mWaitingForSurface = false;
sGLThreadManager.notifyAll();
}
if (doRenderNotification) {
wantRenderNotification = false;
doRenderNotification = false;
mRenderComplete = true;
sGLThreadManager.notifyAll();
}
// Ready to draw?
if ((!mPaused)
&& mHasSurface
&& (mWidth > 0)
&& (mHeight > 0)
&& (mRequestRender || (mRenderMode == RENDERMODE_CONTINUOUSLY))) {
if (mHaveEglContext && !mHaveEglSurface) {
// Let's make sure the context hasn't been
// lost.
// TODO: check lai khi ra ngoai man hinh han
// ben duoi dc goi
// if (!mEglHelper.verifyContext()) {
// mEglHelper.finish();
// mRenderer.onSurfaceLost();
// mHaveEglContext = false;
// }
}
// If we don't have an egl surface, try to
// acquire one.
if ((!mHaveEglContext)
&& sGLThreadManager
.tryAcquireEglSurfaceLocked(this)) {
mHaveEglContext = true;
mEglHelper.start();
sGLThreadManager.notifyAll();
}
if (mHaveEglContext && !mHaveEglSurface) {
mHaveEglSurface = true;
createEglSurface = true;
sizeChanged = true;
}
if (mHaveEglSurface) {
if (mSizeChanged) {
sizeChanged = true;
w = mWidth;
h = mHeight;
wantRenderNotification = true;
if (DRAW_TWICE_AFTER_SIZE_CHANGED) {
// We keep mRequestRender true so
// that we draw twice after the size
// changes.
// (Once because of mSizeChanged,
// the second time because of
// mRequestRender.)
// This forces the updated graphics
// onto the screen.
} else {
mRequestRender = false;
}
mSizeChanged = false;
} else {
mRequestRender = false;
}
sGLThreadManager.notifyAll();
break;
}
}
// By design, this is the only place in a GLThread
// thread where we wait().
if (LOG_THREADS) {
DebugLog.i("GLThread", "waiting tid=" + getId());
}
sGLThreadManager.wait();
}
} // end of synchronized(sGLThreadManager)
if (event != null) {
event.run();
event = null;
continue;
}
if (mHasFocus) {
if (createEglSurface) {
gl = (GL10) mEglHelper.createSurface(getHolder());
sGLThreadManager.checkGLDriver(gl);
if (LOG_RENDERER) {
DebugLog.w("GLThread", "onSurfaceCreated");
}
mGL = gl;
mRenderer.onSurfaceCreated(gl,
mEglHelper.mEglConfig);
createEglSurface = false;
framesSinceResetHack = 0;
}
if (sizeChanged) {
if (LOG_RENDERER) {
DebugLog.w("GLThread", "onSurfaceChanged(" + w
+ ", " + h + ")");
}
mRenderer.onSurfaceChanged(gl, w, h);
sizeChanged = false;
}
if (LOG_RENDERER) {
DebugLog.w("GLThread", "onDrawFrame");
}
// Some phones (Motorola Cliq, Backflip; also the
// Huawei Pulse, and maybe the Samsung Behold II), use a
// broken graphics driver from Qualcomm. It fails in a
// very specific case: when the EGL context is lost due
// to
// resource constraints, and then recreated, if GL
// commands
// are sent within two frames of the surface being
// created
// then eglSwapBuffers() will hang. Normally,
// applications using
// the stock GLSurfaceView never run into this problem
// because it
// discards the EGL context explicitly on every pause.
// But
// I've modified this class to not do that--I only want
// to reload
// textures when the context is actually lost--so this
// bug
// revealed itself as black screens on devices like the
// Cliq.
// Thus, in "safe mode," I force two swaps to occur
// before
// issuing any GL commands. Don't ask me how long it
// took
// to figure this out.
if (framesSinceResetHack > 1 || !mSafeMode) {
mRenderer.onDrawFrame(gl);
} else {
DebugLog.w("GLThread", "Safe Mode Wait...");
}
if (GameRenderer.isDeleteGLDone) {
finish = true;
}
framesSinceResetHack++;
if (!mEglHelper.swap()) {
if (LOG_SURFACE) {
DebugLog.i("GLThread", "egl surface lost tid="
+ getId());
}
stopEglLocked();
}
}
if (wantRenderNotification) {
doRenderNotification = true;
}
if (finish) {
DebugLog.d("DUC", "END RenderThread :)");
}
}
} finally {
mGL = null;
/*
* clean-up everything...
*/
synchronized (sGLThreadManager) {
stopEglLocked();
mEglHelper.finish();
}
}
}
public void setRenderMode(int renderMode) {
if (!((RENDERMODE_WHEN_DIRTY <= renderMode) && (renderMode <= RENDERMODE_CONTINUOUSLY))) {
throw new IllegalArgumentException("renderMode");
}
synchronized (sGLThreadManager) {
mRenderMode = renderMode;
sGLThreadManager.notifyAll();
}
}
public int getRenderMode() {
synchronized (sGLThreadManager) {
return mRenderMode;
}
}
public void requestRender() {
synchronized (sGLThreadManager) {
mRequestRender = true;
sGLThreadManager.notifyAll();
}
}
public void surfaceCreated() {
synchronized (sGLThreadManager) {
if (LOG_THREADS) {
DebugLog.i("GLThread", "surfaceCreated tid=" + getId());
}
mHasSurface = true;
sGLThreadManager.notifyAll();
}
}
public void surfaceDestroyed() {
synchronized (sGLThreadManager) {
if (LOG_THREADS) {
DebugLog.i("GLThread", "surfaceDestroyed tid=" + getId());
}
mHasSurface = false;
sGLThreadManager.notifyAll();
while ((!mWaitingForSurface) && (!mExited)) {
try {
sGLThreadManager.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public void onPause() {
synchronized (sGLThreadManager) {
mPaused = true;
sGLThreadManager.notifyAll();
}
}
public void onResume() {
synchronized (sGLThreadManager) {
mPaused = false;
mRequestRender = true;
sGLThreadManager.notifyAll();
}
}
public void onWindowResize(int w, int h) {
synchronized (sGLThreadManager) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
mRequestRender = true;
mRenderComplete = false;
sGLThreadManager.notifyAll();
// Wait for thread to react to resize and render a frame
while (!mExited && !mPaused && !mRenderComplete) {
if (LOG_SURFACE) {
DebugLog.i("Main thread",
"onWindowResize waiting for render complete.");
}
try {
sGLThreadManager.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
public void loadTextures(TextureLibrary library) {
synchronized (this) {
assert mGL != null;
if (mGL != null && mHasSurface) {
mRenderer.loadTextures(mGL, library);
}
}
}
public void flushTextures(TextureLibrary library) {
synchronized (this) {
assert mGL != null;
if (mGL != null) {
mRenderer.flushTextures(mGL, library);
}
}
}
// TODO:check lai ham nay
public void flushAll() {
synchronized (this) {
assert mGL != null;
if (mGL != null) {
mGL.glFlush();
}
}
}
// On some Qualcomm devices (such as the HTC Magic running Android 1.6),
// there's a bug in the graphics driver that will cause glViewport() to
// do the wrong thing in a very specific situation. When the screen is
// rotated, if a surface is created in one layout (say, portrait view)
// and then rotated to another, subsequent calls to glViewport are
// clipped.
// So, if the window is, say, 320x480 when the surface is created, and
// then the rotation occurs and glViewport() is called with the new
// size of 480x320, devices with the buggy driver will clip the viewport
// to the old width (which means 320x320...ugh!). This is fixed in
// Android 2.1 Qualcomm devices (like Nexus One) and doesn't affect
// non-Qualcomm devices (like the Motorola DROID).
//
// Unfortunately, under Android 1.6 this exact case occurs when the
// screen is put to sleep and then wakes up again. The lock screen
// comes up in portrait mode, but at the same time the window surface
// is also created in the backgrounded game. When the lock screen is
// closed
// and the game comes forward, the window is fixed to the correct size
// which causes the bug to occur.
// The solution used here is to simply never render when the window
// surface
// does not have the focus. When the lock screen (or menu) is up,
// rendering
// will stop. This resolves the driver bug (as the egl surface won't be
// created
// until after the screen size has been fixed), and is generally good
// practice
// since you don't want to be doing a lot of CPU intensive work when the
// lock
// screen is up (to preserve battery life).
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (sGLThreadManager) {
mHasFocus = hasFocus;
sGLThreadManager.notifyAll();
}
if (LOG_SURFACE) {
DebugLog.i("Main thread", "Focus "
+ (mHasFocus ? "gained" : "lost"));
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized (sGLThreadManager) {
mShouldExit = true;
sGLThreadManager.notifyAll();
while (!mExited) {
try {
sGLThreadManager.wait();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
*
* @param r
* the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
if (r == null) {
throw new IllegalArgumentException("r must not be null");
}
synchronized (sGLThreadManager) {
mEventQueue.add(r);
sGLThreadManager.notifyAll();
}
}
public void setSafeMode(boolean on) {
mSafeMode = on;
}
// Once the thread is started, all accesses to the following member
// variables are protected by the sGLThreadManager monitor
private boolean mShouldExit;
private boolean mExited;
private boolean mPaused;
private boolean mHasSurface;
private boolean mWaitingForSurface;
private boolean mHaveEglContext;
private boolean mHaveEglSurface;
private int mWidth;
private int mHeight;
private int mRenderMode;
private boolean mRequestRender;
private boolean mRenderComplete;
private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
private GL10 mGL;
private boolean mHasFocus;
private boolean mSafeMode = false;
// End of member variables protected by the sGLThreadManager monitor.
private Renderer mRenderer;
private EglHelper mEglHelper;
}
static class LogWriter extends Writer {
@Override
public void close() {
flushBuilder();
}
@Override
public void flush() {
flushBuilder();
}
@Override
public void write(char[] buf, int offset, int count) {
for (int i = 0; i < count; i++) {
char c = buf[offset + i];
if (c == '\n') {
flushBuilder();
} else {
mBuilder.append(c);
}
}
}
private void flushBuilder() {
if (mBuilder.length() > 0) {
DebugLog.v("GLSurfaceView", mBuilder.toString());
mBuilder.delete(0, mBuilder.length());
}
}
private StringBuilder mBuilder = new StringBuilder();
}
private void checkRenderThreadState() {
if (mGLThread != null) {
throw new IllegalStateException(
"setRenderer has already been called for this instance.");
}
}
private static class GLThreadManager {
public synchronized void threadExiting(GLThread thread) {
if (LOG_THREADS) {
DebugLog.i("GLThread", "exiting tid=" + thread.getId());
}
thread.mExited = true;
if (mEglOwner == thread) {
mEglOwner = null;
}
notifyAll();
}
/*
* Tries once to acquire the right to use an EGL surface. Does not
* block. Requires that we are already in the sGLThreadManager monitor
* when this is called.
*
* @return true if the right to use an EGL surface was acquired.
*/
public boolean tryAcquireEglSurfaceLocked(GLThread thread) {
if (mEglOwner == thread || mEglOwner == null) {
mEglOwner = thread;
notifyAll();
return true;
}
checkGLESVersion();
if (mMultipleGLESContextsAllowed) {
return true;
}
return false;
}
/*
* Releases the EGL surface. Requires that we are already in the
* sGLThreadManager monitor when this is called.
*/
public void releaseEglSurfaceLocked(GLThread thread) {
if (mEglOwner == thread) {
mEglOwner = null;
}
notifyAll();
}
public synchronized void checkGLDriver(GL10 gl) {
if (!mGLESDriverCheckComplete) {
checkGLESVersion();
if (mGLESVersion < kGLES_20) {
String renderer = gl.glGetString(GL10.GL_RENDERER);
mMultipleGLESContextsAllowed = false;
notifyAll();
}
mGLESDriverCheckComplete = true;
}
}
private void checkGLESVersion() {
if (!mGLESVersionCheckComplete) {
mGLESVersion = ConfigurationInfo.GL_ES_VERSION_UNDEFINED;
if (mGLESVersion >= kGLES_20) {
mMultipleGLESContextsAllowed = true;
}
mGLESVersionCheckComplete = true;
}
}
private boolean mGLESVersionCheckComplete;
private int mGLESVersion;
private boolean mGLESDriverCheckComplete;
private boolean mMultipleGLESContextsAllowed;
private int mGLContextCount;
private static final int kGLES_20 = 0x20000;
private GLThread mEglOwner;
}
private static final GLThreadManager sGLThreadManager = new GLThreadManager();
private boolean mSizeChanged = true;
private GLThread mGLThread;
private EGLConfigChooser mEGLConfigChooser;
private EGLContextFactory mEGLContextFactory;
private EGLWindowSurfaceFactory mEGLWindowSurfaceFactory;
private GLWrapper mGLWrapper;
private int mDebugFlags;
private int mEGLContextClientVersion;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/GLSurfaceView.java | Java | oos | 49,515 |
package org.vn.gl;
/**
* Simple container class for textures. Serves as a mapping between Android
* resource ids and OpenGL texture names, and also as a placeholder object for
* textures that may or may not have been loaded into vram. Objects can cache
* Texture objects but should *never* cache the texture name itself, as it may
* change at any time.
*/
public class Texture extends AllocationGuard {
/** Id tren TexttureLibrary */
public int resource;
/** Id tren gl */
public int name;
public int width;
public int height;
public boolean loaded;
public iBitmapInImageCache bitmapInImageCache;
/**
* sau khi add bitmap vào GL = true sẽ xóa bitmap này;false sẽ không
*/
public boolean isRecycleBitMap;
public String name_bitmap;
public Texture() {
super();
reset();
}
public void reset() {
resource = -1;
name = -1;
width = 0;
height = 0;
loaded = false;
bitmapInImageCache = null;
isRecycleBitMap = true;
name_bitmap = null;
}
public void setIsRecyle(boolean isR) {
isRecycleBitMap = isR;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Texture.java | Java | oos | 1,105 |
package org.vn.gl;
import org.vn.gl.SingerTouchDetector.ITouchDetectorListener;
import org.vn.gl.Touch.ActionTouch;
import android.view.MotionEvent;
public class MultiTouchFilter2 {
public SingerTouchDetector[] pointFs = new SingerTouchDetector[1];
private int countPoint = 0;
private ITouchDetectorListener mTouchDetectorListener = null;
public MultiTouchFilter2() {
for (int i = 0; i < pointFs.length; i++) {
pointFs[i] = new SingerTouchDetector();
}
}
public void setTouchDetectorListener(
ITouchDetectorListener pTouchDetectorListener) {
mTouchDetectorListener = pTouchDetectorListener;
for (int i = 0; i < pointFs.length; i++) {
pointFs[i] = new SingerTouchDetector();
pointFs[i].setTouchDetectorListener(pTouchDetectorListener);
}
}
public SingerTouchDetector[] getPointFTouch() {
return pointFs;
}
synchronized public void onTouchEvent(MotionEvent event) {
int pointerCount = event.getPointerCount();
if (pointerCount > countPoint)
countPoint = pointerCount > pointFs.length ? pointFs.length - 1
: pointerCount;
ContextParameters params = BaseObject.sSystemRegistry.contextParameters;
float xInGame = event.getX() * (1.0f / params.viewScaleX);
float yInGame = params.gameHeight
- (event.getY() * (1.0f / params.viewScaleY));
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_MOVE:
touchMove(pointerCount, xInGame, yInGame, event.getActionIndex());
break;
case MotionEvent.ACTION_DOWN:
touchDown(pointerCount, xInGame, yInGame, 0);
break;
case MotionEvent.ACTION_UP:
touchUp(pointerCount, xInGame, yInGame, 0);
break;
case MotionEvent.ACTION_POINTER_1_DOWN:
touchDown(pointerCount, xInGame, yInGame, 0);
break;
case MotionEvent.ACTION_POINTER_1_UP:
touchUp(pointerCount, xInGame, yInGame, 0);
break;
case MotionEvent.ACTION_POINTER_2_DOWN:// 261
touchDown(pointerCount, xInGame, yInGame, 1);
break;
case MotionEvent.ACTION_POINTER_2_UP:// 262
touchUp(pointerCount, xInGame, yInGame, 1);
break;
case MotionEvent.ACTION_POINTER_3_DOWN:// 517
touchDown(pointerCount, xInGame, yInGame, 2);
break;
case MotionEvent.ACTION_POINTER_3_UP:// 518
touchUp(pointerCount, xInGame, yInGame, 2);
break;
default:
int actionMash = action % 256;
switch (actionMash) {
case 5:// touch down
{
int indext = action / 256;
if (indext < pointFs.length) {
touchDown(pointerCount, xInGame, yInGame, indext);
}
break;
}
case 6:// touch up
{
int indext = action / 256;
if (indext < pointFs.length) {
touchUp(pointerCount, xInGame, yInGame, indext);
}
break;
}
default:
break;
}
break;
}
}
/**
*
* @param pointerCount
* @param event
* @param indextDown
* là vị trí point touch trong mảng
*/
private void touchDown(int pointerCount, float x, float y, int indextDown) {
// DebugLog.d("DUC", "touchDown//pointerCount = " + pointerCount
// + "//indextDown =" + indextDown);
if (pointerCount == 1 && indextDown == 0) {
if (mTouchDetectorListener != null)
mTouchDetectorListener.touchDown(x, y, indextDown);
if (indextDown < pointFs.length)
pointFs[indextDown].touch(ActionTouch.DOWN, x, y, indextDown);
}
}
/**
*
* @param pointerCount
* @param event
* @param indextUp
* là vị trí point touch trong mảng, nhưng chỉ tính những pointf
* enable
*/
private void touchUp(int pointerCount, float x, float y, int indextUp) {
// DebugLog.d("DUC", "touchUp//pointerCount = " + pointerCount
// + "//indextUp =" + indextUp);
if (indextUp == 0 && pointFs[indextUp].getCurrentTouch().touchDown) {
pointFs[indextUp].touch(ActionTouch.UP, x, y, indextUp);
if (mTouchDetectorListener != null)
mTouchDetectorListener.touchUp(x, y, indextUp);
}
}
/**
*
* @param pointerCount
* @param event
*/
private void touchMove(int pointerCount, float x, float y, int indextMove) {
// DebugLog.d("DUC", "touchMove//pointerCount = " + pointerCount);
if (indextMove == 0 && pointFs[indextMove].getCurrentTouch().touchDown) {
if (mTouchDetectorListener != null)
mTouchDetectorListener.touchMove(x, y, indextMove);
pointFs[indextMove].touch(ActionTouch.MOVE, x, y, indextMove);
}
}
synchronized public Touch findPointerInRegion(float regionX, float regionY,
float regionWidth, float regionHeight) {
float regionX2 = regionX + regionWidth;
float regionY2 = regionY + regionHeight;
for (int i = 0; i < countPoint; i++) {
Touch touch = pointFs[i].getCurrentTouch();
if (touch != null
&& touch.touchDown
&& checkIn(touch.x, touch.y, regionX, regionY, regionX2,
regionY2)) {
return touch;
}
}
return null;
}
private static boolean checkIn(float x, float y, float regionX,
float regionY, float regionX2, float regionY2) {
if (x < regionX || y < regionY || x > regionX2 || y > regionY2)
return false;
return true;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/MultiTouchFilter2.java | Java | oos | 5,179 |
package org.vn.gl;
/**
* TObjectPool is a generic version of ObjectPool that automatically casts to
* type T on allocation.
*
* @param <T>
* The type of object managed by the pool.
*/
public abstract class TObjectPool<T> extends ObjectPool {
public TObjectPool() {
super();
}
public TObjectPool(int size) {
super(size);
}
public T allocate() {
T object = (T) super.allocate();
return object;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/TObjectPool.java | Java | oos | 456 |
package org.vn.gl;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* An object wrapper for a pointer to the OpenGL context. Note that the context
* is only valid in certain threads at certain times (namely, in the Rendering
* thread during draw time), and at other times getGL() will return null.
*/
public class OpenGLSystem extends BaseObject {
private static GL10 sGL;
private static int sLastBoundTexture;
private static int sLastSetCropSignature;
public OpenGLSystem() {
super();
sGL = null;
}
public OpenGLSystem(GL10 gl) {
sGL = gl;
}
public static final void setGL(GL10 gl) {
sGL = gl;
sLastBoundTexture = 0;
sLastSetCropSignature = 0;
}
public static final GL10 getGL() {
return sGL;
}
public static final void bindTexture(int target, int texture) {
if (sLastBoundTexture != texture) {
sGL.glBindTexture(target, texture);
sLastBoundTexture = texture;
sLastSetCropSignature = 0;
}
}
public static final void setTextureCrop(int[] crop) {
int cropSignature = 0;
cropSignature = (crop[0] + crop[1]) << 16;
cropSignature |= crop[2] + crop[3];
if (cropSignature != sLastSetCropSignature) {
((GL11) sGL).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, crop, 0);
sLastSetCropSignature = cropSignature;
}
}
@Override
public void reset() {
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/OpenGLSystem.java | Java | oos | 1,519 |
package org.vn.gl;
public class Touch {
public float x, y;
public ActionTouch actionTouch;
public long timeCurrent;
public boolean touchDown = false;
public int indext;
public enum ActionTouch {
DOWN, MOVE, UP
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Touch.java | Java | oos | 236 |
package org.vn.gl;
public class InputTouchScreen extends BaseObject {
// public InputXY findPointerInRegion(float regionX, float regionY,
// float regionWidth, float regionHeight) {
// InputXY[] arrayInput = sSystemRegistry.multiTouchFilter
// .getPointFTouch();
// float regionX2 = regionX + regionWidth;
// float regionY2 = regionY + regionHeight;
// for (int i = 0; i < arrayInput.length; i++) {
// InputXY inputXYTamp = arrayInput[i];
// if (!inputXYTamp.isDisable()
// && checkIn(inputXYTamp.x, inputXYTamp.y, regionX, regionY,
// regionX2, regionY2)) {
// return inputXYTamp;
// }
// }
// return null;
// }
private static boolean checkIn(float x, float y, float regionX,
float regionY, float regionX2, float regionY2) {
if (x < regionX || y < regionY || x > regionX2 || y > regionY2)
return false;
return true;
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/InputTouchScreen.java | Java | oos | 974 |
package org.vn.gl;
/**
* class dung de xac dinh thu tu ve truoc(sau)<br>
*
* @author duchq
*
*/
public final class Priority {
// public static final int BackGroundDark1 = -1;
public static final int BackGroundDark2 = 0;
public static final int BackGroundAtackSight = 1;
public static final int CiclerCharacterMove = 2;
public static final int BackGround = 4;
public static final int Map = 5;
public static final int ItemAffterMap = 6;
public static final int CiclerCharacterAttack = 7;
public static final int BtClick = 8;
public static final int tile_setected = 9;
public static final int CharacterCicler = 10;
public static final int Character = 11;
public static final int CharacterKing = 12;
public static final int CharacterTakeDamage = 13;
public static final int tile_atack = 14;
public static final int Effect1 = 15;
public static final int Effect2 = 16;
public static final int Hind = 17;
public static final int Chat = 18;
public static final int DialogAddEnemy = 19;
public static final int ButtonOnDialogAddEnemy = 20;
public static final int InfoCharacter = 21;
public static final int InfoCharacter2 = 22;
public static final int Time = 23;
public static final int Help = 24;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/Priority.java | Java | oos | 1,260 |
package org.vn.gl;
/**
* The core object from which most other objects are derived. Anything that will
* be managed by an ObjectManager, and anything that requires an update per
* frame should be derived from BaseObject. BaseObject also defines the
* interface for the object-wide system registry.
*/
public abstract class BaseObject extends AllocationGuard {
public static ObjectRegistry sSystemRegistry = null;
public BaseObject() {
super();
}
/**
* Update this object.
*
* @param timeDelta
* The duration since the last update (in seconds).
* @param parent
* The parent of this object (may be NULL).
*/
public void update(float timeDelta, BaseObject parent) {
// Base class does nothing.
}
public void reset() {
}
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/BaseObject.java | Java | oos | 809 |
package org.vn.gl;
/**
* Maintains a canonical time step, in seconds, for the entire game engine. This
* time step represents real changes in time but is only updated once per frame.
*/
// TODO: time distortion effects could go here, or they could go into a special
// object manager.
public class TimeSystem extends BaseObject {
private float mGameTime;
private float mRealTime;
private float mFreezeDelay;
private float mGameFrameDelta;
private float mRealFrameDelta;
private float mTargetScale;
private float mScaleDuration;
private float mScaleStartTime;
private boolean mEaseScale;
private static final float EASE_DURATION = 0.5f;
public TimeSystem() {
super();
reset();
}
@Override
public void reset() {
mGameTime = 0.0f;
mRealTime = 0.0f;
mFreezeDelay = 0.0f;
mGameFrameDelta = 0.0f;
mRealFrameDelta = 0.0f;
mTargetScale = 1.0f;
mScaleDuration = 0.0f;
mScaleStartTime = 0.0f;
mEaseScale = false;
}
@Override
public void update(float timeDelta, BaseObject parent) {
mRealTime += timeDelta;
mRealFrameDelta = timeDelta;
if (mFreezeDelay > 0.0f) {
mFreezeDelay -= timeDelta;
mGameFrameDelta = 0.0f;
} else {
float scale = 1.0f;
if (mScaleStartTime > 0.0f) {
final float scaleTime = mRealTime - mScaleStartTime;
if (scaleTime > mScaleDuration) {
mScaleStartTime = 0;
} else {
if (mEaseScale) {
if (scaleTime <= EASE_DURATION) {
// ease in
scale = Lerp.ease(1.0f, mTargetScale,
EASE_DURATION, scaleTime);
} else if (mScaleDuration - scaleTime < EASE_DURATION) {
// ease out
final float easeOutTime = EASE_DURATION
- (mScaleDuration - scaleTime);
scale = Lerp.ease(mTargetScale, 1.0f,
EASE_DURATION, easeOutTime);
} else {
scale = mTargetScale;
}
} else {
scale = mTargetScale;
}
}
}
mGameTime += (timeDelta * scale);
mGameFrameDelta = (timeDelta * scale);
}
}
public float getGameTime() {
return mGameTime;
}
public float getRealTime() {
return mRealTime;
}
public float getFrameDelta() {
return mGameFrameDelta;
}
public float getRealTimeFrameDelta() {
return mRealFrameDelta;
}
public void freeze(float seconds) {
mFreezeDelay = seconds;
}
public void appyScale(float scaleFactor, float duration, boolean ease) {
mTargetScale = scaleFactor;
mScaleDuration = duration;
mEaseScale = ease;
if (mScaleStartTime <= 0.0f) {
mScaleStartTime = mRealTime;
}
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/TimeSystem.java | Java | oos | 2,630 |
package org.vn.gl;
import android.graphics.Bitmap;
public abstract class BitmapInImageCache {
public abstract Bitmap getBitMapResourcesItem();
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/BitmapInImageCache.java | Java | oos | 155 |
package org.vn.gl;
import org.vn.herowar.CoreActiity;
/**
* Contains global (but typically constant) parameters about the current
* operating context
*/
public class ContextParameters extends BaseObject {
public int viewWidth;
public int viewHeight;
public CoreActiity context;
public int gameWidth;
public int gameHeight;
public float viewScaleX;
public float viewScaleY;
//
public float gameWidthAfter;
public float gameHeightAfter;
public float viewScaleXAfter;
public float viewScaleYAfter;
//
public boolean supportsDrawTexture;
public boolean supportsVBOs;
//
public ContextParameters() {
super();
}
@Override
public void reset() {
}
public void setScale(float value) {
gameWidthAfter = gameWidth / value;
gameHeightAfter = gameHeight / value;
viewScaleXAfter = viewWidth / gameWidthAfter;
viewScaleYAfter = viewHeight / gameHeightAfter;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/ContextParameters.java | Java | oos | 932 |
package org.vn.gl;
/** A collection of miscellaneous utility functions. */
public class GLUtils {
private static final float EPSILON = 0.0001f;
public final static boolean close(float a, float b) {
return close(a, b, EPSILON);
}
public final static boolean close(float a, float b, float epsilon) {
return Math.abs(a - b) < epsilon;
}
public final static int sign(float a) {
if (a >= 0.0f) {
return 1;
} else {
return -1;
}
}
public final static int clamp(int value, int min, int max) {
int result = value;
if (min == max) {
if (value != min) {
result = min;
}
} else if (min < max) {
if (value < min) {
result = min;
} else if (value > max) {
result = max;
}
} else {
result = clamp(value, max, min);
}
return result;
}
public final static int byteArrayToInt(byte[] b) {
if (b.length != 4) {
return 0;
}
// Same as DataInputStream's 'readInt' method
/*
* int i = (((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16) | ((b[2] &
* 0xff) << 8) | (b[3] & 0xff));
*/
// little endian
int i = (((b[3] & 0xff) << 24) | ((b[2] & 0xff) << 16)
| ((b[1] & 0xff) << 8) | (b[0] & 0xff));
return i;
}
public final static float byteArrayToFloat(byte[] b) {
// intBitsToFloat() converts bits as follows:
/*
* int s = ((i >> 31) == 0) ? 1 : -1; int e = ((i >> 23) & 0xff); int m
* = (e == 0) ? (i & 0x7fffff) << 1 : (i & 0x7fffff) | 0x800000;
*/
return Float.intBitsToFloat(byteArrayToInt(b));
}
public final static float framesToTime(int framesPerSecond, int frameCount) {
return (1.0f / framesPerSecond) * frameCount;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/GLUtils.java | Java | oos | 1,716 |
package org.vn.gl;
public class InputXY {
public static final int DISABLE = -9999;
public InputXY() {
x = DISABLE;
y = 0;
}
public float x, y;
public float getX() {
return x;
}
public float getY() {
return y;
}
public boolean isDisable() {
return x == DISABLE;
}
public void disable() {
x = DISABLE;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/InputXY.java | Java | oos | 363 |
package org.vn.gl;
import org.vn.gl.Touch.ActionTouch;
import android.os.SystemClock;
public class SingerTouchDetector extends BaseObject {
public SingerTouchDetector() {
for (int i = 0; i < listTouchs.length; i++) {
listTouchs[i] = new Touch();
}
for (int i = 0; i < mArrayListTouchDown.length; i++) {
mArrayListTouchDown[i] = new Touch();
}
}
private Touch[] listTouchs = new Touch[2];
private int touchCurrent = 0;
private int touchLast = -1;
private final float DISTANCE_CLICK = 50;// <click | > fling
private final long TIME_CLICK = 500;// long <click
private final long TIME_FLING = 1500;// long <fling | > nothing
private ITouchDetectorListener mTouchDetectorListener = null;
private Touch[] mArrayListTouchDown = new Touch[3];
private int indextArrayListTouchDown = 0;
private int countArrayListTouchDown = 0;
private Touch mCurrentTouch = new Touch();
public void touch(ActionTouch pActionTouch, final float x, final float y,
int indextTouch) {
boolean touchDown = (pActionTouch == ActionTouch.UP ? false : true);
mCurrentTouch.actionTouch = pActionTouch;
mCurrentTouch.timeCurrent = SystemClock.elapsedRealtime();
mCurrentTouch.touchDown = touchDown;
mCurrentTouch.x = x;
mCurrentTouch.y = y;
if (touchDown) {
countArrayListTouchDown++;
if (countArrayListTouchDown > mArrayListTouchDown.length)
countArrayListTouchDown = mArrayListTouchDown.length;
indextArrayListTouchDown++;
if (indextArrayListTouchDown >= mArrayListTouchDown.length)
indextArrayListTouchDown = 0;
mArrayListTouchDown[indextArrayListTouchDown].x = x;
mArrayListTouchDown[indextArrayListTouchDown].y = y;
mArrayListTouchDown[indextArrayListTouchDown].timeCurrent = mCurrentTouch.timeCurrent;
if (pActionTouch == ActionTouch.MOVE
&& mTouchDetectorListener != null) {
int indextLastTouchDown = indextArrayListTouchDown - 1;
if (indextLastTouchDown < 0)
indextLastTouchDown = mArrayListTouchDown.length - 1;
mTouchDetectorListener.onScroll(x
- mArrayListTouchDown[indextLastTouchDown].x, y
- mArrayListTouchDown[indextLastTouchDown].y,
indextTouch);
}
}
if (listTouchs[touchCurrent].touchDown != touchDown) {
touchLast = touchCurrent;
touchCurrent = (touchCurrent == 0 ? 1 : 0);
listTouchs[touchCurrent].touchDown = touchDown;
listTouchs[touchCurrent].x = x;
listTouchs[touchCurrent].y = y;
listTouchs[touchCurrent].timeCurrent = mCurrentTouch.timeCurrent;
if (!listTouchs[touchCurrent].touchDown
&& listTouchs[touchLast].touchDown) {
long deltaTime = listTouchs[touchCurrent].timeCurrent
- listTouchs[touchLast].timeCurrent;
float Vx = listTouchs[touchCurrent].x - listTouchs[touchLast].x;
float Vy = listTouchs[touchCurrent].y - listTouchs[touchLast].y;
float distan = Vx * Vx + Vy * Vy;
// DebugLog.d("DUC", "deltaTime:" + deltaTime + "//distan:"
// + distan);
if (distan < DISTANCE_CLICK) {
if (deltaTime < TIME_CLICK) {
if (mTouchDetectorListener != null)
mTouchDetectorListener.onClick(
listTouchs[touchCurrent].x,
listTouchs[touchCurrent].y, indextTouch);
}
} else {
if (mTouchDetectorListener != null
&& countArrayListTouchDown == mArrayListTouchDown.length) {
int lastTouch = indextArrayListTouchDown - 1;
if (lastTouch == -1)
lastTouch = mArrayListTouchDown.length - 1;
Vx = listTouchs[touchCurrent].x
- mArrayListTouchDown[lastTouch].x;
Vy = listTouchs[touchCurrent].y
- mArrayListTouchDown[lastTouch].y;
deltaTime = listTouchs[touchCurrent].timeCurrent
- mArrayListTouchDown[lastTouch].timeCurrent;
mTouchDetectorListener.onFling(Vx, Vy, deltaTime,
indextTouch);
}
}
indextArrayListTouchDown = 0;
countArrayListTouchDown = 0;
}
}
}
public Touch getCurrentTouch() {
return mCurrentTouch;
}
public void setTouchDetectorListener(
ITouchDetectorListener pTouchDetectorListener) {
mTouchDetectorListener = pTouchDetectorListener;
}
public interface ITouchDetectorListener {
// ===========================================================
// Methods
// ===========================================================
public void touchDown(float x, float y, int indext);
public void touchMove(float x, float y, int indext);
public void onScroll(float xOffset, float yOffset, int indext);
public void touchUp(float x, float y, int indext);
public void onClick(float x, float y, int indext);
public void onFling(float Vx, float Vy, float deltaTime, int indext);
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/SingerTouchDetector.java | Java | oos | 4,840 |
package org.vn.gl;
/**
* A basic object that adds an execution phase. When PhasedObjects are combined
* with PhasedObjectManagers, objects within the manager will be updated by
* phase.
*/
public class PhasedObject extends BaseObject {
public int phase; // This is public because the phased is accessed extremely
// often, so much
// so that the function overhead of an getter is
// non-trivial.
public PhasedObject() {
super();
}
@Override
public void reset() {
}
public void setPhase(int phaseValue) {
phase = phaseValue;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/gl/PhasedObject.java | Java | oos | 595 |
package org.vn.model;
public class NextTurnMessage {
public int idPlayerInTurnNext;
public long totaltime;
public long turntime;
public long rivalTotaltime;
public long rivalTurnTime;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/NextTurnMessage.java | Java | oos | 201 |
package org.vn.model;
public class AttackMessage {
public int idAttacker;
public int idBeAttacker;
public int hpIdAttack;
public int hpIdBeAttack;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/AttackMessage.java | Java | oos | 162 |
package org.vn.model;
public class MoveMessage {
public int idMove;
public int xTypeMoveNext;
public int yTypeMoveNext;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/MoveMessage.java | Java | oos | 133 |
package org.vn.model;
public class Board {
public int id;
public byte maxPlayer;
public byte nPlayer;
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Board.java | Java | oos | 113 |
package org.vn.model;
public class Result {
public int winnerID;
public String winnerName;
public long winnerMoney;
public int winnerLevel;
public int loserID;
public String loserName;
public long loserMoney;
public int loserLevel;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Result.java | Java | oos | 255 |
package org.vn.model;
public class TouchTouch {
public float xNoCamera;
public float yNoCamera;
public float xHasCameRa;
public float yHasCamera;
/** cai nay do uu tien lon nhat */
public boolean isTouch;
public boolean isTouchUp;
public boolean chuaXuLyTouchDownTrongVongLap;
public boolean isWaitProccessClick;
public boolean isClick;
public TouchTouchType mAction = TouchTouchType.chua_lam_gi;
public enum TouchTouchType {
chua_lam_gi, da_touch_down, touch_up;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/TouchTouch.java | Java | oos | 508 |
package org.vn.model;
import org.vn.unit.Tile;
public class Move {
public enum TypeMove {
left, right, left_top, left_bot, right_top, right_bot
}
public Tile tileNext;
public TypeMove typeMove;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Move.java | Java | oos | 219 |
package org.vn.model;
public class MapType {
public byte[][] mapType;
public int row;
public int column;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/MapType.java | Java | oos | 118 |
package org.vn.model;
public class EnemyType {
/**
* 0:Cung thu; 1:Bo Binh; 2:Ky binh
*/
public int armyType;
public String armyName;
public int cost;
public int hp;
public int damageMax;
public int damageMin;
public int mana;
public int movecost;
public int attackcost;
public int rangeattack;
public int rangeview;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/EnemyType.java | Java | oos | 356 |
package org.vn.model;
public class Money {
public int playerID;
public int money;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Money.java | Java | oos | 93 |
package org.vn.model;
import org.vn.cache.CurrentGameInfo;
public class Enemy {
public int armyId;
public int armyType;
public int playerId;
public int xTile = -1;
public int yTile = -1;
public EnemyType mEnemyType = null;
public EnemyType getEnemyType() {
if (mEnemyType != null) {
return mEnemyType;
}
for (EnemyType enemyType : CurrentGameInfo.getIntance().listEnemytype) {
if (armyType == enemyType.armyType) {
mEnemyType = enemyType;
return mEnemyType;
}
}
return null;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Enemy.java | Java | oos | 542 |
package org.vn.model;
/**
* Save the data of a player
*
* @author Quách Toàn Chính
*
*/
public class PlayerModel {
public int ID;
public String name;
public long money;
public int lv;
public boolean isReady = false;
} | zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/PlayerModel.java | Java | oos | 247 |
package org.vn.model;
public class Server {
public String name;
public String ip;
public int port;
public Server(String ip, int port, String name) {
this.ip = ip;
this.port = port;
this.name = name;
}
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Server.java | Java | oos | 217 |
package org.vn.model;
public class BuyEnemy {
public int buyerId;
public int money;
public int armytype;
public int armyid;
public int x_tile;
public int y_tile;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/BuyEnemy.java | Java | oos | 181 |
package org.vn.model;
public class Achievement {
public int playerID;
public String playerName;
public int winnumber;
public int losenumber;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Achievement.java | Java | oos | 156 |
package org.vn.model;
public class Map {
public byte mapId;
public String mapName = "";
public MapType mapType = null;
}
| zzzzzzzzzzz | trunk/hero_war/src/org/vn/model/Map.java | Java | oos | 132 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.loginAPI;
/**
*
* @author truongps
*/
public class LoginAPI {
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/loginAPI/LoginAPI.java | Java | oos | 199 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.registerAPI;
import vn.thedreamstudio.core.common.Player;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import vn.thedreamstudio.util.FileManager;
/**
*
* @author truongps
*/
public class RegisterManager {
// public static final int USER_EXIST = 0;
// public static final int USER_DONT_EXIST = 1;
// public static final int USER_REGISTER_OK = 2;
// public static final int USER_REGISTER_FAIL = 3;
private static int currentID;
public static final String dir = FileManager.getcurrentDirectory() + "USER" + FileManager.SEPARATOR;
public static final String[] registerParttern = new String[]{
"userid=",
"username=",
"password=",
"phonenumber"
};
static {
System.out.println("Current user info save in: " + dir);
FileManager.makeDir(dir);
currentID = new File(dir).list().length;
System.out.println("Current user: " + currentID);
}
/**
* Kiem tra xem ten nay co duoc phep them vao database.
* @param username
* @return
*/
public static boolean checkUsername(String username) {
return FileManager.checkFileExist(dir + username);
}
/**
* Them 1 user vào database.
* @param p
* @return
*/
public static boolean addUser(Player p) {
try {
if (!checkUsername(p.userName)) {
currentID = new File(dir).list().length;
System.out.println("Current user: " + currentID);
p.playerID = currentID;
FileManager.saveUserInfo(p, dir + p.userName);
return true;
}
} catch (IOException ex) {
Logger.getLogger(RegisterManager.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public static Player getPlayer(String userName) {
if (!checkUsername(userName)) {
return null;
}
Player p = null;
try {
p = FileManager.getPlayerFromFile(dir + userName);
} catch (IOException ex) {
Logger.getLogger(RegisterManager.class.getName()).log(Level.SEVERE, null, ex);
}
return p;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/registerAPI/RegisterManager.java | Java | oos | 2,386 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.map;
/**
*
* @author truongps
*/
public class Position {
/**
*
*/
public int xPos;
/**
*
*/
public int yPos;
public Position(int xPos, int yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/map/Position.java | Java | oos | 386 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.map;
import vn.thedreamstudio.game.army.Soldier;
/**
* 1 cell tren ban do.
* @author truongps
*/
public class Cell {
/**
* Không cho bất kì ai đặt chân lên ô này.
*/
public static final byte ALLOW_NONE = 0;
/**
* Chi cho phep linh bo di wa o dat nay. Linh bo bao gom: Ki binh, Bo binh và Lính cung.
*/
public static final byte ALLOW_INFANTRY = 1;
/**
* Cho phép các phuong tiện nhu xe ban da, ... (Cai nay de nang cap sau nay neu co).
*/
public static final byte ALLOW_VEHICLES = 2;
/**
* Cho phep ca xe va linh deu di qua duoc cell nay.
*/
public static final byte ALLOW_VEHICLES_INFANTRY = 3;
/**
* Cell này dành cho tướng. Mất ô này thì user thua.
*/
public static final byte ALLOW_GENERAL = 4;
public byte allow = ALLOW_NONE;
/**
* Vi tri x, y cua cell.
*/
public int x;
public int y;
/**
* Quan doi dang dong tren cell nay.
*/
public Soldier army = null;
public Cell(int x, int y, byte allow) {
this.x = x;
this.y = y;
this.allow = allow;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/map/Cell.java | Java | oos | 1,283 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.map;
/**
* Map chua nhieu cell.
* @author truongps
*/
public class Map {
private Cell[][] map;
private byte[][] mapAllows;
public int rowNum;
public int colNum;
public Position ownerGeneral;
public Position visitGeneral;
public int mapID;
/**
* Khoang cách từ general de dat duoc linh.
*/
public int initRange = 6;
public Map(final int mapID, final int rowNum, final int colNum, byte[][] mapData) {
this.mapID = mapID;
this.rowNum = rowNum;
this.colNum = colNum;
map = new Cell[rowNum][colNum];
mapAllows = mapData;
for (int i = 0; i < rowNum; i++) {
for (int j = 0; j < colNum; j++) {
map[i][j] = new Cell(i, j, mapAllows[i][j]);
if (map[i][j].allow == Cell.ALLOW_GENERAL) {
if (ownerGeneral == null) {
ownerGeneral = new Position(i, j);
} else {
visitGeneral = new Position(i, j);
}
}
}
}
if (ownerGeneral == null) {
ownerGeneral = new Position(0, 0);
}
if (visitGeneral == null) {
visitGeneral = new Position(0, 0);
}
}
public byte[][] getMapLayout() {
return mapAllows;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/map/Map.java | Java | oos | 1,482 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.map;
import vn.thedreamstudio.constance.CProtocol;
import core.network.Message;
/**
*
* @author truongps
*/
public class MapFactory {
public final static int MAP_ROW = 50;
public final static int MAP_COL = 50;
public static final byte[] MAP_IDs = new byte[]{0};
public static final String[] MAP_NAMEs = new String[]{"Hoang mạc"};
public static final byte[][] MAP_ONE;
static {
MAP_ONE = new byte[24][24];
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 24; j++) {
if (i == 20 && j == 3) {
MAP_ONE[i][j] = Cell.ALLOW_GENERAL;
} else if (i == 4 && j == 20) {
MAP_ONE[i][j] = Cell.ALLOW_GENERAL;
} else {
MAP_ONE[i][j] = Cell.ALLOW_VEHICLES_INFANTRY;
}
}
}
}
public synchronized static Map getMapFromID(final int mapID) {
switch (mapID) {
case 0:
return new Map(0, 24, 24, MAP_ONE);
}
return null;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/map/MapFactory.java | Java | oos | 1,203 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Linh mexico.
* @author truongps
*/
public class Mexico extends Soldier {
public static final int COST = 10;
public Mexico() {
typeID = Soldier.TYPE_MEXICO;
name = "Lính cận vệ";
hp = 100;
mana = 54;
damageMin = 11;
damageMax = 30;
rangeView = 5;
costMove = 8;
rangeAttack = 1;
costAttack = 22;
cost = 10;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Mexico.java | Java | oos | 514 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Pháo binh.
* @author truongps
*/
public class Artillery extends Soldier {
public static final int COST = 12;
public Artillery() {
typeID = Soldier.TYPE_ARTILLERY;
name = "Pháo binh";
hp = 40;
mana = 72;
damageMin = 41;
damageMax = 58;
rangeView = 7;
costMove = 15;
rangeAttack = 7;
costAttack = 38;
cost = 12;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Artillery.java | Java | oos | 517 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
*
* @author truongps
*/
public class General extends Soldier {
public General() {
typeID = TYPE_GENERAL;
hp = 100;
rangeView = 6;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/General.java | Java | oos | 312 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Ki binh
* @author truongps
*/
public class Cavalry extends Soldier {
// public static final int COST = 30;
// public Cavalry() {
// typeID = Soldier.TYPE_CAVARLY;
// name = "Kị binh";
// cost = 30;
// hp = 60;
// damageMax = 20;
// damageMin = 12;
// mana = 54;
// costMove = 6;
// costAttack = 24;
// rangeAttack = 4;
// rangeView = 5;
// }
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Cavalry.java | Java | oos | 584 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Tho dan.
* @author truongps
*/
public class Indian extends Soldier {
public static final int COST = 10;
public Indian() {
typeID = Soldier.TYPE_INDIAN;
name = "Cung thủ";
hp = 60;
mana = 54;
damageMin = 18;
damageMax = 26;
rangeView = 5;
costMove = 8;
rangeAttack = 4;
costAttack = 32;
cost = 10;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Indian.java | Java | oos | 503 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
import vn.thedreamstudio.core.common.Player;
/**
*
* @author truongps
*/
public class Soldier {
/**
* Linh cung.
*/
// public static final int TYPE_ARCHER = 0;
// /**
// * Linh bo.
// */
// public static final int TYPE_INFANTRY = 1;
// /**
// * Ki binh.
// */
// public static final int TYPE_CAVARLY = 2;
/**
* Pháo binh.
*/
public static final int TYPE_ARTILLERY = 0;
/**
* Lính già.
*/
public static final int TYPE_GEEZER = 1;
/**
* Linh cao boi.
*/
public static final int TYPE_COWBOY = 2;
/**
* Tho dan.
*/
public static final int TYPE_INDIAN = 3;
/**
* Lính người mexico.
*/
public static final int TYPE_MEXICO = 4;
/**
* Lính bắn tỉa, bắn súng ngắm.
*/
public static final int TYPE_SCOUT = 5;
/**
* Con tuong.
*/
public static final int TYPE_GENERAL = -1;
/**
* Player là chủ cua doi quan nay.
*/
public Player owner;
/**
* Vi tri cua doi quan dung.
*/
public int x;
public int y;
/**
* Id cua doi quan tren ban.
*/
public int id;
/**Id cua binh chủng.*/
public int typeID;
public String name = "";
public int cost;
public int hp;
public int damageMax;
public int damageMin;
public int mana;
public int costMove;
public int costAttack;
public int rangeAttack;
public int rangeView;
public int getID() {
return typeID;
}
public String getName() {
return name;
}
public int getCost() {
return cost;
}
public int getHP() {
return hp;
}
public int getDamageMax() {
return damageMax;
}
public int getDamageMin() {
return damageMin;
}
public int getMana() {
return mana;
}
public int getCostMove() {
return costMove;
}
public int getCostAttack() {
return costAttack;
}
public int getRangeAttack() {
return rangeAttack;
}
public int getRangeView() {
return rangeView;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Soldier.java | Java | oos | 2,329 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Lính bộ
* @author truongps
*/
public class Infantry extends Soldier {
// public static final int COST = 16;
// public Infantry() {
// typeID = Soldier.TYPE_INFANTRY;
// name = "Bộ binh";
// cost = 16;
// hp = 60;
// damageMax = 20;
// damageMin = 12;
// mana = 54;
// costMove = 6;
// costAttack = 24;
// rangeAttack = 4;
// rangeView = 5;
// }
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Infantry.java | Java | oos | 585 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Linh cao boi.
* @author truongps
*/
public class Cowboy extends Soldier {
public static final int COST = 8;
public Cowboy() {
typeID = Soldier.TYPE_COWBOY;
name = "Lính Tốc Độ";
hp = 20;
mana = 54;
damageMin = 18;
damageMax = 26;
rangeView = 2;
costMove = 5;
rangeAttack = 1;
costAttack = 24;
cost = 8;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Cowboy.java | Java | oos | 513 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Linh gia
*
* @author truongps
*/
public class Geezer extends Soldier {
public static final int COST = 12;
public Geezer() {
typeID = Soldier.TYPE_GEEZER;
name = "Lính già-DamageRandom";
hp = 50;
mana = 54;
damageMin = 1;
damageMax = 100;
rangeView = 5;
costMove = 8;
rangeAttack = 4;
costAttack = 43;
cost = 12;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Geezer.java | Java | oos | 493 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Quan li toan bo shop linh.
* @author truongps
*/
public class ArmyShop {
private static Soldier[] shopContents;
private static ArmyShop instance = new ArmyShop();
public synchronized static ArmyShop getInstance() {
return instance;
}
private ArmyShop() {
shopContents = new Soldier[] {
/*new Archer(), new Infantry(), new Cavalry()*/
new Artillery(), new Geezer(), new Cowboy(), new Indian(), new Mexico(), new Scout(), new General()
};
}
public Soldier getArtillery() {
return shopContents[0];
}
public Soldier[] getArmySupported() {
return shopContents;
}
// public Soldier getArcher() {
// return shopContents[0];
// }
//
// public Soldier getInfantry() {
// return shopContents[1];
// }
//
// public Soldier getCavalry() {
// return shopContents[2];
// }
public synchronized static int getPriceOF(final int ID) {
switch(ID) {
// case Soldier.TYPE_ARCHER:
// return Archer.COST;
// case Soldier.TYPE_CAVARLY:
// return Cavalry.COST;
// case Soldier.TYPE_INFANTRY:
// return Infantry.COST;
case Soldier.TYPE_ARTILLERY:
return Artillery.COST;
case Soldier.TYPE_COWBOY:
return Cowboy.COST;
case Soldier.TYPE_GEEZER:
return Geezer.COST;
case Soldier.TYPE_INDIAN:
return Indian.COST;
case Soldier.TYPE_MEXICO:
return Mexico.COST;
case Soldier.TYPE_SCOUT:
return Scout.COST;
}
return 0;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/ArmyShop.java | Java | oos | 1,905 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Linh ban tia.
*
* @author truongps
*/
public class Scout extends Soldier {
public static final int COST = 37;
public Scout() {
typeID = Soldier.TYPE_SCOUT;
name = "Lính tinh nhuệ";
hp = 120;
mana = 56;
damageMin = 52;
damageMax = 85;
rangeView = 8;
costMove = 8;
rangeAttack = 7;
costAttack = 26;
cost = 37;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Scout.java | Java | oos | 490 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.army;
/**
* Linh cung
* @author truongps
*/
public class Archer extends Soldier {
// public static final int COST = 10;
// public Archer() {
// typeID = Soldier.TYPE_ARCHER;
// name = "Cung thủ";
// cost = 10;
// hp = 60;
// damageMax = 20;
// damageMin = 12;
// mana = 54;
// costMove = 6;
// costAttack = 24;
// rangeAttack = 4;
// rangeView = 5;
// }
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/army/Archer.java | Java | oos | 579 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.network;
import vn.thedreamstudio.core.common.Player;
import vn.thedreamstudio.constance.CProtocol;
import vn.thedreamstudio.game.common.Board;
import vn.thedreamstudio.game.common.MGameController;
import core.network.Message;
import java.util.Vector;
import vn.thedreamstudio.game.common.MatchResult;
import vn.thedreamstudio.game.army.Soldier;
import vn.thedreamstudio.game.map.Map;
import vn.thedreamstudio.network.GlobalServices;
/**
*
* @author truongps
*/
public class GameServices {
public static void processGetBoardListMessage(Player p) {
Board[] bs = MGameController.getInstance().getBoardList();
Message m = new Message(CProtocol.GET_BOARD_LIST);
m.putInt(bs.length);
for (int i = 0; i < bs.length; i++) {
m.putInt(bs[i].boardID);
m.putByte(bs[i].maxPlayer);
m.putByte(bs[i].countPlayer());
}
p.session.write(m);
m.cleanup();
}
public static void processJoinBoardMessage(Player p, boolean isOK, int boardID) {
Message m = new Message(CProtocol.JOIN_BOARD);
m.putInt(boardID);
m.putByte((isOK ? 1 : 0));
if (isOK) {
Board b = MGameController.getInstance().getBoard(boardID);
m.putInt(b.ownerID);
int size = b.players.size();
for (int i = 0; i < size; i++) {
Player tp = ((Player) b.players.elementAt(i));
m.putInt(tp.playerID);
m.putString(tp.userName);
}
}
p.session.write(m);
m.cleanup();
if (isOK) {
sendMyInfoToBoard(boardID, p);
}
}
private static void sendMyInfoToBoard(int boardID, Player myinfo) {
Board b = MGameController.getInstance().getBoard(boardID);
int size = b.players.size();
for (int i = 0; i < size; i++) {
Player p = (Player) b.players.elementAt(i);
if (p.session != null && p.playerID != myinfo.playerID) {
Message m = new Message(CProtocol.SOMEONE_JOIN_BOARD);
m.putInt(boardID);
for (int j = 0; j < size; j++) {
Player pp = (Player) b.players.elementAt(j);
if (pp.session != null) {
m.putInt(pp.playerID);
m.putString(pp.userName);
}
}
p.session.write(m);
m.cleanup();
}
}
}
public static void processSomeOneLeaveBoardMessage(final int boardID, Player p) {
Board b = MGameController.getInstance().getBoard(boardID);
int size = b.players.size();
for (int i = 0; i < size; i++) {
Player pp = (Player) b.players.elementAt(i);
if (pp.session != null) {
Message m = new Message(CProtocol.SOMEONE_LEAVE_BOARD);
m.putInt(p.playerID);
m.putInt(b.ownerID);
pp.session.write(m);
m.cleanup();
}
}
p.boardID = -1;
}
public static void processGetArmyShopContentsMessage(Player p) {
Soldier[] temp = MGameController.getInstance().getArmyShopContents();
Message m = new Message(CProtocol.GET_ARMY_SHOP);
m.putInt(MGameController.TOTAL_MONEY);//cho nay de tam, sau nay sua lai
m.putByte(temp.length);
for (int i = 0; i < temp.length; i++) {
m.putInt(temp[i].getID());
m.putString(temp[i].getName());
m.putInt(temp[i].getCost());
m.putInt(temp[i].getHP());
m.putInt(temp[i].getDamageMax());
m.putInt(temp[i].getDamageMin());
m.putInt(temp[i].getMana());
m.putInt(temp[i].getCostMove());
m.putInt(temp[i].getCostAttack());
m.putInt(temp[i].getRangeAttack());
m.putInt(temp[i].getRangeView());
}
p.session.write(m);
m.cleanup();
}
public synchronized static void processSelectArmyMessage(Player p, int[] ids) {
Message m = new Message(CProtocol.SELECT_ARMY);
if (MGameController.getInstance().checkUserSelectArmy(ids)) {
m.putByte(1);
Board b = MGameController.getInstance().getBoard(p.boardID);
Vector v = b.setArmyOnMap(ids, p.playerID);
int size = v.size();
System.out.println("So linh da set vao map: " + size);
for (int i = 0; i < size; i++) {
Soldier s = (Soldier) v.elementAt(i);
m.putInt(s.id);
m.putInt(s.typeID);
}
} else {
m.putByte(0);
}
p.session.write(m);
m.cleanup();
}
public static void processGetMapMessage(Player p) {
Message m = new Message(CProtocol.GET_MAP);
int row = 50;
int col = 50;
m.putInt(row);
m.putInt(col);
int c = row * col;
for (int i = 0; i < c; i++) {
m.putInt(0);
}
p.session.write(m);
m.cleanup();
}
public static void processLayoutArmyMessage(Player p, int armyID, int xPos, int yPos) {
byte status = 1;//cai nay ve sau se tinh lai.
Message m = new Message(CProtocol.LAYOUT_ARMY);
m.putInt(armyID);
m.putInt(xPos);
m.putInt(yPos);
m.putByte(status);
p.session.write(m);
m.cleanup();
}
public static void processSomeOneReadyMessage(Player p, Player pReady) {
if (p == null || p.playerID == -1) {
return;
}
Message m = new Message(CProtocol.READY);
m.putInt(pReady.boardID);
m.putInt(pReady.playerID);
m.putByte(pReady.isReady ? 1 : 0);
p.session.write(m);
}
public static void processStartGame(Player p, Vector soldier) {
Message m = new Message(CProtocol.START_GAME);
int size = soldier.size();
for (int i = size; --i >= 0;) {
Soldier s = (Soldier) soldier.elementAt(i);
m.putInt(s.id);
m.putInt(s.typeID);
m.putInt(s.owner.playerID);
m.putInt(s.x);
m.putInt(s.y);
}
p.session.write(m);
}
public static void processMoveArmyMessage(Player p, Soldier s) {
Message m = new Message(CProtocol.MOVE_ARMY);
m.putInt(s.id);
m.putInt(s.x);
m.putInt(s.y);
p.session.write(m);
m.cleanup();
}
public static void sendMessageSetMap(Player p, Board b, Map map) {
if (map == null) {
GlobalServices.sendServerMessage(p, 1, "Trên server chua co map.");
return;
}
Message m = new Message(CProtocol.SET_MAP);
m.putByte(map.mapID);
m.putByte(1);
int size = b.players.size();
for (int i = size; --i >= 0;) {
m.putInt(b.players.elementAt(i).playerID);
if (b.players.elementAt(i).playerID == b.ownerID) {
m.putInt(map.ownerGeneral.xPos);
m.putInt(map.ownerGeneral.yPos);
} else {
m.putInt(map.visitGeneral.xPos);
m.putInt(map.visitGeneral.yPos);
}
m.putInt(map.initRange);
}
p.session.write(m);
m.cleanup();
}
public static void sendMatchResult(Player p, MatchResult ma) {
if (p.session == null || ma == null) {
return;
}
Message m = new Message(CProtocol.END_GAME);
m.putInt(ma.pWin.playerID);
m.putString(ma.pWin.playerName);
m.putLong(ma.pWin.money);
m.putInt(ma.pWin.level);
m.putInt(ma.pLose.playerID);
m.putString(ma.pLose.playerName);
m.putLong(ma.pLose.money);
m.putInt(ma.pLose.level);
p.session.write(m);
m.cleanup();
}
/**
* Chi can xac dinh duoc ban thì goi het cho nhung thang trong ban.
* @param b
*/
public static Message getMessageUpdateMoney(Board b) {
Message m = new Message(CProtocol.UPDATE_MONEY_INGAME);
m.putByte(0);//sub command 0.
for (int j = b.players.size(); --j >= 0;) {
m.putInt(b.players.elementAt(j).playerID);
m.putInt((int) b.players.elementAt(j).money);
}
return m;
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/network/GameServices.java | Java | oos | 8,513 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vn.thedreamstudio.game.network;
import vn.thedreamstudio.common.L;
import vn.thedreamstudio.common.PlayerManager;
import core.network.IMessageHandler;
import vn.thedreamstudio.core.common.Player;
import vn.thedreamstudio.constance.CProtocol;
import java.io.IOException;
import vn.thedreamstudio.game.common.Board;
import vn.thedreamstudio.game.common.MGameController;
import core.network.Message;
import java.security.spec.MGF1ParameterSpec;
import java.util.Vector;
import vn.thedreamstudio.game.common.AttackResult;
import vn.thedreamstudio.game.army.Soldier;
import vn.thedreamstudio.game.map.Map;
import vn.thedreamstudio.game.map.MapFactory;
import vn.thedreamstudio.network.GlobalServices;
import vn.thedreamstudio.registerAPI.RegisterManager;
import vn.thedreamstudio.util.FileManager;
/**
*
* @author truongps
*/
public class GameMessageHandler implements IMessageHandler {
@Override
public void processMessage(Player player, Message msg) throws IOException {
switch (msg.id) {
case CProtocol.GET_BOARD_LIST: {
GameServices.processGetBoardListMessage(player);
// Board b = MGameController.getInstance().getBoardSuggested();
// if (b != null) {
// GlobalServices.sendBoardSuggestion(player, b);
// }
}
break;
// case CProtocol.EXIT_BOARD:
// MGameController.getInstance().exitBoard(msg.reader().readInt(), player);
// break;
case CProtocol.CHAT_BOARD:
MGameController.getInstance().chatInBoard(player, msg.reader().readUTF());
break;
case CProtocol.LEAVE_BOARD: {
Board b = MGameController.getInstance().getBoard(player.boardID);
if (b != null) {
b.someoneExitBoard(player);
GameServices.processSomeOneLeaveBoardMessage(player.boardID, player);
}
}
// MGameController.getInstance().exitBoard(player.boardID, player);
break;
case CProtocol.GET_ARMY_SHOP:
GameServices.processGetArmyShopContentsMessage(player);
break;
case CProtocol.SELECT_ARMY://Chọn quan.
{
int length = msg.reader().readInt();
System.out.println("user name: " + player.userName + " , length: " + length);
int[] b = new int[length];
for (int i = 0; i < length; i++) {
b[i] = msg.reader().readInt();
}
GameServices.processSelectArmyMessage(player, b);
}
break;
case CProtocol.LAYOUT_ARMY: //
{
Vector mm = new Vector();
while (msg.reader().available() > 0) {
Soldier s = new Soldier();
s.id = msg.reader().readInt();
s.x = msg.reader().readInt();
s.y = msg.reader().readInt();
mm.addElement(s);
}
Board b = MGameController.getInstance().getBoard(player.boardID);
Message m = new Message(CProtocol.LAYOUT_ARMY);
if (b.layoutArmy(mm, player.playerID)) {
m.putByte(1);
}
m.putByte(0);
player.session.write(m);
m.cleanup();
// GameServices.processLayoutArmyMessage(player, msg.reader().readInt(), msg.reader().readInt(), msg.reader().readInt());
}
break;
case CProtocol.GET_ALL_MAP: {
Message m = new Message(CProtocol.GET_ALL_MAP);
m.putByte(MapFactory.MAP_IDs.length);
for (int i = 0; i < MapFactory.MAP_IDs.length; i++) {
m.putByte(MapFactory.MAP_IDs[i]);
m.putString(MapFactory.MAP_NAMEs[i]);
}
player.session.write(m);
m.cleanup();
}
break;
case CProtocol.GET_MAP: {
byte mapID = msg.reader().readByte();
Map map = MapFactory.getMapFromID(mapID);
Message m = new Message(CProtocol.GET_MAP);
m.putByte(mapID);
if (map == null || player.boardID < 0) {
m.putInt(0);
} else {
m.putInt(map.rowNum);
m.putInt(map.colNum);
for (int i = 0; i < map.rowNum; i++) {
for (int j = 0; j < map.colNum; j++) {
m.putByte(map.getMapLayout()[i][j]);
}
}
}
player.session.write(m);
m.cleanup();
}
break;
case CProtocol.JOIN_BOARD: {
int boardID = msg.reader().readInt();
Board b = MGameController.getInstance().getBoard(boardID);
if (b == null) {//Kiem tra board nay co ton tai trong he thong hay khong.
GlobalServices.sendServerMessage(player, 1, L.gl(player.languageType, 1));
return;
}
if (b.someoneJoinBoard(player)) {//join board success.
GameServices.processJoinBoardMessage(player, true, boardID);
Map map = b.getMap();
if (map != null) {
GameServices.sendMessageSetMap(player, b, map);
}
} else {
GameServices.processJoinBoardMessage(player, false, boardID);
}
}
break;
case CProtocol.SET_MAP: {
byte mapID = msg.reader().readByte();
Board b = MGameController.getInstance().getBoard(player.boardID);
if (b.ownerID != player.playerID) {//Kiem tra neu khong phai la chu ban thi se k cho set map.
GlobalServices.sendServerMessage(player, 1, L.gl(player.languageType, 0));
return;
}
Map map = b.createMap(player.playerID, mapID);
GameServices.sendMessageSetMap(player, b, map);
for (int i = 0; i < b.maxPlayer; i++) {
Player p = ((Player) b.players.elementAt(i));
if (p.playerID != -1) {
GameServices.sendMessageSetMap(p, b, map);
}
}
// Map map = MGameController.getInstance().setMapOnBoard(player, mapID);
// for (int i = 0; i < b.maxPlayer; i++) {
// Player p = ((Player) b.players.elementAt(i));
// Message m = new Message(CProtocol.SET_MAP);
// m.putByte(mapID);
// if (map != null) {
// m.putByte(1);
// m.putInt(p.playerID);
// if (p.playerID == b.ownerID) {
// m.putInt(map.ownerGeneral.xPos);
// m.putInt(map.ownerGeneral.yPos);
// } else {
// m.putInt(map.visitGeneral.xPos);
// m.putInt(map.visitGeneral.yPos);
// }
// m.putInt(map.initRange);
// } else {
// m.putByte(0);
// }
// p.session.write(m);
// m.cleanup();
// }
}
break;
case CProtocol.READY: //ready - goi ve cho tat ca moi user trong ban.
{
Board b = MGameController.getInstance().getBoard(player.boardID);
b.someoneReady(player);
}
break;
case CProtocol.START_GAME: {
Board b = MGameController.getInstance().getBoard(player.boardID);
b.startGame(player);
}
break;
case CProtocol.MOVE_ARMY: {
Soldier s = new Soldier();
s.id = msg.reader().readInt();
s.x = msg.reader().readInt();
s.y = msg.reader().readInt();
Board b = MGameController.getInstance().getBoard(player.boardID);
if (b.moveArmy(s)) {
int size = b.players.size();
for (int i = size; --i >= 0;) {
if (((Player) b.players.elementAt(i)).playerID != -1 && ((Player) b.players.elementAt(i)).session != null) {
Message m = new Message(CProtocol.MOVE_ARMY);
m.putByte(1);
m.putInt(s.id);
m.putInt(s.x);
m.putInt(s.y);
((Player) b.players.elementAt(i)).session.write(m);
m.cleanup();
}
}
} else {
s = b.getArmyFromId(s.id);
int size = b.players.size();
for (int i = size; --i >= 0;) {
if (((Player) b.players.elementAt(i)).playerID != -1 && ((Player) b.players.elementAt(i)).session != null) {
Message m = new Message(CProtocol.MOVE_ARMY);
m.putByte(0);
m.putInt(s.id);
m.putInt(s.x);
m.putInt(s.y);
((Player) b.players.elementAt(i)).session.write(m);
m.cleanup();
}
}
}
}
break;
case CProtocol.ATTACH: {
Board b = MGameController.getInstance().getBoard(player.boardID);
AttackResult a = b.attack(msg.reader().readInt(), msg.reader().readInt());
if (a == null) {
int size = b.players.size();
for (int i = size; --i >= 0;) {
if (((Player) b.players.elementAt(i)).playerID != -1 && ((Player) b.players.elementAt(i)).session != null) {
Message m = new Message(CProtocol.ATTACH);
m.putByte(0);
((Player) b.players.elementAt(i)).session.write(m);
m.cleanup();
}
}
} else {
int size = b.players.size();
for (int i = size; --i >= 0;) {
if (((Player) b.players.elementAt(i)).playerID != -1 && ((Player) b.players.elementAt(i)).session != null) {
Message m = new Message(CProtocol.ATTACH);
m.putByte(1);
m.putInt(a.myArmyID);
m.putInt(a.myArmyHP);
m.putInt(a.rivalArmyID);
m.putInt(a.rivalArmyHP);
((Player) b.players.elementAt(i)).session.write(m);
m.cleanup();
}
}
Player loser = b.isEndGame();
if (loser != null) {
b.endGame(b.players.elementAt(0).playerID == loser.playerID
? b.players.elementAt(1) : b.players.elementAt(0), loser);
}
}
}
break;
case CProtocol.NEXT_TURN: {
Board b = MGameController.getInstance().getBoard(player.boardID);
if (b.isStartGame) {
b.changeTurn(player);
}
}
break;
case CProtocol.GET_WAITTING_LIST://
{
Vector v = MGameController.getInstance().players;
Message m = new Message(CProtocol.GET_WAITTING_LIST);
m.putByte(0);
int size = v.size();
size = size > MGameController.MAX_ITEM_IN_A_PAGE ? MGameController.MAX_ITEM_IN_A_PAGE : size;
for (int i = size; --i >= 0;) {
Player p = (Player) v.elementAt(i);
m.putInt(p.playerID);
m.putString(p.playerName);
m.putLong(p.money);
}
player.session.write(m);
m.cleanup();
}
break;
case CProtocol.INVITE://
{
int subCommand = msg.reader().readByte();
int boardID = -1;
int playerID = -1;
if (subCommand == 1) {
boardID = msg.reader().readByte();
} else if (subCommand == 0) {
playerID = msg.reader().readInt();
boardID = player.boardID;
}
Board b = MGameController.getInstance().getBoard(boardID);
if (b == null) {
if (subCommand == 1) {
//cai nay cua thang tra loi.
} else if (subCommand == 0) {
GlobalServices.sendServerMessage(player, 1, "Ban khong duoc phep moi.");
}
}
if (subCommand == 0 && b.ownerID == player.playerID) {//chu phong
} else if (subCommand == 1) {
b.someoneJoinBoard(player);
}
}
break;
case CProtocol.KICK://
{
int pID = msg.reader().readInt();
Board b = MGameController.getInstance().getBoard(player.boardID);
if (b == null) {
return;
}
if (b.ownerID == player.playerID) {//neu la chu ban thi moi dc phep duoi.
Player p = b.getPlayerFromId(pID);
b.someoneExitBoard(p);
GameServices.processSomeOneLeaveBoardMessage(p.boardID, p);
Message m = new Message(CProtocol.KICK);
p.session.write(m);
m.cleanup();
}
}
break;
case CProtocol.BUY_SOLDIER_INGAME: {
int armyTypeID = msg.reader().readInt();
int x = msg.reader().readInt();
int y = msg.reader().readInt();
Board b = MGameController.getInstance().getBoard(player.boardID);
if (b != null && b.isStartGame) {
Soldier s = b.setArmyIngame(player, armyTypeID, x, y);
if (s == null) {
GlobalServices.sendServerMessage(player, 1, L.gl(player.languageType, 6));
} else {
int size = b.players.size();
for (int i = size; --i >= 0;) {
if (((Player) b.players.elementAt(i)).playerID != -1 && ((Player) b.players.elementAt(i)).session != null) {
sendSetArmyInGameTo(((Player) b.players.elementAt(i)), player, s);
}
}
}
} else if (b == null) {
GlobalServices.sendServerMessage(player, 1, L.gl(player.languageType, 7));
}
}
break;
case CProtocol.PING: {
long time = msg.reader().readLong();
Message m = new Message(CProtocol.PING);
m.putLong(System.currentTimeMillis());
player.session.write(m);
m.cleanup();
}
break;
case CProtocol.ACHIEVEMENT: {
String pName = msg.reader().readUTF();
Player p = PlayerManager.getInstance().getPlayerFromUsername(pName);
if (p != null) {
player.session.write(getMessageAchievement(p));
} else {
p = RegisterManager.getPlayer(pName);
if (p != null) {
player.session.write(getMessageAchievement(p));
} else {
GlobalServices.sendServerMessage(player, 1, "Không tồn tại user này trong hệ thống");
}
}
}
break;
}
}
private Message getMessageAchievement(Player p) {
Message m = new Message(CProtocol.ACHIEVEMENT);
m.putInt(p.playerID);
m.putString(p.userName);
m.putInt(p.winNumber);
m.putInt(p.loseNumber);
return m;
}
@Override
public void onDisconnected(Player user) {
MGameController.getInstance().exitBoard(user.boardID, user);
GameServices.processSomeOneLeaveBoardMessage(user.boardID, user);
}
public void sendSetArmyInGameTo(Player p, Player psetarmy, Soldier s) {
Message m = new Message(CProtocol.BUY_SOLDIER_INGAME);
m.putInt(psetarmy.playerID);
m.putInt((int) psetarmy.money);
m.putInt(s.typeID);
m.putInt(s.id);
m.putInt(s.x);
m.putInt(s.y);
p.session.write(m);
m.cleanup();
}
}
| zzzzzzzzzzz | trunk/j2seServer/src/vn/thedreamstudio/game/network/GameMessageHandler.java | Java | oos | 17,673 |