Java/3D/Cube

Материал из Java эксперт
Версия от 09:15, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creates 1000 same-sized cubes and compiles the scene

   <source lang="java">

/**********************************************************

Copyright (C) 2001   Daniel Selman
First distributed with the book "Java 3D Programming"
by Daniel Selman and published by Manning Publications.
http://manning.ru/selman
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, version 2.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
The license can be found on the WWW at:
http://www.fsf.org/copyleft/gpl.html
Or by writing to:
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
Authors can be contacted at:
Daniel Selman: daniel@selman.org
If you make changes you think others would like, please 
contact one of the authors or someone at the 
www.j3d.org web site.
**************************************************************/

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.GraphicsConfigTemplate; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.io.File; import java.net.URL; import javax.media.j3d.Alpha; import javax.media.j3d.AudioDevice; import javax.media.j3d.Background; import javax.media.j3d.BoundingSphere; import javax.media.j3d.Bounds; import javax.media.j3d.BranchGroup; import javax.media.j3d.Canvas3D; import javax.media.j3d.GraphicsConfigTemplate3D; import javax.media.j3d.Group; import javax.media.j3d.Locale; import javax.media.j3d.PhysicalBody; import javax.media.j3d.PhysicalEnvironment; import javax.media.j3d.RotationInterpolator; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import javax.media.j3d.View; import javax.media.j3d.ViewPlatform; import javax.media.j3d.VirtualUniverse; import javax.vecmath.Color3f; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import com.sun.j3d.audioengines.javasound.JavaSoundMixer; import com.sun.j3d.utils.applet.MainFrame; import com.sun.j3d.utils.geometry.ColorCube; //import org.selman.java3d.book.rumon.*; /**

* Creates 1000 same-sized cubes and compiles the scene.
*/

public class CompileTest extends Java3dApplet {

 private static int m_kWidth = 256;
 private static int m_kHeight = 256;
 public CompileTest() {
   initJava3d();
 }
 private BranchGroup createColorCubes() {
   BranchGroup bg = new BranchGroup();
   final int kNumCubes = 1000;
   for (int n = 0; n < kNumCubes; n++) {
     ColorCube cube1 = new ColorCube(1.0);
     // switch off pickable attribute so we can compile
     cube1.setPickable(false);
     bg.addChild(cube1);
   }
   bg.rupile();
   return bg;
 }
 protected BranchGroup createSceneBranchGroup() {
   BranchGroup objRoot = super.createSceneBranchGroup();
   // do NOT auto compute bounds for this node
   objRoot.setBoundsAutoCompute(false);
   TransformGroup objTrans = new TransformGroup();
   objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
   objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
   Transform3D yAxis = new Transform3D();
   Alpha rotationAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE, 0, 0,
       4000, 0, 0, 0, 0, 0);
   RotationInterpolator rotator = new RotationInterpolator(rotationAlpha,
       objTrans, yAxis, 0.0f, (float) Math.PI * 2.0f);
   rotator.setSchedulingBounds(createApplicationBounds());
   objTrans.addChild(rotator);
   objTrans.addChild(createColorCubes());
   objRoot.addChild(objTrans);
   return objRoot;
 }
 public static void main(String[] args) {
   CompileTest compileTest = new CompileTest();
   compileTest.saveCommandLineArguments(args);
   new MainFrame(compileTest, m_kWidth, m_kHeight);
 }

} /*******************************************************************************

* Copyright (C) 2001 Daniel Selman
* 
* First distributed with the book "Java 3D Programming" by Daniel Selman and
* published by Manning Publications. http://manning.ru/selman
* 
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, version 2.
* 
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* 
* The license can be found on the WWW at: http://www.fsf.org/copyleft/gpl.html
* 
* Or by writing to: Free Software Foundation, Inc., 59 Temple Place - Suite
* 330, Boston, MA 02111-1307, USA.
* 
* Authors can be contacted at: Daniel Selman: daniel@selman.org
* 
* If you make changes you think others would like, please contact one of the
* authors or someone at the www.j3d.org web site.
******************************************************************************/

//***************************************************************************** /**

* Java3dApplet
* 
* Base class for defining a Java 3D applet. Contains some useful methods for
* defining views and scenegraphs etc.
* 
* @author Daniel Selman
* @version 1.0
*/

//***************************************************************************** abstract class Java3dApplet extends Applet {

 public static int m_kWidth = 300;
 public static int m_kHeight = 300;
 protected String[] m_szCommandLineArray = null;
 protected VirtualUniverse m_Universe = null;
 protected BranchGroup m_SceneBranchGroup = null;
 protected Bounds m_ApplicationBounds = null;

// protected com.tornadolabs.j3dtree.Java3dTree m_Java3dTree = null;

 public Java3dApplet() {
 }
 public boolean isApplet() {
   try {
     System.getProperty("user.dir");
     System.out.println("Running as Application.");
     return false;
   } catch (Exception e) {
   }
   System.out.println("Running as Applet.");
   return true;
 }
 public URL getWorkingDirectory() throws java.net.MalformedURLException {
   URL url = null;
   try {
     File file = new File(System.getProperty("user.dir"));
     System.out.println("Running as Application:");
     System.out.println("   " + file.toURL());
     return file.toURL();
   } catch (Exception e) {
   }
   System.out.println("Running as Applet:");
   System.out.println("   " + getCodeBase());
   return getCodeBase();
 }
 public VirtualUniverse getVirtualUniverse() {
   return m_Universe;
 }
 //public com.tornadolabs.j3dtree.Java3dTree getJ3dTree() {
   //return m_Java3dTree;

// }

 public Locale getFirstLocale() {
   java.util.Enumeration e = m_Universe.getAllLocales();
   if (e.hasMoreElements() != false)
     return (Locale) e.nextElement();
   return null;
 }
 protected Bounds getApplicationBounds() {
   if (m_ApplicationBounds == null)
     m_ApplicationBounds = createApplicationBounds();
   return m_ApplicationBounds;
 }
 protected Bounds createApplicationBounds() {
   m_ApplicationBounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
       100.0);
   return m_ApplicationBounds;
 }
 protected Background createBackground() {
   Background back = new Background(new Color3f(0.9f, 0.9f, 0.9f));
   back.setApplicationBounds(createApplicationBounds());
   return back;
 }
 public void initJava3d() {
 //  m_Java3dTree = new com.tornadolabs.j3dtree.Java3dTree();
   m_Universe = createVirtualUniverse();
   Locale locale = createLocale(m_Universe);
   BranchGroup sceneBranchGroup = createSceneBranchGroup();
   ViewPlatform vp = createViewPlatform();
   BranchGroup viewBranchGroup = createViewBranchGroup(
       getViewTransformGroupArray(), vp);
   createView(vp);
   Background background = createBackground();
   if (background != null)
     sceneBranchGroup.addChild(background);

// m_Java3dTree.recursiveApplyCapability(sceneBranchGroup);

 //  m_Java3dTree.recursiveApplyCapability(viewBranchGroup);
   locale.addBranchGraph(sceneBranchGroup);
   addViewBranchGroup(locale, viewBranchGroup);
   onDoneInit();
 }
 protected void onDoneInit() {
 //  m_Java3dTree.updateNodes(m_Universe);
 }
 protected double getScale() {
   return 1.0;
 }
 public TransformGroup[] getViewTransformGroupArray() {
   TransformGroup[] tgArray = new TransformGroup[1];
   tgArray[0] = new TransformGroup();
   // move the camera BACK a little...
   // note that we have to invert the matrix as
   // we are moving the viewer
   Transform3D t3d = new Transform3D();
   t3d.setScale(getScale());
   t3d.setTranslation(new Vector3d(0.0, 0.0, -20.0));
   t3d.invert();
   tgArray[0].setTransform(t3d);
   return tgArray;
 }
 protected void addViewBranchGroup(Locale locale, BranchGroup bg) {
   locale.addBranchGraph(bg);
 }
 protected Locale createLocale(VirtualUniverse u) {
   return new Locale(u);
 }
 protected BranchGroup createSceneBranchGroup() {
   m_SceneBranchGroup = new BranchGroup();
   return m_SceneBranchGroup;
 }
 protected View createView(ViewPlatform vp) {
   View view = new View();
   PhysicalBody pb = createPhysicalBody();
   PhysicalEnvironment pe = createPhysicalEnvironment();
   AudioDevice audioDevice = createAudioDevice(pe);
   if (audioDevice != null) {
     pe.setAudioDevice(audioDevice);
     audioDevice.initialize();
   }
   view.setPhysicalEnvironment(pe);
   view.setPhysicalBody(pb);
   if (vp != null)
     view.attachViewPlatform(vp);
   view.setBackClipDistance(getBackClipDistance());
   view.setFrontClipDistance(getFrontClipDistance());
   Canvas3D c3d = createCanvas3D();
   view.addCanvas3D(c3d);
   addCanvas3D(c3d);
   return view;
 }
 protected PhysicalBody createPhysicalBody() {
   return new PhysicalBody();
 }
 protected AudioDevice createAudioDevice(PhysicalEnvironment pe) {
   JavaSoundMixer javaSoundMixer = new JavaSoundMixer(pe);
   if (javaSoundMixer == null)
     System.out.println("create of audiodevice failed");
   return javaSoundMixer;
 }
 protected PhysicalEnvironment createPhysicalEnvironment() {
   return new PhysicalEnvironment();
 }
 protected float getViewPlatformActivationRadius() {
   return 100;
 }
 protected ViewPlatform createViewPlatform() {
   ViewPlatform vp = new ViewPlatform();
   vp.setViewAttachPolicy(View.RELATIVE_TO_FIELD_OF_VIEW);
   vp.setActivationRadius(getViewPlatformActivationRadius());
   return vp;
 }
 protected Canvas3D createCanvas3D() {
   GraphicsConfigTemplate3D gc3D = new GraphicsConfigTemplate3D();
   gc3D.setSceneAntialiasing(GraphicsConfigTemplate.PREFERRED);
   GraphicsDevice gd[] = GraphicsEnvironment.getLocalGraphicsEnvironment()
       .getScreenDevices();
   Canvas3D c3d = new Canvas3D(gd[0].getBestConfiguration(gc3D));
   c3d.setSize(getCanvas3dWidth(c3d), getCanvas3dHeight(c3d));
   return c3d;
 }
 protected int getCanvas3dWidth(Canvas3D c3d) {
   return m_kWidth;
 }
 protected int getCanvas3dHeight(Canvas3D c3d) {
   return m_kHeight;
 }
 protected double getBackClipDistance() {
   return 100.0;
 }
 protected double getFrontClipDistance() {
   return 1.0;
 }
 protected BranchGroup createViewBranchGroup(TransformGroup[] tgArray,
     ViewPlatform vp) {
   BranchGroup vpBranchGroup = new BranchGroup();
   if (tgArray != null && tgArray.length > 0) {
     Group parentGroup = vpBranchGroup;
     TransformGroup curTg = null;
     for (int n = 0; n < tgArray.length; n++) {
       curTg = tgArray[n];
       parentGroup.addChild(curTg);
       parentGroup = curTg;
     }
     tgArray[tgArray.length - 1].addChild(vp);
   } else
     vpBranchGroup.addChild(vp);
   return vpBranchGroup;
 }
 protected void addCanvas3D(Canvas3D c3d) {
   setLayout(new BorderLayout());
   add(c3d, BorderLayout.CENTER);
   doLayout();
 }
 protected VirtualUniverse createVirtualUniverse() {
   return new VirtualUniverse();
 }
 protected void saveCommandLineArguments(String[] szArgs) {
   m_szCommandLineArray = szArgs;
 }
 protected String[] getCommandLineArguments() {
   return m_szCommandLineArray;
 }

}


      </source>
   
  
 
  



HelloJava3Dbalt renders a single, rotated cube

   <source lang="java">

/*

* HelloJava3Dbalt.java
* 
* Copyright (c) 1996-1998 Sun Microsystems, Inc. All Rights Reserved.
* 
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
* 
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGES.
* 
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear facility.
* Licensee represents and warrants that it will not use or redistribute the
* Software for such purposes.
*/

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Frame; import javax.media.j3d.BranchGroup; import javax.media.j3d.Canvas3D; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import com.sun.j3d.utils.applet.MainFrame; import com.sun.j3d.utils.geometry.ColorCube; import com.sun.j3d.utils.universe.SimpleUniverse; // HelloJava3Dbalt renders a single, rotated cube. public class HelloJava3Dbalt extends Applet {

 public BranchGroup createSceneGraph() {
   // Create the root of the branch graph
   BranchGroup objRoot = new BranchGroup();
   // rotate object has composited transformation matrix
   Transform3D rotate = new Transform3D();
   Transform3D tempRotate = new Transform3D();
   rotate.rotX(Math.PI / 4.0d);
   tempRotate.rotY(Math.PI / 5.0d);
   tempRotate.mul(rotate);
   TransformGroup objRotate = new TransformGroup(tempRotate);
   objRoot.addChild(objRotate);
   objRotate.addChild(new ColorCube(0.4));
   // Let Java 3D perform optimizations on this scene graph.
   objRoot.rupile();
   return objRoot;
 } // end of CreateSceneGraph method of HelloJava3Dbalt
 // Create a simple scene and attach it to the virtual universe
 public HelloJava3Dbalt() {
   setLayout(new BorderLayout());
   Canvas3D canvas3D = new Canvas3D(null);
   add("Center", canvas3D);
   BranchGroup scene = createSceneGraph();
   // SimpleUniverse is a Convenience Utility class
   SimpleUniverse simpleU = new SimpleUniverse(canvas3D);
   // This will move the ViewPlatform back a bit so the
   // objects in the scene can be viewed.
   simpleU.getViewingPlatform().setNominalViewingTransform();
   simpleU.addBranchGraph(scene);
 } // end of HelloJava3Db (constructor)
 //  The following allows this to be run as an application
 //  as well as an applet
 public static void main(String[] args) {
   Frame frame = new MainFrame(new HelloJava3Dbalt(), 256, 256);
 } // end of main (method of HelloJava3Dbalt)

} // end of class HelloJava3Dbalt


      </source>
   
  
 
  



Pyramid 2 Cube

   <source lang="java">

/*

* @(#)Pyramid2Cube.java 1.18 02/10/21 13:45:50
* 
* Copyright (c) 1996-2002 Sun Microsystems, Inc. All Rights Reserved.
* 
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*  - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*  - Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* 
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGES.
* 
* You acknowledge that Software is not designed,licensed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/

import java.applet.Applet; import java.awt.BorderLayout; import java.awt.GraphicsConfiguration; import java.util.Enumeration; import javax.media.j3d.Alpha; import javax.media.j3d.Appearance; import javax.media.j3d.Background; import javax.media.j3d.Behavior; import javax.media.j3d.BoundingSphere; import javax.media.j3d.BranchGroup; import javax.media.j3d.Canvas3D; import javax.media.j3d.GeometryArray; import javax.media.j3d.Morph; import javax.media.j3d.QuadArray; import javax.media.j3d.Shape3D; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import javax.media.j3d.WakeupOnElapsedFrames; import javax.vecmath.Color3f; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import com.sun.j3d.utils.applet.MainFrame; import com.sun.j3d.utils.universe.SimpleUniverse; public class Pyramid2Cube extends Applet {

 private SimpleUniverse u = null;
 private BranchGroup createSceneGraph() {
   // Create the root of the branch graph
   BranchGroup objRoot = new BranchGroup();
   // Create a Transformgroup to scale all objects so they
   // appear in the scene.
   TransformGroup objScale = new TransformGroup();
   Transform3D t3d = new Transform3D();
   t3d.setScale(0.4);
   objScale.setTransform(t3d);
   objRoot.addChild(objScale);
   // Create a bounds for the background and behavior
   BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
       100.0);
   // Set up the background
   Color3f bgColor = new Color3f(0.05f, 0.05f, 0.2f);
   Background bg = new Background(bgColor);
   bg.setApplicationBounds(bounds);
   objScale.addChild(bg);
   //
   // Create the transform group nodes for the 3 original objects
   // and the morphed object. Add them to the root of the
   // branch graph.
   //
   TransformGroup objTrans[] = new TransformGroup[4];
   for (int i = 0; i < 4; i++) {
     objTrans[i] = new TransformGroup();
     objScale.addChild(objTrans[i]);
   }
   Transform3D tr = new Transform3D();
   Transform3D rotY15 = new Transform3D();
   rotY15.rotY(15.0 * Math.PI / 180.0);
   objTrans[0].getTransform(tr);
   tr.setTranslation(new Vector3d(-3.0, 1.5, -6.5));
   tr.mul(rotY15);
   objTrans[0].setTransform(tr);
   objTrans[1].getTransform(tr);
   tr.setTranslation(new Vector3d(0.0, 1.5, -6.5));
   tr.mul(rotY15);
   objTrans[1].setTransform(tr);
   objTrans[2].getTransform(tr);
   tr.setTranslation(new Vector3d(3.0, 1.5, -6.5));
   tr.mul(rotY15);
   objTrans[2].setTransform(tr);
   objTrans[3].getTransform(tr);
   tr.setTranslation(new Vector3d(0.0, -2.0, -5.0));
   tr.mul(rotY15);
   objTrans[3].setTransform(tr);
   // Now create simple geometries.
   QuadArray g[] = new QuadArray[3];
   Shape3D shape[] = new Shape3D[3];
   for (int i = 0; i < 3; i++) {
     g[i] = null;
     shape[i] = null;
   }
   g[0] = new ColorPyramidUp();
   g[1] = new ColorCube();
   g[2] = new ColorPyramidDown();
   Appearance a = new Appearance();
   for (int i = 0; i < 3; i++) {
     shape[i] = new Shape3D(g[i], a);
     objTrans[i].addChild(shape[i]);
   }
   //
   // Create a Morph node, and set the appearance and input geometry
   // arrays. Set the Morph node"s capability bits to allow the weights
   // to be modified at runtime.
   //
   Morph morph = new Morph((GeometryArray[]) g, a);
   morph.setCapability(Morph.ALLOW_WEIGHTS_READ);
   morph.setCapability(Morph.ALLOW_WEIGHTS_WRITE);
   objTrans[3].addChild(morph);
   // Now create the Alpha object that controls the speed of the
   // morphing operation.
   Alpha morphAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE
       | Alpha.DECREASING_ENABLE, 0, 0, 4000, 1000, 500, 4000, 1000,
       500);
   // Finally, create the morphing behavior
   MorphingBehavior mBeh = new MorphingBehavior(morphAlpha, morph);
   mBeh.setSchedulingBounds(bounds);
   objScale.addChild(mBeh);
   return objRoot;
 }
 public Pyramid2Cube() {
 }
 public void init() {
   setLayout(new BorderLayout());
   GraphicsConfiguration config = SimpleUniverse
       .getPreferredConfiguration();
   Canvas3D c = new Canvas3D(config);
   add("Center", c);
   // Create a simple scene and attach it to the virtual universe
   BranchGroup scene = createSceneGraph();
   u = new SimpleUniverse(c);
   // This will move the ViewPlatform back a bit so the
   // objects in the scene can be viewed.
   u.getViewingPlatform().setNominalViewingTransform();
   u.addBranchGraph(scene);
 }
 public void destroy() {
   u.cleanup();
 }
 public static void main(String[] args) {
   new MainFrame(new Pyramid2Cube(), 700, 700);
 }

} class ColorPyramidUp extends QuadArray {

 private static final float[] verts = {
 // front face
     1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f,
     -1.0f, 1.0f,
     // back face
     -1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
     -1.0f, -1.0f,
     // right face
     1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
     -1.0f, 1.0f,
     // left face
     -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f,
     -1.0f, -1.0f,
     // top face
     0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
     0.0f,
     // bottom face
     -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f,
     -1.0f, 1.0f, };
 private static final float[] colors = {
 // front face (cyan)
     0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
     1.0f,
     // back face (magenta)
     1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
     1.0f,
     // right face (yellow)
     1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
     0.0f,
     // left face (blue)
     0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
     1.0f,
     // top face (green)
     0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
     0.0f,
     // bottom face (red)
     1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,
 };
 ColorPyramidUp() {
   super(24, QuadArray.COORDINATES | QuadArray.COLOR_3);
   setCoordinates(0, verts);
   setColors(0, colors);
 }

} class ColorCube extends QuadArray {

 private static final float[] verts = {
 // front face
     1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f,
     -1.0f, 1.0f,
     // back face
     -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,
     -1.0f, -1.0f,
     // right face
     1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
     -1.0f, 1.0f,
     // left face
     -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
     -1.0f, -1.0f,
     // top face
     1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
     1.0f, 1.0f,
     // bottom face
     -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f,
     -1.0f, 1.0f, };
 private static final float[] colors = {
 // front face (red)
     1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,
     // back face (green)
     0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
     0.0f,
     // right face (blue)
     0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
     1.0f,
     // left face (yellow)
     1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
     0.0f,
     // top face (magenta)
     1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
     1.0f,
     // bottom face (cyan)
     0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
     1.0f, };
 ColorCube() {
   super(24, QuadArray.COORDINATES | QuadArray.COLOR_3);
   setCoordinates(0, verts);
   setColors(0, colors);
 }

} class ColorPyramidDown extends QuadArray {

 private static final float[] verts = {
 // front face
     0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f,
     -1.0f, 0.0f,
     // back face
     0.0f, -1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 0.0f,
     -1.0f, 0.0f,
     // right face
     0.0f, -1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
     -1.0f, 0.0f,
     // left face
     0.0f, -1.0f, 0.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 0.0f,
     -1.0f, 0.0f,
     // top face
     1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
     1.0f, 1.0f,
     // bottom face
     0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
     -1.0f, 0.0f, };
 private static final float[] colors = {
 // front face (green)
     0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
     0.0f,
     // back face (red)
     1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,
     // right face (yellow)
     1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
     0.0f,
     // left face (magenta)
     1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
     1.0f,
     // top face (blue)
     0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
     1.0f,
     // bottom face (cyan)
     0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
     1.0f, };
 ColorPyramidDown() {
   super(24, QuadArray.COORDINATES | QuadArray.COLOR_3);
   setCoordinates(0, verts);
   setColors(0, colors);
 }

} //User-defined morphing behavior class class MorphingBehavior extends Behavior {

 Alpha alpha;
 Morph morph;
 double weights[];
 WakeupOnElapsedFrames w = new WakeupOnElapsedFrames(0);
 // Override Behavior"s initialize method to setup wakeup criteria
 public void initialize() {
   alpha.setStartTime(System.currentTimeMillis());
   // Establish initial wakeup criteria
   wakeupOn(w);
 }
 // Override Behavior"s stimulus method to handle the event
 public void processStimulus(Enumeration criteria) {
   // NOTE: This assumes 3 objects. It should be generalized to
   // "n" objects.
   double val = alpha.value();
   if (val < 0.5) {
     double a = val * 2.0;
     weights[0] = 1.0 - a;
     weights[1] = a;
     weights[2] = 0.0;
   } else {
     double a = (val - 0.5) * 2.0;
     weights[0] = 0.0;
     weights[1] = 1.0f - a;
     weights[2] = a;
   }
   morph.setWeights(weights);
   // Set wakeup criteria for next time
   wakeupOn(w);
 }
 public MorphingBehavior(Alpha a, Morph m) {
   alpha = a;
   morph = m;
   weights = morph.getWeights();
 }

}


      </source>
   
  
 
  



RubiksCube

Stereo Cube

   <source lang="java">

//Copyright 1999 Resplendent Technology Ltd. greg@resplendent.ru import java.applet.Applet; import java.awt.FlowLayout; import java.awt.GraphicsConfiguration; import javax.media.j3d.BoundingSphere; import javax.media.j3d.BranchGroup; import javax.media.j3d.Canvas3D; import javax.media.j3d.PhysicalBody; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import javax.media.j3d.View; import javax.vecmath.Point3d; import com.sun.j3d.utils.applet.MainFrame; import com.sun.j3d.utils.behaviors.keyboard.KeyNavigatorBehavior; import com.sun.j3d.utils.behaviors.mouse.MouseRotate; import com.sun.j3d.utils.behaviors.mouse.MouseTranslate; import com.sun.j3d.utils.geometry.ColorCube; import com.sun.j3d.utils.universe.SimpleUniverse; public class StereoCube extends Applet {

   Canvas3D c1 = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
   Canvas3D c2 = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
   static MainFrame mf;
   private SimpleUniverse u = null;
   private BranchGroup scene = null;
   public void init() {
       setLayout(new FlowLayout());
       GraphicsConfiguration config =
          SimpleUniverse.getPreferredConfiguration();
       
       c1.setSize(180, 180);
       c1.setMonoscopicViewPolicy(View.LEFT_EYE_VIEW);
       add(c1);
       
       c2.setSize(180, 180);
       c2.setMonoscopicViewPolicy(View.RIGHT_EYE_VIEW);
       add(c2);
       // Create a simple scene and attach it to the virtual universe
       scene = createSceneGraph(0);
       u = new SimpleUniverse(c1);
       View view0 = u.getViewer().getView();
       View view = new View();
       PhysicalBody myBod = view0.getPhysicalBody();
       myBod.setLeftEyePosition(new Point3d(-.006,0.0, 0.0)); // default is(-0.033, 0.0, 0.0)
       myBod.setRightEyePosition(new Point3d(+.006,0.0, 0.0));
       view.setPhysicalBody(myBod);
       view.setPhysicalEnvironment(view0.getPhysicalEnvironment());
       view.attachViewPlatform(u.getViewingPlatform().getViewPlatform());
       view.addCanvas3D(c2);
       // This will move the ViewPlatform back a bit so the
       // objects in the scene can be viewed.
       u.getViewingPlatform().setNominalViewingTransform();
       u.addBranchGraph(scene);
   }
   public BranchGroup createSceneGraph(int i) {
       // Create the root of the branch graph
       BranchGroup objRoot = new BranchGroup();
       TransformGroup objTrans = new TransformGroup();
       objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
       Transform3D t = new Transform3D();
     TransformGroup tg = new TransformGroup(t);
     tg.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
     tg.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
     objTrans.addChild(tg);
       tg.addChild(new ColorCube(0.4));
       MouseRotate behavior = new MouseRotate();
     BoundingSphere bounds =
         new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
           
     behavior.setTransformGroup(tg);
     objTrans.addChild(behavior);
       // Create the translate behavior node
     MouseTranslate behavior3 = new MouseTranslate();
     behavior3.setTransformGroup(tg);
     objTrans.addChild(behavior3);
     behavior3.setSchedulingBounds(bounds);
     
     KeyNavigatorBehavior keyNavBeh = new KeyNavigatorBehavior(tg);
   keyNavBeh.setSchedulingBounds(new BoundingSphere(
     new Point3d(),1000.0));
   objTrans.addChild(keyNavBeh);
   
     behavior.setSchedulingBounds(bounds);
       objRoot.addChild(objTrans);
       return objRoot;
   }     
   public StereoCube() {
   }
   public void destroy() {
       u.removeAllLocales();
   }
   public void setSize(int width, int height) {
       System.out.println("setsize " + width +"," +height);
       super.setSize(width, height);
       int minDimension = Math.min(width/2, height);
       c1.setSize((minDimension - 20),(minDimension - 20)); 
       c2.setSize((minDimension - 20),(minDimension - 20)); 
       if (mf != null) {
           mf.appletResize(width, height);
       }
       validate();
   }
   public static void main(String[] args) {
       mf = new MainFrame(new StereoCube(), 400, 200);
   }

}


      </source>
   
  
 
  



This uses the Box utility class to build a simple cube

   <source lang="java">

/* Essential Java 3D Fast Ian Palmer Publisher: Springer-Verlag ISBN: 1-85233-394-4

  • /

import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.media.j3d.Appearance; import javax.media.j3d.BranchGroup; import javax.media.j3d.Canvas3D; import javax.media.j3d.Locale; import javax.media.j3d.Node; import javax.media.j3d.PhysicalBody; import javax.media.j3d.PhysicalEnvironment; import javax.media.j3d.PolygonAttributes; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import javax.media.j3d.View; import javax.media.j3d.ViewPlatform; import javax.media.j3d.VirtualUniverse; import javax.vecmath.AxisAngle4d; import javax.vecmath.Vector3f; import com.sun.j3d.utils.geometry.Box; /**

* This uses the Box utility class to build a simple cube. The cube is then
* displayed in as a wireframe by setting the polygon attributes accordingly.
* 
* @author I.J.Palmer
* @version 1.0
*/

public class SimpleWire extends Frame implements ActionListener {

 protected Canvas3D myCanvas3D = new Canvas3D(null);
 protected Button myButton = new Button("Exit");
 /**
  * This function builds the view branch of the scene graph. It creates a
  * branch group and then creates the necessary view elements to give a
  * useful view of our content.
  * 
  * @param c
  *            Canvas3D that will display the view
  * @return BranchGroup that is the root of the view elements
  */
 protected BranchGroup buildViewBranch(Canvas3D c) {
   BranchGroup viewBranch = new BranchGroup();
   Transform3D viewXfm = new Transform3D();
   viewXfm.set(new Vector3f(0.0f, 0.0f, 5.0f));
   TransformGroup viewXfmGroup = new TransformGroup(viewXfm);
   ViewPlatform myViewPlatform = new ViewPlatform();
   PhysicalBody myBody = new PhysicalBody();
   PhysicalEnvironment myEnvironment = new PhysicalEnvironment();
   viewXfmGroup.addChild(myViewPlatform);
   viewBranch.addChild(viewXfmGroup);
   View myView = new View();
   myView.addCanvas3D(c);
   myView.attachViewPlatform(myViewPlatform);
   myView.setPhysicalBody(myBody);
   myView.setPhysicalEnvironment(myEnvironment);
   return viewBranch;
 }
 /**
  * This builds the content branch of our scene graph. It uses the buildCube
  * function to create the actual shape, adding to to the transform group so
  * that the shape is slightly tilted to reveal its 3D shape.
  * 
  * @param shape
  *            Node that represents the geometry for the content
  * @return BranchGroup that is the root of the content branch
  */
 protected BranchGroup buildContentBranch(Node shape) {
   BranchGroup contentBranch = new BranchGroup();
   Transform3D rotateCube = new Transform3D();
   rotateCube.set(new AxisAngle4d(1.0, 1.0, 0.0, Math.PI / 4.0));
   TransformGroup rotationGroup = new TransformGroup(rotateCube);
   contentBranch.addChild(rotationGroup);
   rotationGroup.addChild(shape);
   return contentBranch;
 }
 /**
  * This constructs a cube using the Box utility class. The attributes are
  * set so that the lines are drawn and not the faces.
  * 
  * @return Node that is the cube
  */
 protected Node buildShape() {
   Appearance app = new Appearance();
   //Create the polygon attributes
   PolygonAttributes polyAttr = new PolygonAttributes();
   //Set them so that the draw mode is polygon line
   polyAttr.setPolygonMode(PolygonAttributes.POLYGON_LINE);
   //Use these in the appearance
   app.setPolygonAttributes(polyAttr);
   return new Box(1.0f, 1.0f, 1.0f, app);
 }
 /**
  * Handles the exit button action to quit the program.
  */
 public void actionPerformed(ActionEvent e) {
   dispose();
   System.exit(0);
 }
 public SimpleWire() {
   VirtualUniverse myUniverse = new VirtualUniverse();
   Locale myLocale = new Locale(myUniverse);
   myLocale.addBranchGraph(buildViewBranch(myCanvas3D));
   myLocale.addBranchGraph(buildContentBranch(buildShape()));
   setTitle("SimpleWire");
   setSize(400, 400);
   setLayout(new BorderLayout());
   add("Center", myCanvas3D);
   add("South", myButton);
   myButton.addActionListener(this);
   setVisible(true);
 }
 public static void main(String[] args) {
   SimpleWire sw = new SimpleWire();
 }

}

      </source>