import java.io.*; // IOException

import java.awt.*;
import javax.swing.*;

import javax.media.j3d.*;
import javax.vecmath.*;

import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.behaviors.vp.OrbitBehavior;

class Panel3D extends JPanel {
    private SimpleUniverse mUniverse;
    private Canvas3D mCanvas;
    private BranchGroup mBranchGroup;
    private Background mBackground;

    public Panel3D() {
	// Canvas3DをJFrameに貼り付ける
	GraphicsConfiguration config
	    = SimpleUniverse.getPreferredConfiguration();
	mCanvas = new Canvas3D(config);
	setLayout(new BorderLayout());
	add(mCanvas);

	// SimpleUniverseの作成と視点の設定
	mUniverse = new SimpleUniverse(mCanvas);
	mUniverse.getViewingPlatform().setNominalViewingTransform();

	BoundingSphere bounds = new BoundingSphere(new Point3d(0, 0, 0),
		Double.POSITIVE_INFINITY);

	// マウスで視点を移動できるようにビヘイビアを設定
	OrbitBehavior orbit = new OrbitBehavior(mCanvas,
						OrbitBehavior.REVERSE_ALL);
	orbit.setSchedulingBounds(bounds);
	mUniverse.getViewingPlatform().setViewPlatformBehavior(orbit);

	// 表示範囲を設定
	mUniverse.getViewer().getView().setFrontClipPolicy(View.VIRTUAL_EYE);
	mUniverse.getViewer().getView().setFrontClipDistance(0.01);
	mUniverse.getViewer().getView().setBackClipPolicy(View.VIRTUAL_EYE);
	mUniverse.getViewer().getView().setBackClipDistance(100.0);

	// 背景
	mBackground = new Background();
	mBackground.setCapability(Background.ALLOW_COLOR_WRITE);
	mBackground.setApplicationBounds(bounds);
	BranchGroup bg = new BranchGroup();
	bg.addChild(mBackground);
	mUniverse.addBranchGraph(bg);
    }

    public void setSceneGraph(Node node) throws IOException {
        Transform3D tf1 = new Transform3D();
	tf1.setScale(0.005); // 1/200
        TransformGroup tg1 = new TransformGroup(tf1);
        tg1.addChild(node);

        mBranchGroup = new BranchGroup();
	mBranchGroup.setCapability(BranchGroup.ALLOW_DETACH);
        mBranchGroup.addChild(tg1);
	mBranchGroup.compile();
	mUniverse.addBranchGraph(mBranchGroup);
    }

    public void clearSceneGraph() {
	if(mBranchGroup != null) {
	    mUniverse.getLocale().removeBranchGraph(mBranchGroup);
	    mBranchGroup = null;
	}
    }

    public void resetCameraPos() {
	mUniverse.getViewingPlatform().setNominalViewingTransform();
    }

    public void setBackgroundColor(float r, float g, float b) {
	mBackground.setColor(r, g, b);
    }
}
