/*
* Sample code for M3G article on IBM developerWorks.
* http://www.ibm.com/developerworks/
*/
package m3gsamples2;
import javax.microedition.lcdui.*;
import javax.microedition.m3g.*;
/**
* Sample that displays a simple cube with eight vertices. It has the same
* output than VerticesSample form the first part but uses retained mode instead
* of immediate mode.
*
* @author Claus Hoefele
*/
public class VerticesRetainedSample extends Canvas implements Sample
{
/** The cube's vertex positions (x, y, z). */
private static final byte[] VERTEX_POSITIONS = {
-1, -1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1,
-1, -1, -1, 1, -1, -1, -1, 1, -1, 1, 1, -1
};
/** Indices that define how to connect the vertices to build
* triangles. */
private static int[] TRIANGLE_INDICES = {
0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1
};
/** Object that represents the 3D world. */
private World _world;
/** Graphics singleton used for rendering. */
private Graphics3D _graphics3d;
/**
* Called when this sample is displayed.
*/
public void showNotify()
{
init();
}
/**
* Initializes the sample.
*/
protected void init()
{
// Get the singleton for 3D rendering and create a World.
_graphics3d = Graphics3D.getInstance();
_world = new World();
// Create vertex data.
VertexBuffer cubeVertexData = new VertexBuffer();
VertexArray vertexPositions =
new VertexArray(VERTEX_POSITIONS.length/3, 3, 1);
vertexPositions.set(0, VERTEX_POSITIONS.length/3, VERTEX_POSITIONS);
cubeVertexData.setPositions(vertexPositions, 1.0f, null);
// Create the triangles that define the cube; the indices point to
// vertices in VERTEX_POSITIONS.
TriangleStripArray cubeTriangles = new TriangleStripArray(
TRIANGLE_INDICES, new int[] {TRIANGLE_INDICES.length});
// Create a Mesh that represents the cube.
Mesh cubeMesh = new Mesh(cubeVertexData, cubeTriangles, new Appearance());
_world.addChild(cubeMesh);
// Create a camera with perspective projection.
Camera camera = new Camera();
float aspect = (float) getWidth() / (float) getHeight();
camera.setPerspective(30.0f, aspect, 1.0f, 1000.0f);
camera.setTranslation(0.0f, 0.0f, 10.0f);
_world.addChild(camera);
_world.setActiveCamera(camera);
}
/**
* Renders the sample on the screen.
*
* @param graphics the graphics object to draw on.
*/
protected void paint(Graphics graphics)
{
_graphics3d.bindTarget(graphics);
_graphics3d.render(_world);
_graphics3d.releaseTarget();
}
/**
* Returns the <code>Displayable</code> used to display this sample.
*
* @return display
*/
public Displayable getDisplayable()
{
return this;
}
/**
* Returns the display name of this sample.
*
* @return name
*/
public String getName()
{
return "Cube Vertices Retained";
}
}
|