handcanvas.java

来自「3D手机游戏开发实例源代码」· Java 代码 · 共 771 行 · 第 1/3 页

JAVA
771
字号


import javax.microedition.lcdui.*;
import javax.microedition.m3g.*;


public class HandCanvas extends Canvas
                   implements CommandListener
{
  private static final String TEX_FNM = "/r.gif";
    // name of tex image file; change as required

  private static final float X_CAMERA = 0.0f; 
  private static final float Y_CAMERA = 0.0f; 
  private static final float Z_CAMERA = 3.0f; 
    // camera coordinates; change as required

  private static final float MODEL_MOVE = 0.2f; 
    // distance to move the model up/down/left/right/fwd/back for a key press

  private static final float MODEL_ROT = 5.0f;     // 5 degrees
    // angle to rotate the model left/right for a key press


  private HandDisplay top;

  private Graphics3D g3d;
  private Camera camera;
  private Light light;

  private Background bg;

  private VertexBuffer vertBuf; 
     // holds the model's positions, normals, colors coords, and tex coords
  private IndexBuffer idxBuf;   
     // indices to the model's triangle strips

  private Appearance app;

  private Transform camTrans, modelTrans;
    // transforms used by the camera and the model

  // model position and angle information
  private float xTrans, yTrans, zTrans;
  private int totalDegrees;

  private KeyRepeat keyRepeater;   // for repeating key presses


  public HandCanvas(HandDisplay top)
  {
    this.top = top;
    setCommandListener(this);
    keyRepeater = new KeyRepeat(this);
    keyRepeater.start();

    try {
      createScene();
    }
    catch (Exception e) 
    {  e.printStackTrace(); }
  } // end of HandCanvas()


  public void commandAction(Command c, Displayable d)
  {  
    if (c.getCommandType() == Command.EXIT) {
       keyRepeater.cancel();
       keyRepeater = null;
       top.quitApp();
     }
  } // end of commandAction()


  private void createScene() throws Exception
  {
    addCommand( new Command("Exit", Command.EXIT, 1) );

    g3d = Graphics3D.getInstance();

    // create a camera
    camera = new Camera();
    float aspectRatio = ((float) getWidth()) / ((float) getHeight());
    camera.setPerspective(45.0f, aspectRatio, 0.1f, 50.0f);
    // was 60, aspectRatio, 1, 1000

    // set up the camera's position
    camTrans = new Transform();
    camTrans.postTranslate(X_CAMERA, Y_CAMERA, Z_CAMERA);

    // create a light
    light = new Light();
    light.setColor(0xffffff);  // white light
    light.setIntensity(1.25f); // over bright

    // initialise the model's transform vars
    modelTrans = new Transform();
    xTrans = 0.0f; yTrans = 0.0f; zTrans = 0.0f;
    totalDegrees = 0;

    makeGeometry();
    makeAppearance();

    bg = new Background();
    bg.setColor(0x9EFEFE); // light blue 
  } // end of createScene()


  // ------------------- model creation -----------------------------

  private void makeGeometry()
  /* Read in the values for the vertices, normals, texture coords,
     and colour coords, and create a VertexBuffer object. Also
     read in the strip lengths array to create the index for the
     triangle strips used in the vertex buffer.

     Depending on the model, there may not be any texture or colour
     coordinates, and so the calls related to them should be commented
     out.

     The texture coordinates can use 2, 3, or 4 components, and the
     colour coordinates 3 or 4, which will require changes to the array
     creation code. The code here assumes (s,t) format for texture coords
     (2 components) and RGB for the colours (3 components), the most common 
     formats.
  */
  {
    // create vertices
    short[] verts = getVerts();
    VertexArray va = new VertexArray(verts.length/3, 3, 2);
    va.set(0, verts.length/3, verts);

    // create normals
    byte[] norms = getNormals();
    VertexArray normArray = new VertexArray(norms.length/3, 3, 1);
    normArray.set(0, norms.length/3, norms);
/*
    // create texture coordinates
    short[] tcs = getTexCoordsRev();
    VertexArray texArray = new VertexArray(tcs.length/2, 2, 2);
                          // this assumes (s,t) texture coordinates
    texArray.set(0, tcs.length/2, tcs);
*/
/*
    // create colour coordinates
    short[] cols = getColourCoords();
    VertexArray colsArray = new VertexArray(cols.length/3, 3, 2);
                          // this assumes RGB colour coordinates
    colsArray.set(0, cols.length/3, cols);
*/

    // ------ create the VertexBuffer for the model -------

    vertBuf = new VertexBuffer();
    float[] pbias = {(1.0f/255.0f), (1.0f/255.0f), (1.0f/255.0f)};
    vertBuf.setPositions(va, (2.0f/255.0f), pbias); // scale, bias
       // fix the scale and bias to create points in range [-1 to 1]

    vertBuf.setNormals(normArray);

    // vertBuf.setTexCoords(0, texArray, (1.0f/255.0f), null);
        // fix the scale to create texCoords in range [0 to 1] 

    // vertBuf.setColors(colsArray);

    // create the index buffer for the model (this tells MIDP how to
    // create triangle strips from the contents of the vertex buffer).
    idxBuf = new TriangleStripArray(0, getStripLengths() );
  }  // end of makeGeometry()

/*
  private short[] getTexCoordsRev()
  // Return an array of texture coords (s,t)
  // with their t coords reversed. 

  // This method will need to be commented out if there are 
  // no textures used in the model.
  { 
    short[] tcs = getTexCoords();

    // t' = 255 - t   (will later be scaled from 255 to 1)
    for(int i=1; i < tcs.length; i=i+2)
      tcs[i] = (short)(255 - tcs[i]);

    return tcs;
  }  // end of getTexCoordsRev()
*/


  private void makeAppearance() throws Exception
  /* Load the texture and material information into the Appearance
     node. 

     Depending on the model, there may not be a texture image, and so
     the texture-specific code here will need to be commented out.

     The material colour and shininess data is obtained from 
     setMatColours().
  */
  {
/*
    // load the image for the texture
    Image im = Image.createImage(TEX_FNM);

    // create an Image2D for the Texture2D
    Image2D image2D = new Image2D(Image2D.RGB, im);

    // create the Texture2D and enable mip mapping
    // the texture color is modulated with the lit material color
    Texture2D tex = new Texture2D(image2D);
    tex.setFiltering(Texture2D.FILTER_NEAREST, Texture2D.FILTER_NEAREST);
    tex.setWrapping(Texture2D.WRAP_CLAMP, Texture2D.WRAP_CLAMP);
    // tex.setWrapping(Texture2D.WRAP_REPEAT, Texture2D.WRAP_REPEAT);
    tex.setBlending(Texture2D.FUNC_MODULATE);
*/
    // create the appearance
    app = new Appearance();
    // app.setTexture(0, tex);
    app.setMaterial( setMatColours() );
  }  // end of makeAppearance()


  // ------------------ paint the canvas ------------------


  public void paint(Graphics g)
  {
    // bind the canvas graphic to our Graphics3D object
    g3d.bindTarget(g, true, Graphics3D.DITHER | Graphics3D.TRUE_COLOR);

    g3d.clear(bg);    // clear the color and depth buffers

    g3d.setCamera(camera, camTrans);   // position the camera

    // set up a "headlight": a directional light shining
    // from the direction of the camera
    g3d.resetLights();
    g3d.addLight(light, camTrans);

    updateModelTrans();

    // Render the model. We provide the vertex and index buffers
    // to specify the geometry; the appearance so we know what
    // material and texture to use; and a tranform to position
    // the model
    g3d.render(vertBuf, idxBuf, app, modelTrans);

    g3d.releaseTarget();      // flush
  } // end of paint()


  private void updateModelTrans()
  // the model's transform = a translation * a rotation
  {
    modelTrans.setIdentity();   // reset
    modelTrans.postTranslate(xTrans, yTrans, zTrans);
    modelTrans.postRotate(totalDegrees, 0, 1, 0);  // around y-axis

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?