// First3DMIDlet.java package first3d; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class First3DMIDlet extends MIDlet { private First3DCanvas displayable = new First3DCanvas(); public void startApp() { Display.getDisplay(this).setCurrent(displayable); }
public void pauseApp() {}
public void destroyApp(boolean unconditional) {} }
// First3Dcanvas.java package first3d; import javax.microedition.lcdui.*; import javax.microedition.m3g.*; import java.util.*; /** * 第一个3D程序 */ public class First3DCanvas extends Canvas implements Runnable { /**World对象*/ private World myWorld = null; /**Graphics3D对象*/ private Graphics3D g3d = Graphics3D.getInstance(); /**Camera对象*/ private Camera cam = null; private int viewport_x; private int viewport_y; private int viewport_width; private int viewport_height; private long worldStartTime = 0; //重绘时间 private int validity = 0; public First3DCanvas() { //启动重绘界面的线程 Thread thread = new Thread(this); thread.start(); try { //导入3D图片 myWorld = (World) Loader.load("/swerve.m3g")[0]; viewport_x = 0; viewport_y = 0; viewport_width = getWidth(); viewport_height = getHeight(); cam = myWorld.getActiveCamera(); //设置cam对象 float[] params = new float[4]; int type = cam.getProjection(params); if (type != Camera.GENERIC) { //calculate window aspect ratio float waspect = viewport_width / viewport_height; if (waspect < params[1]) { float height = viewport_width / params[1]; viewport_height = (int) height; viewport_y = (getHeight() - viewport_height) / 2; } else { float width = viewport_height * params[1]; viewport_width = (int) width; viewport_x = (getWidth() - viewport_width) / 2; } } worldStartTime = System.currentTimeMillis(); } catch (Exception e) {} } protected void paint(Graphics g) { //清除背景 g.setColor(0x00); g.fillRect(0, 0, getWidth(), getHeight()); //和3D对象绑定 g3d.bindTarget(g); g3d.setViewport(viewport_x, viewport_y, viewport_width, viewport_height); long startTime = System.currentTimeMillis() - worldStartTime; validity = myWorld.animate((int)startTime); try { g3d.render(myWorld); } finally { g3d.releaseTarget(); } }
public void run() { try { while(true) { //重绘图形 repaint(viewport_x, viewport_y, viewport_width, viewport_height); } } catch(Exception e){} } } |