Example usage for javax.media.j3d Canvas3D Canvas3D

List of usage examples for javax.media.j3d Canvas3D Canvas3D

Introduction

In this page you can find the example usage for javax.media.j3d Canvas3D Canvas3D.

Prototype

public Canvas3D(GraphicsConfiguration graphicsConfiguration) 

Source Link

Document

Constructs and initializes a new Canvas3D object that Java 3D can render into.

Usage

From source file:Human1.java

public void init() {

    // set up a NumFormat object to print out float with only 3 fraction
    // digits/*w ww  .ja va  2  s  .  co  m*/
    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    canvas = new Canvas3D(config);

    add("Center", canvas);

    u = new SimpleUniverse(canvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= offScreenScale;
        dim.height *= offScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);
    }

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();
    u.addBranchGraph(scene);

    view = u.getViewer().getView();

    add("East", guiPanel());
}

From source file:PickTest.java

public void init() {
    setLayout(new BorderLayout());
    Canvas3D c = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
    add("Center", c);

    JPanel guiPanel = new JPanel();
    setupGUI(guiPanel);//from   w  w  w  . j a  va  2s. c om
    add(guiPanel, BorderLayout.EAST);

    // Create a scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph(c);
    u = new SimpleUniverse(c);

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    u.getViewingPlatform().setNominalViewingTransform();
    view = u.getViewer().getView();

    u.addBranchGraph(scene);
}

From source file:GeomInfoApp.java

public GeomInfoApp(String[] args) {
    setLayout(new BorderLayout());
    Canvas3D canvas3D = new Canvas3D(null);
    add("Center", canvas3D);

    BranchGroup scene = createSceneGraph(args.length > 0);

    // 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);/*from w  ww.ja va 2  s .c  om*/
}

From source file:FourByFour.java

/**
 * Initialization//from  w w w . j av a  2 s  .  c  o  m
 */
public void init() {

    // Set the port number.
    port = 4111;

    // Set the graphics window size.
    width = 350;
    height = 350;

    // Set the weighting factors used for scoring.
    level_weight = 1311;
    move_weight = 111;
    time_weight = 1000;

    // Create the "base" color for the AWT components.
    setBackground(new Color(200, 200, 200));

    // Read the instructions file.
    if (appletFlag) {

        // Get the host from which this applet came.
        host = getCodeBase().getHost();

        try {
            inStream = new BufferedInputStream(new URL(getCodeBase(), "instructions.txt").openStream(), 8192);
            text = new byte[5000];
            int character = inStream.read();
            int count = 0;
            while (character != -1) {
                text[count++] = (byte) character;
                character = inStream.read();
            }
            textString = new String(text);
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    } else {

        try {
            inStream = new BufferedInputStream(new FileInputStream("instructions.txt"));
            text = new byte[5000];
            int character = inStream.read();
            int count = 0;
            while (character != -1) {
                text[count++] = (byte) character;
                character = inStream.read();
            }
            textString = new String(text);
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }

    // Read the high-scores file.
    places = new int[20];
    scores = new int[20];
    names = new String[20];
    if (appletFlag) {
        try {
            inStream = new BufferedInputStream(new URL(getCodeBase(), "scores.txt").openStream(), 8192);
            Reader read = new BufferedReader(new InputStreamReader(inStream));
            StreamTokenizer st = new StreamTokenizer(read);
            st.whitespaceChars(32, 44);
            st.eolIsSignificant(false);

            int count = 0;
            int token = st.nextToken();
            boolean scoreFlag = true;
            String string;
            while (count < 20) {
                places[count] = (int) st.nval;
                string = new String("");
                token = st.nextToken();
                while (token == StreamTokenizer.TT_WORD) {
                    string += st.sval;
                    string += " ";
                    token = st.nextToken();
                }
                names[count] = string;
                scores[count] = (int) st.nval;
                token = st.nextToken();
                count++;
            }
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    } else {
        try {
            inStream = new BufferedInputStream(new FileInputStream("scores.txt"));
            Reader read = new BufferedReader(new InputStreamReader(inStream));
            StreamTokenizer st = new StreamTokenizer(read);
            st.whitespaceChars(32, 44);
            st.eolIsSignificant(false);

            int count = 0;
            int token = st.nextToken();
            boolean scoreFlag = true;
            String string;
            while (count < 20) {
                places[count] = (int) st.nval;
                string = new String("");
                token = st.nextToken();
                while (token == StreamTokenizer.TT_WORD) {
                    string += st.sval;
                    string += " ";
                    token = st.nextToken();
                }
                names[count] = string;
                scores[count] = (int) st.nval;
                token = st.nextToken();
                count++;
            }
            inStream.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }

    // The positions object sets up the switch nodes which
    // control the rendering of the player's positions.
    positions = new Positions();

    // Create the game board object which is responsible
    // for keeping track of the moves on the game board
    // and determining what move the computer should make.
    board = new Board(this, positions, width, height);
    positions.setBoard(board);

    // Create a 2D graphics canvas.
    canvas2D = new Canvas2D(board);
    canvas2D.setSize(width, height);
    canvas2D.setLocation(width + 10, 5);
    canvas2D.addMouseListener(canvas2D);
    board.setCanvas(canvas2D);

    // Create the 2D backbuffer
    backbuffer2D = createImage(width, height);
    canvas2D.setBuffer(backbuffer2D);

    // Create a 3D graphics canvas.
    canvas3D = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
    canvas3D.setSize(width, height);
    canvas3D.setLocation(5, 5);

    // Create the scene branchgroup.
    BranchGroup scene3D = createScene3D();

    // Create a universe with the Java3D universe utility.
    universe = new SimpleUniverse(canvas3D);
    universe.addBranchGraph(scene3D);

    // Use parallel projection.
    View view = universe.getViewer().getView();
    view.setProjectionPolicy(View.PARALLEL_PROJECTION);

    // Set the universe Transform3D object.
    TransformGroup tg = universe.getViewingPlatform().getViewPlatformTransform();
    Transform3D transform = new Transform3D();
    transform.set(65.f, new Vector3f(0.0f, 0.0f, 400.0f));
    tg.setTransform(transform);

    // Create the canvas container.
    c_container = new Panel();
    c_container.setSize(720, 360);
    c_container.setLocation(0, 0);
    c_container.setVisible(true);
    c_container.setLayout(null);
    add(c_container);

    // Add the 2D and 3D canvases to the container.
    c_container.add(canvas2D);
    c_container.add(canvas3D);

    // Turn off the layout manager, widgets will be sized
    // and positioned explicitly.
    setLayout(null);

    // Create the button container.
    b_container = new Panel();
    b_container.setSize(720, 70);
    b_container.setLocation(0, 360);
    b_container.setVisible(true);
    b_container.setLayout(null);

    // Create the buttons.
    instruct_button = new Button("Instructions");
    instruct_button.setSize(135, 25);
    instruct_button.setLocation(10, 10);
    instruct_button.setVisible(true);
    instruct_button.addActionListener(this);

    new_button = new Button("New Game");
    new_button.setSize(135, 25);
    new_button.setLocation(150, 10);
    new_button.setVisible(true);
    new_button.addActionListener(this);

    undo_button = new Button("Undo Move");
    undo_button.setSize(135, 25);
    undo_button.setLocation(290, 10);
    undo_button.setVisible(true);
    undo_button.addActionListener(this);

    skill_button = new Button("Skill Level");
    skill_button.setSize(135, 25);
    skill_button.setLocation(430, 10);
    skill_button.setVisible(true);
    skill_button.addActionListener(this);

    high_button = new Button("High Scores");
    high_button.setSize(135, 25);
    high_button.setLocation(570, 10);
    high_button.setVisible(true);
    high_button.addActionListener(this);

    b_container.add(new_button);
    b_container.add(undo_button);
    b_container.add(skill_button);
    b_container.add(high_button);
    b_container.add(instruct_button);

    // Add the button container to the applet.
    add(b_container);

    // Create the "Skill Level" dialog box.
    skill_panel = new Panel();
    skill_panel.setSize(400, 300);
    skill_panel.setLocation(200, 20);
    skill_panel.setLayout(null);

    skill_label = new Label("Pick your skill level:");
    skill_label.setSize(200, 25);
    skill_label.setLocation(25, 20);
    skill_label.setVisible(true);
    skill_panel.add(skill_label);

    group = new CheckboxGroup();
    Checkbox skill_1 = new Checkbox("Babe in the Woods        ", group, false);
    Checkbox skill_2 = new Checkbox("Walk and Chew Gum        ", group, false);
    Checkbox skill_3 = new Checkbox("Jeopardy Contestant      ", group, false);
    Checkbox skill_4 = new Checkbox("Rocket Scientist         ", group, false);
    Checkbox skill_5 = new Checkbox("Be afraid, be very afraid", group, true);
    skill_1.setSize(170, 25);
    skill_1.setLocation(80, 60);
    skill_1.setVisible(true);
    skill_2.setSize(170, 25);
    skill_2.setLocation(80, 100);
    skill_2.setVisible(true);
    skill_3.setSize(170, 25);
    skill_3.setLocation(80, 140);
    skill_3.setVisible(true);
    skill_4.setSize(170, 25);
    skill_4.setLocation(80, 180);
    skill_4.setVisible(true);
    skill_5.setSize(170, 25);
    skill_5.setLocation(80, 220);
    skill_5.setVisible(true);
    skill_return_button = new Button("Return");
    skill_return_button.setSize(120, 25);
    skill_return_button.setLocation(300, 370);
    skill_return_button.setVisible(false);
    skill_return_button.addActionListener(this);
    skill_panel.add(skill_1);
    skill_panel.add(skill_2);
    skill_panel.add(skill_3);
    skill_panel.add(skill_4);
    skill_panel.add(skill_5);
    skill_panel.setVisible(false);
    add(skill_return_button);
    add(skill_panel);

    // Create the "Instructions" panel.
    instruct_return_button = new Button("Return");
    instruct_return_button.setLocation(300, 370);
    instruct_return_button.setSize(120, 25);
    instruct_return_button.setVisible(false);
    instruct_return_button.addActionListener(this);
    instruct_text = new TextArea(textString, 100, 200, TextArea.SCROLLBARS_VERTICAL_ONLY);
    instruct_text.setSize(715, 350);
    instruct_text.setLocation(0, 0);
    instruct_text.setVisible(false);
    add(instruct_text);

    add(instruct_return_button);

    high_panel = new Panel();
    high_panel.setSize(715, 350);
    high_panel.setLocation(0, 0);
    high_panel.setVisible(false);
    high_panel.setLayout(null);

    high_label = new Label("High Scores");
    high_label.setLocation(330, 5);
    high_label.setSize(200, 30);
    high_label.setVisible(true);
    high_panel.add(high_label);

    high_places = new Label[20];
    high_names = new Label[20];
    high_scores = new Label[20];
    for (int i = 0; i < 20; i++) {
        high_places[i] = new Label(Integer.toString(i + 1));
        high_places[i].setSize(20, 30);
        high_places[i].setVisible(true);
        high_names[i] = new Label(names[i]);
        high_names[i].setSize(150, 30);
        high_names[i].setVisible(true);
        high_scores[i] = new Label(Integer.toString(scores[i]));
        high_scores[i].setSize(150, 30);
        high_scores[i].setVisible(true);
        if (i < 10) {
            high_places[i].setLocation(70, i * 30 + 40);
            high_names[i].setLocation(100, i * 30 + 40);
            high_scores[i].setLocation(260, i * 30 + 40);
        } else {
            high_places[i].setLocation(425, (i - 10) * 30 + 40);
            high_names[i].setLocation(455, (i - 10) * 30 + 40);
            high_scores[i].setLocation(615, (i - 10) * 30 + 40);
        }
        high_panel.add(high_places[i]);
        high_panel.add(high_names[i]);
        high_panel.add(high_scores[i]);
    }
    high_return_button = new Button("Return");
    high_return_button.setSize(120, 25);
    high_return_button.setLocation(300, 370);
    high_return_button.setVisible(false);
    high_return_button.addActionListener(this);
    add(high_return_button);
    add(high_panel);

    // Create the "Winner" dialog box
    winner_panel = new Panel();
    winner_panel.setLayout(null);
    winner_panel.setSize(600, 500);
    winner_panel.setLocation(0, 0);
    winner_return_button = new Button("Return");
    winner_return_button.setSize(120, 25);
    winner_return_button.setLocation(300, 360);
    winner_return_button.addActionListener(this);
    winner_panel.add(winner_return_button);
    winner_label = new Label("");
    winner_label.setSize(200, 30);
    winner_label.setLocation(270, 110);
    winner_score_label = new Label("");
    winner_score_label.setSize(200, 30);
    winner_top_label = new Label("You have a score in the top 20.");
    winner_top_label.setSize(200, 25);
    winner_top_label.setLocation(260, 185);
    winner_top_label.setVisible(false);
    winner_name_label = new Label("Enter your name here:");
    winner_name_label.setSize(150, 25);
    winner_name_label.setLocation(260, 210);
    winner_name_label.setVisible(false);
    winner_name = new TextField("");
    winner_name.setSize(200, 30);
    winner_name.setLocation(260, 240);
    winner_name.setVisible(false);
    winner_panel.add(winner_label);
    winner_panel.add(winner_score_label);
    winner_panel.add(winner_top_label);
    winner_panel.add(winner_name_label);
    winner_panel.add(winner_name);
    winner_panel.setVisible(false);
    add(winner_panel);
}

From source file:EnvironmentExplorer.java

public void init() {
    // initialize the code base
    try {// w ww .j  av a  2s.  c  om
        java.net.URL codeBase = getCodeBase();
        codeBaseString = codeBase.toString();
    } catch (Exception e) {
        // probably running as an application, try the application
        // code base
        codeBaseString = "file:./";
    }

    if (colorMode == USE_COLOR) {
        objColor = red;
    } else {
        objColor = white;
    }

    Container contentPane = getContentPane();

    contentPane.setLayout(new BorderLayout());

    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    canvas = new Canvas3D(config);

    u = new SimpleUniverse(canvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= OFF_SCREEN_SCALE;
        dim.height *= OFF_SCREEN_SCALE;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * OFF_SCREEN_SCALE);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * OFF_SCREEN_SCALE);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);

    }
    contentPane.add("Center", canvas);

    // setup the env nodes and their GUI elements
    setupLights();
    setupBackgrounds();
    setupFogs();
    setupSounds();

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // set up sound
    u.getViewer().createAudioDevice();

    // get the view
    view = u.getViewer().getView();

    // Get the viewing platform
    ViewingPlatform viewingPlatform = u.getViewingPlatform();

    // Move the viewing platform back to enclose the -4 -> 4 range
    double viewRadius = 4.0; // want to be able to see circle
    // of viewRadius size around origin
    // get the field of view
    double fov = u.getViewer().getView().getFieldOfView();

    // calc view distance to make circle view in fov
    float viewDistance = (float) (viewRadius / Math.tan(fov / 2.0));
    tmpVector.set(0.0f, 0.0f, viewDistance);// setup offset
    tmpTrans.set(tmpVector); // set trans to translate
    // move the view platform
    viewingPlatform.getViewPlatformTransform().setTransform(tmpTrans);

    // add an orbit behavior to move the viewing platform
    OrbitBehavior orbit = new OrbitBehavior(canvas, OrbitBehavior.STOP_ZOOM);
    orbit.setSchedulingBounds(infiniteBounds);
    viewingPlatform.setViewPlatformBehavior(orbit);

    u.addBranchGraph(scene);

    contentPane.add("East", guiPanel());
}

From source file:ViewProj.java

public void init() {
    setLayout(new BorderLayout());

    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);/*from  ww  w  .jav a 2  s .c  om*/

    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    JPanel canvasPanel = new JPanel();
    GridBagLayout gridbag = new GridBagLayout();
    canvasPanel.setLayout(gridbag);

    canvas = new Canvas3D(config);
    canvas.setSize(400, 400);

    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridx = 0;
    constraints.gridy = 0;
    constraints.gridwidth = 2;
    constraints.gridheight = 2;
    constraints.insets = new Insets(5, 5, 5, 5);
    constraints.fill = GridBagConstraints.BOTH;
    gridbag.setConstraints(canvas, constraints);
    canvasPanel.add(canvas);

    constraints.fill = GridBagConstraints.REMAINDER;
    constraints.gridwidth = 1;
    constraints.gridheight = 1;
    constraints.gridx = 2;
    constraints.gridy = 0;
    urCanvas = new Canvas3D(config);
    urCanvas.setSize(200, 200);
    gridbag.setConstraints(urCanvas, constraints);
    canvasPanel.add(urCanvas);

    constraints.gridx = 2;
    constraints.gridy = 1;
    lrCanvas = new Canvas3D(config);
    lrCanvas.setSize(200, 200);
    gridbag.setConstraints(lrCanvas, constraints);
    canvasPanel.add(lrCanvas);

    add(canvasPanel, BorderLayout.NORTH);

    SimpleUniverse u = new SimpleUniverse(canvas);
    urUniverse = new SimpleUniverse(urCanvas);
    lrUniverse = new SimpleUniverse(lrCanvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= offScreenScale;
        dim.height *= offScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);

        urOffScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        sOn = urCanvas.getScreen3D();
        sOff = urOffScreenCanvas.getScreen3D();
        dim = sOn.getSize();
        dim.width *= urOffScreenScale;
        dim.height *= urOffScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * urOffScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * urOffScreenScale);

        // attach the offscreen canvas to the view
        urUniverse.getViewer().getView().addCanvas3D(urOffScreenCanvas);

        lrOffScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        sOn = lrCanvas.getScreen3D();
        sOff = lrOffScreenCanvas.getScreen3D();
        dim = sOn.getSize();
        dim.width *= lrOffScreenScale;
        dim.height *= lrOffScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * lrOffScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * lrOffScreenScale);

        // attach the offscreen canvas to the view
        lrUniverse.getViewer().getView().addCanvas3D(lrOffScreenCanvas);
    }

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    viewingPlatform = u.getViewingPlatform();
    viewingPlatform.setNominalViewingTransform();

    view = u.getViewer().getView();
    view.setFrontClipPolicy(View.VIRTUAL_EYE);
    view.setBackClipPolicy(View.VIRTUAL_EYE);
    view.setFrontClipDistance(frontClipDist);
    view.setBackClipDistance(backClipDist);

    u.addBranchGraph(scene);

    // init the clipGridPts arrays
    for (int i = 0; i < maxClipGridPts; i++) {
        clipGridPtsVW[i] = new Point3f();
        clipGridPtsProj[i] = new Point3f();
    }

    // init the circlePts arrays
    for (int i = 0; i < numCirclePts; i++) {
        circlePtsVW[i] = new Point3f();
        circlePtsProj[i] = new Point3f();
    }

    // setup the ur canvas
    urScene = createVWorldViewSG();
    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    urUniverse.getViewingPlatform().setNominalViewingTransform();
    View urView = urUniverse.getViewer().getView();
    urView.setProjectionPolicy(View.PARALLEL_PROJECTION);
    urUniverse.addBranchGraph(urScene);
    // set up the background on a separate BG so that it can stay there
    // when we replace the scene SG
    Background urBgWhite = new Background(white);
    urBgWhite.setApplicationBounds(infiniteBounds);
    BranchGroup urBackBG = new BranchGroup();
    urBackBG.addChild(urBgWhite);
    urUniverse.addBranchGraph(urBackBG);

    // setup the lr canvas
    lrScene = createProjViewSG();
    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    lrUniverse.getViewingPlatform().setNominalViewingTransform();
    View lrView = lrUniverse.getViewer().getView();
    lrView.setProjectionPolicy(View.PARALLEL_PROJECTION);
    lrUniverse.addBranchGraph(lrScene);
    // set up the background on a separate BG so that it can stay there
    // when we replace the scene SG
    Background lrBgWhite = new Background(white);
    lrBgWhite.setApplicationBounds(infiniteBounds);
    BranchGroup lrBackBG = new BranchGroup();
    lrBackBG.addChild(lrBgWhite);
    lrUniverse.addBranchGraph(lrBackBG);

    // set up the sliders
    JPanel guiPanel = new JPanel();
    guiPanel.setLayout(new GridLayout(0, 2));
    FloatLabelJSlider dynamicSlider = new FloatLabelJSlider("Dynamic Offset", 0.1f, 0.0f, 2.0f, dynamicOffset);
    dynamicSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            dynamicOffset = e.getValue();
            solidPa.setPolygonOffsetFactor(dynamicOffset);
        }
    });
    guiPanel.add(dynamicSlider);

    LogFloatLabelJSlider staticSlider = new LogFloatLabelJSlider("Static Offset", 0.1f, 10000.0f, staticOffset);
    staticSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            staticOffset = e.getValue();
            solidPa.setPolygonOffset(staticOffset);
        }
    });
    guiPanel.add(staticSlider);

    // These are declared final here so they can be changed by the
    // listener routines below.
    LogFloatLabelJSlider frontClipSlider = new LogFloatLabelJSlider("Front Clip Distance", 0.001f, 10.0f,
            frontClipDist);
    final LogFloatLabelJSlider backClipSlider = new LogFloatLabelJSlider("Back Clip Distance", 1.0f, 10000.0f,
            backClipDist);
    final LogFloatLabelJSlider backClipRatioSlider = new LogFloatLabelJSlider("Back Clip Ratio", 1.0f, 10000.0f,
            backClipRatio);

    frontClipSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            frontClipDist = e.getValue();
            view.setFrontClipDistance(frontClipDist);
            backClipRatio = backClipDist / frontClipDist;
            backClipRatioSlider.setValue(backClipRatio);
            updateViewWindows();
        }
    });
    guiPanel.add(frontClipSlider);

    backClipSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            backClipDist = e.getValue();
            backClipRatio = backClipDist / frontClipDist;
            backClipRatioSlider.setValue(backClipRatio);
            view.setBackClipDistance(backClipDist);
            updateViewWindows();
        }
    });
    guiPanel.add(backClipSlider);

    backClipRatioSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            backClipRatio = e.getValue();
            backClipDist = backClipRatio * frontClipDist;
            backClipSlider.setValue(backClipDist);
            updateViewWindows();
        }
    });
    guiPanel.add(backClipRatioSlider);
    FloatLabelJSlider innerSphereSlider = new FloatLabelJSlider("Inner Sphere Scale", 0.001f, 0.90f, 1.0f,
            innerScale);
    innerSphereSlider.addFloatListener(new FloatListener() {
        public void floatChanged(FloatEvent e) {
            innerScale = e.getValue();
            updateInnerScale();
        }
    });
    guiPanel.add(innerSphereSlider);

    JButton mainSnap = new JButton(snapImageString);
    mainSnap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Point loc = canvas.getLocationOnScreen();
            offScreenCanvas.setOffScreenLocation(loc);
            Dimension dim = canvas.getSize();
            dim.width *= offScreenScale;
            dim.height *= offScreenScale;
            nf.setMinimumIntegerDigits(3);
            offScreenCanvas.snapImageFile(outFileBase + nf.format(outFileSeq++), dim.width, dim.height);
            nf.setMinimumIntegerDigits(0);
        }
    });
    guiPanel.add(mainSnap);

    JButton urSnap = new JButton(urSnapImageString);
    urSnap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Snap UR");
            Point loc = urCanvas.getLocationOnScreen();
            urOffScreenCanvas.setOffScreenLocation(loc);
            Dimension dim = urCanvas.getSize();
            dim.width *= urOffScreenScale;
            dim.height *= urOffScreenScale;
            nf.setMinimumIntegerDigits(3);
            urOffScreenCanvas.snapImageFile(urOutFileBase + nf.format(urOutFileSeq++), dim.width, dim.height);
            nf.setMinimumIntegerDigits(0);
        }
    });
    guiPanel.add(urSnap);

    JButton lrSnap = new JButton(lrSnapImageString);
    lrSnap.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Snap LR");
            Point loc = lrCanvas.getLocationOnScreen();
            lrOffScreenCanvas.setOffScreenLocation(loc);
            Dimension dim = lrCanvas.getSize();
            dim.width *= lrOffScreenScale;
            dim.height *= lrOffScreenScale;
            nf.setMinimumIntegerDigits(3);
            lrOffScreenCanvas.snapImageFile(lrOutFileBase + nf.format(lrOutFileSeq++), dim.width, dim.height);
            nf.setMinimumIntegerDigits(0);
        }
    });
    guiPanel.add(lrSnap);
    add(guiPanel, BorderLayout.SOUTH);
}

From source file:GearTest.java

public void init() {
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    Canvas3D c = new Canvas3D(config);
    add("Center", c);

    // Create the gearbox and attach it to the virtual universe
    BranchGroup scene = createGearBox(toothCount);
    u = new SimpleUniverse(c);

    // add mouse behaviors to the ViewingPlatform
    ViewingPlatform viewingPlatform = u.getViewingPlatform();

    // This will move the ViewPlatform back a bit so the
    // objects in the scene can be viewed.
    viewingPlatform.setNominalViewingTransform();

    // add orbit behavior to the ViewingPlatform
    OrbitBehavior orbit = new OrbitBehavior(c, OrbitBehavior.REVERSE_ALL);
    BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    orbit.setSchedulingBounds(bounds);//ww  w .j a  va  2s. c  o  m
    viewingPlatform.setViewPlatformBehavior(orbit);

    u.addBranchGraph(scene);
}

From source file:AppearanceExplorer.java

public void init() {

    // initialize the code base
    try {/*from ww w. j  av  a 2s . c o  m*/
        java.net.URL codeBase = getCodeBase();
        codeBaseString = codeBase.toString();
    } catch (Exception e) {
        // probably running as an application, try the application
        // code base
        codeBaseString = "file:./";
    }

    // set up a NumFormat object to print out float with only 3 fraction
    // digits
    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    canvas = new Canvas3D(config);
    canvas.setSize(600, 600);

    u = new SimpleUniverse(canvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= offScreenScale;
        dim.height *= offScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);
    }
    contentPane.add("Center", canvas);

    BackgroundTool bgTool = new BackgroundTool(codeBaseString);
    bgSwitch = bgTool.getSwitch();
    bgChooser = bgTool.getChooser();

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // set up sound
    u.getViewer().createAudioDevice();

    // get the view
    view = u.getViewer().getView();

    // Get the viewing platform
    ViewingPlatform viewingPlatform = u.getViewingPlatform();

    // Move the viewing platform back to enclose the -2 -> 2 range
    double viewRadius = 2.0; // want to be able to see circle
    // of viewRadius size around origin
    // get the field of view
    double fov = u.getViewer().getView().getFieldOfView();

    // calc view distance to make circle view in fov
    float viewDistance = (float) (viewRadius / Math.tan(fov / 2.0));
    tmpVector.set(0.0f, 0.0f, viewDistance);// setup offset
    tmpTrans.set(tmpVector); // set trans to translate
    // move the view platform
    viewingPlatform.getViewPlatformTransform().setTransform(tmpTrans);

    // add an orbit behavior to move the viewing platform
    OrbitBehavior orbit = new OrbitBehavior(canvas,
            OrbitBehavior.PROPORTIONAL_ZOOM | OrbitBehavior.REVERSE_ROTATE | OrbitBehavior.REVERSE_TRANSLATE);
    orbit.setZoomFactor(0.25);
    BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    orbit.setSchedulingBounds(bounds);
    viewingPlatform.setViewPlatformBehavior(orbit);

    u.addBranchGraph(scene);

    contentPane.add("East", guiPanel());
}

From source file:pl.edu.icm.visnow.geometries.viewer3d.Display3DPanel.java

/**
 * Creates new form Display3DPanel//from w w w .j  a va 2 s. c o m
 */
public Display3DPanel() {
    initComponents();
    effectiveHeight = getHeight();
    effectiveWidth = getWidth();
    logger.debug("creating Display3DPanel");
    this.setMinimumSize(new Dimension(200, 200));
    this.setPreferredSize(new Dimension(800, 600));
    GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
    template.setStereo(GraphicsConfigTemplate3D.PREFERRED);

    // Get the GraphicsConfiguration that best fits our needs.
    logger.debug("getting config");
    GraphicsConfiguration gcfg = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getBestConfiguration(template);
    logger.debug("creating canvas");
    canvas = new Canvas3D(gcfg) {
        @Override
        public void postRender() {
            vGraphics = super.getGraphics2D();
            vGraphics.setFont(new Font("sans-serif", Font.PLAIN, 10));
            vGraphics.setColor(Color.YELLOW);
            locToWin.update();
            fireProjectionChanged(new ProjectionEvent(this, locToWin));
            draw2D(vGraphics, locToWin, effectiveWidth, effectiveHeight);
            vGraphics.flush(false);
        }

        @Override
        public void postSwap() {
            if (postRenderSilent || waitForExternalTrigger) {
                return;
            }
            if (!(storingJPEG || storingPNG || storingFrames)) {
                fireFrameRendered();
            }
            if (storingFrames) {
                if (storingJPEG) {
                    writeImage(new File(controlsPanel.getMovieCreationPanel().getCurrentFrameFileName()));
                } else {
                    writeYUV(controlsPanel.getMovieCreationPanel().getGenericFrameFileName());
                }
            }
        }
    };
    canvas.setStereoEnable(false);
    add("Center", canvas);

    pickObject = new PickObject(canvas, objScene, rootObject.getGeometryObj(), objRotate);

    canvas.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent evt) {
            if (evt.isShiftDown()) {
                //              if (e.isShiftDown())
                //                 System.out.println(""+e.getX() + " " + e.getY());
            }
            if (evt.getButton() == MouseEvent.BUTTON1) {
                if (evt.getClickCount() > 1) {
                    reset();
                } else if (pickObject.consumeEmulated3DPick(evt.getX(), evt.getY())) {
                    /* Nothing must be done - everything was done in consumeEmulated3DPick() */
                } else {
                    pickObject.consume2DSelectModule(evt.getX(), evt.getY());
                }
                rootObject.firePickChanged(evt, locToWin);
            }
            if (evt.getButton() == MouseEvent.BUTTON3) {
                if (getControlsFrame() != null) {
                    getControlsFrame().setBounds(evt.getXOnScreen() - 130, evt.getYOnScreen(), 240, 500);
                    getControlsFrame().setVisible(true);
                } else if (getTransientControlsFrame() != null) {
                    getTransientControlsFrame().setBounds(evt.getXOnScreen() - 130, evt.getYOnScreen(), 240,
                            500);
                    getTransientControlsFrame().setVisible(true);
                } else if (application != null) {
                    application.getFrames().getGuiPanel().selectModule(name);
                }
            }
            if (evt.getButton() == MouseEvent.BUTTON2) {
                reset();
            }
        }

        @Override
        public void mouseEntered(java.awt.event.MouseEvent evt) {
            mouseOn = true;
            mouseObserverThread = new Thread(new MouseObserver());
            mouseObserverThread.start();
        }

        @Override
        public void mouseExited(java.awt.event.MouseEvent evt) {
            mouseObserverThread = null;
            mouseOn = false;
        }
    });

    canvas.addMouseMotionListener(new java.awt.event.MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent e) {
            //              if (e.isShiftDown())
            //                 System.out.println(""+e.getX() + " " + e.getY());
        }

        @Override
        public void mouseMoved(MouseEvent e) {
        }
    });

    canvas.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
        @Override
        public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
            rescaleFromMouseWheel(evt);
        }
    });

    canvas.addKeyListener(new java.awt.event.KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent evt) {
            formKeyTyped(evt);
        }

        @Override
        public void keyPressed(KeyEvent evt) {
            formKeyPressed(evt);
        }

        @Override
        public void keyReleased(KeyEvent evt) {
            formKeyReleased(evt);
        }
    });

    ToolTipManager.sharedInstance().setLightWeightPopupEnabled(true);
    universe = new SimpleUniverse(canvas);
    view = canvas.getView();
    view.setProjectionPolicy(View.PERSPECTIVE_PROJECTION);
    view.setTransparencySortingPolicy(View.TRANSPARENCY_SORT_GEOMETRY);

    objScene.addChild(rootObject.getGeometryObj());
    rootObject.setRenderingWindow(this);
    rootObject.getGeometryObj().setUserData(null);

    bg.setCapability(Background.ALLOW_COLOR_WRITE);
    bg.setCapability(Background.ALLOW_COLOR_READ);
    bg.setCapability(Background.ALLOW_IMAGE_WRITE);
    bg.setCapability(Background.ALLOW_IMAGE_READ);
    bg.setCapability(Background.ALLOW_IMAGE_SCALE_MODE_READ);
    bg.setCapability(Background.ALLOW_IMAGE_SCALE_MODE_WRITE);
    bg.setImageScaleMode(Background.SCALE_FIT_ALL);
    bg.setApplicationBounds(bounds);

    myFog.setCapability(LinearFog.ALLOW_DISTANCE_WRITE);
    myFog.setCapability(LinearFog.ALLOW_COLOR_WRITE);
    myFog.setInfluencingBounds(bounds);
    myFog.setFrontDistance(1.);
    myFog.setBackDistance(4.);
    myFogGroup.addChild(myFog);

    mouseRotate.setTransformGroup(objRotate);
    mouseRotate.setSchedulingBounds(bounds);
    mouseRotate.setFactor(mouseRotateSensitivity);

    mouseTranslate.setTransformGroup(objRotate);
    mouseTranslate.setSchedulingBounds(bounds);
    mouseTranslate.setFactor(mouseTranslateSensitivity);

    mouseZoom.setTransformGroup(objRotate);
    mouseZoom.setSchedulingBounds(bounds);

    windowRootObject.addChild(mouseRotate);
    windowRootObject.addChild(mouseTranslate);
    windowRootObject.addChild(mouseZoom);

    objTranslate.addChild(objScene);
    objScale.addChild(objTranslate);
    objRotate.addChild(bg);
    objRotate.addChild(objScale);
    windowRootObject.addChild(objRotate);

    ambientLight = new EditableAmbientLight(new Color3f(.25f, .25f, .25f), bounds, "ambient light", true);
    windowRootObject.addChild(ambientLight.getLight());

    directionalLights.add(new EditableDirectionalLight(new Color3f(0.4f, 0.4f, 0.4f),
            new Vector3f(.1f, .08f, -.5f), bounds, "light 1", true, true));
    directionalLights.add(new EditableDirectionalLight(new Color3f(0.2f, 0.15f, 0.1f),
            new Vector3f(-1.f, -0.4f, -.5f), bounds, "light 2", true, false));
    directionalLights.add(new EditableDirectionalLight(new Color3f(0.1f, 0.1f, 0.15f),
            new Vector3f(0.f, 0.6f, -1.f), bounds, "light 3", true, false));
    directionalLights.add(new EditableDirectionalLight(new Color3f(0.1f, 0.1f, 0.15f),
            new Vector3f(0.f, -0.6f, -1.f), bounds, "light 3", false, false));
    for (int i = 0; i < directionalLights.size(); i++) {
        TransformGroup lightTransform = new TransformGroup();
        lightTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        lightTransform.setName("light" + i + "Transform");
        directionalLightTransforms.add(lightTransform);
        OpenBranchGroup lightGroup = new OpenBranchGroup();
        EditableDirectionalLight light = directionalLights.get(i);
        lightGroup.addChild(light.getLight());
        lightGroup.addChild(light.getBackLight());
        lightTransform.addChild(lightGroup);
        windowRootObject.addChild(lightTransform);
    }
    modelClip.setCapability(ModelClip.ALLOW_ENABLE_READ);
    modelClip.setCapability(ModelClip.ALLOW_ENABLE_WRITE);
    modelClip.setCapability(ModelClip.ALLOW_PLANE_READ);
    modelClip.setCapability(ModelClip.ALLOW_PLANE_WRITE);
    modelClip.setInfluencingBounds(bounds);
    objScene.addChild(modelClip);

    pointLights
            .add(new EditablePointLight(new Color3f(0.4f, 0.4f, 0.4f), bounds, null, null, "light 1", false));
    pointLights
            .add(new EditablePointLight(new Color3f(0.4f, 0.4f, 0.4f), bounds, null, null, "light 1", false));
    pointLights
            .add(new EditablePointLight(new Color3f(0.4f, 0.4f, 0.4f), bounds, null, null, "light 1", false));
    for (int i = 0; i < pointLights.size(); i++) {
        TransformGroup lightTransform = new TransformGroup();
        lightTransform.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
        lightTransform.setName("light" + i + "Transform");
        pointLightTransforms.add(lightTransform);
        OpenBranchGroup lightGroup = new OpenBranchGroup();
        EditablePointLight light = pointLights.get(i);
        lightGroup.addChild(light.getLight());
        lightTransform.addChild(lightGroup);
        windowRootObject.addChild(lightTransform);
    }
    alternateTransformObj.addChild(alternateRootObj);
    alternateTransormBranch.addChild(alternateTransformObj);
    windowRootObject.addChild(alternateTransormBranch);

    universe.getViewingPlatform().setNominalViewingTransform();
    universe.addBranchGraph(windowRootObject);

    view.getPhysicalBody().getLeftEyePosition(defaultLeftEye);
    view.getPhysicalBody().getRightEyePosition(defaultRightEye);
    controlsFrame = new Display3DControlsFrame(this);
    controlsPanel = controlsFrame.getControlPanel();
    universe.getViewingPlatform().getViewPlatformTransform().getTransform(initialCameraTransform);

    objReper.addChild(reper.getGeometryObj());
    positionedReper.addChild(objReper);
    positionedReper.setTransform(
            new Transform3D(new float[] { .15f, 0, 0, -.8f, 0, .15f, 0, .76f, 0, 0, .15f, 0, 0, 0, 0, 1 }));
    reperGroup.addChild(positionedReper);
    OpenBranchGroup reperLightGroup = new OpenBranchGroup();
    reperLightGroup.addChild(new AmbientLight(new Color3f(.6f, .6f, .6f)));
    reperLightGroup.addChild(new EditableDirectionalLight(new Color3f(0.4f, 0.4f, 0.4f),
            new Vector3f(.1f, .08f, -1f), bounds, "light 1", true, true).getLight());
    reperGroup.addChild(reperLightGroup);
    universe.addBranchGraph(reperGroup);
    locToWin = new LocalToWindow(rootObject.getGeometryObj(), canvas);

    /**
     * The line below binds reper with scene rotation when using any method that calls
     * objRotate.setTransform(), so: keyboard (explicitly calling), mouse (Java3D is calling
     * setTransform) and some custom ways (e.g. in haptic pointer)
     */
    objRotate.addTransformListener(objReper);
    //        mouseRotate.setupCallback(objReper); // it is not needed, because Java3D calls objRotate.setTranform which fires callback to the reper
}