in Programming

Loading 3D objects in Java

/**
	Example that shows load 3D models in Java
	@author vlarob
*/
public class LoaderObj extends javax.swing.JFrame{

	private javax.media.j3d.Canvas3D canvas3D;
	private javax.media.j3d.BranchGroup bg;
	private javax.media.j3d.TransformGroup tg;
	private com.sun.j3d.utils.universe.SimpleUniverse simpleUniverse;
	/**
		Class constructor: generates the instance of canvas3D and simple universe.
		@param path - Specifies the name and path of 3D object model
	*/
	public LoaderObj(String path){
		super("Ejemplo de carga de objetos 3D");
		setSize(400,400);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		canvas3D=new javax.media.j3d.Canvas3D(com.sun.j3d.utils.universe.SimpleUniverse.getPreferredConfiguration());
		add(canvas3D);
		
		bg=new javax.media.j3d.BranchGroup();
		tg=new javax.media.j3d.TransformGroup();
		tg.setCapability(javax.media.j3d.TransformGroup.ALLOW_TRANSFORM_READ);
		tg.setCapability(javax.media.j3d.TransformGroup.ALLOW_TRANSFORM_WRITE);

		
		javax.media.j3d.BoundingSphere bs=new javax.media.j3d.BoundingSphere();
		com.sun.j3d.utils.behaviors.mouse.MouseRotate mr=new com.sun.j3d.utils.behaviors.mouse.MouseRotate(tg);
		mr.setSchedulingBounds(bs);
		com.sun.j3d.utils.behaviors.mouse.MouseZoom mz=new com.sun.j3d.utils.behaviors.mouse.MouseZoom(tg);
		mz.setSchedulingBounds(bs);
		com.sun.j3d.utils.behaviors.mouse.MouseTranslate mt=new com.sun.j3d.utils.behaviors.mouse.MouseTranslate(tg);
		mt.setSchedulingBounds(bs);

		javax.media.j3d.AmbientLight ambientLight=new javax.media.j3d.AmbientLight();
		ambientLight.setColor(new javax.vecmath.Color3f(1.f,0.f,0.0f));
		ambientLight.setInfluencingBounds(bs);
		tg.addChild(ambientLight);
		
		try{
			com.sun.j3d.loaders.objectfile.ObjectFile objectFile=new com.sun.j3d.loaders.objectfile.ObjectFile(com.sun.j3d.loaders.objectfile.ObjectFile.RESIZE);
			com.sun.j3d.loaders.Scene scene=objectFile.load(ClassLoader.getSystemResource("galleon.obj"));
			tg.addChild(scene.getSceneGroup());
			System.out.println(scene.getNamedObjects());
			System.out.println("Cargado...");
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		javax.media.j3d.TransformGroup tgEscala=new javax.media.j3d.TransformGroup();
		javax.media.j3d.Transform3D t3d=new javax.media.j3d.Transform3D();
// 		t3d.setScale(0.2f);
		tgEscala.setTransform(t3d);
		tgEscala.addChild(tg);

		bg.addChild(tgEscala);
		bg.addChild(mr);
		bg.addChild(mz);
		bg.addChild(mt);
		
		bg.compile();
		simpleUniverse=new com.sun.j3d.utils.universe.SimpleUniverse(canvas3D);
		simpleUniverse.addBranchGraph(bg);
		simpleUniverse.getViewingPlatform().setNominalViewingTransform();
	}
	
	public static void main(String []args){
		new LoaderObj("").setVisible(true);
	}
}

Free 3D models: http://tf3dm.com/3d-models/file/1/obj

Write a Comment

Comment