World Class

Carlos – World Class – First Prototype

World Class
World in this game is made by blocks that can by passable or cannot, there is different class used to handle boxes it is called CBox. Idea is really simple but really effective and popular in industry. (google for Minecraft or cubeengine – fun fact Crytek – has used little *ekhem*, well bit more than that.. but based on the same idea solution  for Crisis, where whole world is created by millions of boxes that allows creation of tunnels, caves, etc.

Feature
Load, process and draw  3-dimension map, it is container class that contains all elements that are on map player, AI opponent, floor, walls, lights.

Class include:

  • Update on click/touch
  • Process lights – note: only exit point light – requires future development
  • Draw – draw blocks
  • Checker for boxes is is passable
  • Clearing visited positions
  • keep past and current frame time

File Structure:

File structure is very simple

// x y z - this is just simple comment ignored by script
ARRAY 4 3 5 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

ARRAY – is used for 2 goals

  1. Create Array that will keeps details about map
  2. last two numbers specifying block on map that we have go to.

Code

package com.fps.carlos;

import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import com.iamedu.gfx.IMesh;
import com.path.TileBasedMap;

import android.content.Context;

import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;

/**
* This class is our World representation
*
* @author Lukasz Iwanski
*/
public class World implements OnKeyListener, OnTouchListener, TileBasedMap {

/** The Activity Context */
private Context context;

/** The World sector */
//private Sector sector1;

/** Create new Player - human **/
private Player player;

private int xWorld;
private int yWorld;
private int zWorld;

private long pastFrame, currentFrame;
float temp;

/** Indicator if a given tile has been visited during the search */
private boolean[][] visited;

/*
* used to allow to moving accross the world
*
*/

/* input handler */
private float oldX;
private float oldY;
private final float TOUCH_SCALE = 0.2f;			//Proved to be good for rotation

/**
* The World constructor
*
* @param context - The Activity Context
*/
public World(Context context) {
this.context = context;
this.setCurrentFrame(getCurrentTime());

}

//array to keep our boxes on the world

public String bFromTextFile[];
public CBox aWorld[][][];

// win point
private int finishPointX;
private int finishPointY;
/* The buffers for our light values */
private FloatBuffer lightAmbientBuffer;
private FloatBuffer lightDiffuseBuffer;
private FloatBuffer lightPositionBuffer;

private AIPlayer ai;

/**
* @param fileName - The file name to load from the Asset directory
*/
public void loadWorld(String fileName) {
try {
//Some temporary variables

List lines = null;

//Quick Reader for the input file
BufferedReader reader = new BufferedReader(new InputStreamReader(this.context.getAssets().open(fileName)));

//Iterate over all lines
String line = null;
while((line = reader.readLine()) != null) {
//Skip comments and empty lines
if(line.startsWith("//") || line.trim().equals("")) {
continue;
}

//Read how many polygons this file contains
if(line.startsWith("ARRAY")) {

xWorld = Integer.valueOf(line.split(" ")[1]);
yWorld = Integer.valueOf(line.split(" ")[2]);
zWorld = Integer.valueOf(line.split(" ")[3]);
finishPointX = Integer.valueOf(line.split(" ")[4]);
finishPointY = Integer.valueOf(line.split(" ")[5]);

}else {
if(lines == null) {
lines = new ArrayList();
}

bFromTextFile = line.split(" ");

}
//chop next line to get cubes types

}

//Clean up!
reader.close();

int helper = 0;
aWorld = new CBox[xWorld][yWorld][zWorld];
for(int y = 0; y< yWorld; y++ )
{
for(int z = 0; z 				{
for(int x = 0; x 					{
int temp = Integer.parseInt(bFromTextFile[helper]);
aWorld[x][y][z] = new CBox(x,y,z,temp);
helper++;

}

}
}

visited = new boolean[this.xWorld][this.zWorld];
this.player = new Player(aWorld);
this.ai = new AIPlayer(this);

//Now iterate over all read lines...

//If anything should happen, write a log and return
} catch(Exception e) {
Log.e("World", "Could not load the World file!", e);
return;
}

}
/**
* The world drawing function.
*
* @param gl - The GL Context
* @param filter - Which texture filter to use
*/
public void draw(GL10 gl, int texure, IMesh mesh) {

this.setPastFrame(getCurrentFrame());
this.setCurrentFrame(getCurrentTime());

//Bind the texture based on the given filter
gl.glBindTexture(GL10.GL_TEXTURE_2D, texure);

float xtrans = -player.getXpos();						//Used For Player Translation On The X Axis
float ztrans = -player.getZpos();						//Used For Player Translation On The Z Axis
float ytrans = -player.getWalkbias() - 0.25f;			//Used For Bouncing Motion Up And Down
float sceneroty = 360.0f - player.getYrot();			//360 Degree Angle For Player Direction

//View
gl.glRotatef(player.getLookupdown(), 1.0f, 0, 0);		//Rotate Up And Down To Look Up And Down
gl.glRotatef(sceneroty, 0, 1.0f, 0);		//Rotate Depending On Direction Player Is Facing
gl.glTranslatef(xtrans, ytrans, ztrans);	//Translate The Scene Based On Player Position

//Enable the vertex, texture and normal state
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

//draw world elements

//Point to our buffers

drawCubes(gl);

//draw exit light
this.updateLight();
//this.drawLight(gl);

player.updateLight();
player.drawLight(gl);

ai.update(player);
ai.draw(gl, mesh);

//Disable the client state before leaving
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

}

private void drawCubes(GL10 gl) {
// TODO Auto-generated method stub
for(int y = 0; y< yWorld; y++ )
{
for(int z = 0; z 			{
for(int x = 0; x= 0.88)
{
temp = 0.1f;
}else {

temp = temp + 0.23f;
}

Log.v("temp", temp+"");
float[] lightAmbient = {0.0f, temp, 0.0f, 1.0f};
float[] lightDiffuse = {0.0f, temp, 0.0f, 1.0f};
float[] lightPosition = {this.finishPointX, 0.5f, this.finishPointY, temp};

ByteBuffer byteBuf = ByteBuffer.allocateDirect(lightAmbient.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
lightAmbientBuffer = byteBuf.asFloatBuffer();
lightAmbientBuffer.put(lightAmbient);
lightAmbientBuffer.position(0);

byteBuf = ByteBuffer.allocateDirect(lightDiffuse.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
lightDiffuseBuffer = byteBuf.asFloatBuffer();
lightDiffuseBuffer.put(lightDiffuse);
lightDiffuseBuffer.position(0);

byteBuf = ByteBuffer.allocateDirect(lightPosition.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
lightPositionBuffer = byteBuf.asFloatBuffer();
lightPositionBuffer.put(lightPosition);
lightPositionBuffer.position(0);

}

public void drawLight(GL10 gl)
{
//And there'll be light!
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_AMBIENT, lightAmbientBuffer);		//Setup The Ambient Light
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_DIFFUSE, lightDiffuseBuffer);		//Setup The Diffuse Light
gl.glLightfv(GL10.GL_LIGHT1, GL10.GL_POSITION, lightPositionBuffer);	//Position The Light
gl.glEnable(GL10.GL_LIGHT1);

//Enable Light 0

}

/* ***** Listener Events ***** */
/**
* Override the key listener to receive onKey events.
*
*/
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
//Handle key down events
if(event.getAction() == KeyEvent.ACTION_DOWN) {
return onKeyDown(keyCode, event);
}

return false;
}

/**
* Check for the DPad presses left, right, up and down.
* Walk in the according direction or rotate the "head".
*
* @param keyCode - The key code
* @param event - The key event
* @return If the event has been handled
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {

player.log();

if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
player.left();

} else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
player.right();

} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
player.forward();

} else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
player.backward();
}

return true;
}

/**
* React to moves on the touchscreen.
*/
@Override
public boolean onTouch(View v, MotionEvent event) {
//
boolean handled = false;

//
float x = event.getX();
float y = event.getY();

//If a touch is moved on the screen
if(event.getAction() == MotionEvent.ACTION_MOVE) {
//Calculate the change
float dx = x - oldX;
float dy = y - oldY;

float heading = player.getHeading();
float lookupdown = player.getLookupdown();
float yrot = heading;

//Up and down looking through touch
lookupdown += dy * TOUCH_SCALE;
//Look left and right through moving on screen
heading += dx * TOUCH_SCALE;
yrot = heading;

player.setLookupdown(lookupdown);
player.setHeading(heading);
player.setYrot(yrot);

//We handled the event
handled = true;
}

//Remember the values
oldX = x;
oldY = y;

//
return handled;
}

public int getX()
{
return this.xWorld;
}
public int getZ()
{
return this.zWorld;
}
public boolean isMoveAllowed(int dx, int dy) {

if(dx >= this.xWorld)
{
return false;
}else if(dy>= this.zWorld)
{
return false;
}else if(dy < 0 || dx < 0){
return false;
}else {

Log.v("dx dy", dx+" "+dy);

if(aWorld[dx][1][dy].isPassAble() == true)
{
Log.v("dx dy", dx+" "+dy +" - is allowed");
return true;

}
}

return false;
}
@Override
public int getWidthInTiles() {
// TODO Auto-generated method stub
return this.xWorld;
}
@Override
public int getHeightInTiles() {
// TODO Auto-generated method stub
return this.zWorld;
}
/**
* Clear the array marking which tiles have been visted by the path
* finder.
*/
public void clearVisited() {
for (int x=0;x 			for (int y=0;y 				visited[x][y] = false;
}
}
}
/**
* @see TileBasedMap#visited(int, int)
*/
public boolean visited(int x, int y) {
return visited[x][y];
}
@Override
public void pathFinderVisited(int x, int y) {
// TODO Auto-generated method stub
visited[x][y] = true;
}
@Override
public boolean blocked(int x, int y) {
// TODO Auto-generated method stub
if(aWorld[x][1][y].isPassAble())
{
return true;
}
return false;
}
@Override
public float getCost(int sx, int sy, int tx, int ty) {
// TODO Auto-generated method stub
return 1;
}

public void setPastFrame(long pastFrame) {
this.pastFrame = pastFrame;
}

public long getPastFrame() {
return pastFrame;
}

public void setCurrentFrame(long currentFrame) {
this.currentFrame = currentFrame;
}

public long getCurrentFrame() {
return currentFrame;
}

public long getCurrentTime()
{
Calendar now = Calendar.getInstance();
return now.getTimeInMillis();
}

Future Improvement

  • 2D interface – used to display animation and controls on the display, current game time, mini map, compas and other features that allows user to feel more comfortable during playing a game
  • Improve AI
  • Multi-users handler
  • Collision detection improvement – collision between players
  • Improvement of player position – allows player to move between levels – eg lifts between floors
  • Improvement for lighting system
  • Other 3D objects files importer

Published by

Luke Iwanski

Senior Graphics Programmer @ CD Projekt RED

Leave a Reply

Your email address will not be published. Required fields are marked *