Creates a scene which plots a custom Alpha function : Alpha « 3D « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » 3D » AlphaScreenshots 
Creates a scene which plots a custom Alpha function
Creates a scene which plots a custom Alpha function


/**********************************************************
 Copyright (C) 2001   Daniel Selman

 First distributed with the book "Java 3D Programming"
 by Daniel Selman and published by Manning Publications.
 http://manning.com/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.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfigTemplate;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Vector;

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.PositionInterpolator;
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;

/**
 * Creates a scene which plots a custom Alpha function (loaded from a file). In
 * addition the Alpha is applied to a rendered object in a scene. Note: this
 * example does not currently run as an Applet.
 */
public class CustomAlphaTest extends Java3dApplet implements ActionListener,
    FileAlphaListener {
  private static int m_kWidth = 600;

  private static int m_kHeight = 600;

  final int m_knLoopCount = 0;

  final long m_kTimeStep = 200;

  private FileAlpha m_Alpha = null;

  private Vector m_EditFieldVector = null;

  private BufferedImage m_Image = null;

  private long m_CurrentTime = 0;

  private float m_CurrentValue = 0;

  // offsets and drawing information
  private int m_nMaxHeight = 0;

  private int m_nMaxWidth = 0;

  private int m_nInsetX = 0;

  private int m_nInsetY = 0;

  private int m_nGraphMaxWidth = 0;

  private int m_nGraphMaxHeight = 0;

  private int m_nGraphInsetX = 0;

  private int m_nGraphInsetY = 0;

  private double m_ScaleX = 0;

  public CustomAlphaTest() {
    try {
      // HACK:
      // if we are running as an Applet
      // the getWorkingDirectory() call will throw an NPE
      // as we cannot call getCodeBase until "start" has been called
      // (below).
      m_Alpha = new FileAlpha(
          new URL(getWorkingDirectory()"values.xls"));
      m_Image = new BufferedImage(m_kWidth, m_kHeight,
          BufferedImage.TYPE_INT_RGB);

      buildUi();
      initJava3d();
    catch (Exception e) {
    }
  }

  // we duplicate this code here for Applet support
  public void start() {
    if (m_Alpha != null)
      return;

    try {
      m_Alpha = new FileAlpha(
          new URL(getWorkingDirectory()"values.xls"));
      m_Image = new BufferedImage(m_kWidth, m_kHeight,
          BufferedImage.TYPE_INT_RGB);

      buildUi();
      initJava3d();
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected void addCanvas3D(Canvas3D c3d) {
    Frame frame = new Frame("Custom Alpha Test");

    Panel aPanel = new Panel();
    aPanel.setLayout(new BorderLayout());
    aPanel.add(c3d, BorderLayout.CENTER);

    frame.add(aPanel);

    frame.pack();
    frame.setSize(new Dimension(320320));
    frame.validate();
    frame.setVisible(true);

    doLayout();
  }

  protected void buildUi() {
    m_EditFieldVector = new Vector(1);

    addField("Loop Count", m_knLoopCount);

    addButton("Update");

    updateUi();
    drawGraph();
    repaint();
  }

  protected BranchGroup createSceneBranchGroup() {
    BranchGroup objRoot = super.createSceneBranchGroup();

    TransformGroup objTrans = new TransformGroup();
    objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
    objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);

    ColorCube cube = new ColorCube(2);
    objTrans.addChild(cube);

    FileAlpha fileAlpha = null;

    try {
      fileAlpha = new FileAlpha(new URL(getWorkingDirectory(),
          "values.xls")this);
    catch (Exception e) {
      e.toString();
    }

    PositionInterpolator posInterpolator = new PositionInterpolator(
        fileAlpha, objTrans, new Transform3D(), -66);
    posInterpolator.setSchedulingBounds(getApplicationBounds());

    objTrans.addChild(posInterpolator);
    objRoot.addChild(objTrans);

    return objRoot;
  }

  // handle event from the GUI components we created
  public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("Update"!= false) {
      updateAlpha();
      updateUi();

      drawGraph();
      repaint();
    }
  }

  protected void updateAlpha() {
    if (m_Alpha != null)
      m_Alpha.setLoopCount(Integer.parseInt(getField(m_knLoopCount)
          .getText()));
  }

  protected void updateUi() {
    if (m_Alpha != null)
      getField(m_knLoopCount).setText(
          String.valueOf(m_Alpha.getLoopCount()));
  }

  long getMaxTime() {
    return m_Alpha.getStopTime();
  }

  protected void drawGraph() {
    if (m_Alpha != null) {
      Graphics g = m_Image.getGraphics();

      g.setColor(Color.white);
      g.fillRect(00, m_kWidth, m_kHeight);
      g.setColor(Color.black);

      m_Alpha.setStartTime(0);
      long lMaxTime = getMaxTime();

      computeDrawScale(lMaxTime);

      drawAxes(g, lMaxTime);
      drawPhases(g, lMaxTime);
      drawAlpha(g, lMaxTime);
    }
  }

  protected TextField getField(final int nIndex) {
    return (TextFieldm_EditFieldVector.get(nIndex);
  }

  protected void addButton(final String szText) {
    Button button = new Button(szText);
    button.addActionListener(this);
    add(button);
  }

  protected void addField(final String szText, final int nIndex) {
    Label label = new Label(szText);
    TextField textField = new TextField(4);

    m_EditFieldVector.add(nIndex, (ObjecttextField);

    add(label);
    add(textField);
  }

  protected void computeDrawScale(long lMaxTime) {
    int nWidth = getWidth();
    int nHeight = getHeight();

    if (nWidth > m_kWidth)
      nWidth = m_kWidth;

    if (nHeight > m_kHeight)
      nHeight = m_kHeight;

    m_nMaxHeight = (int) (nHeight * 0.7);
    m_nMaxWidth = (int) (nWidth * 0.9);

    m_nInsetX = (nWidth - m_nMaxWidth2;
    m_nInsetY = (int) ((nHeight - m_nMaxHeight1.1);

    m_nGraphMaxWidth = (int) (m_nMaxWidth * 0.80);
    m_nGraphMaxHeight = (int) (m_nMaxHeight * 0.80);

    m_nGraphInsetX = (m_nMaxWidth - m_nGraphMaxWidth2;
    m_nGraphInsetY = (m_nMaxHeight - m_nGraphMaxHeight2;

    m_ScaleX = ((doublem_nGraphMaxWidth((doublelMaxTime);
  }

  protected void drawAreaRect(Graphics g, int x, int y, int width, int height) {
    g.drawRect(x, y, width, height);
  }

  protected void drawAreaString(Graphics g, int nLen, String szText,
      double x, double y) {
    if (nLen > && szText.length() > nLen)
      szText = szText.substring(0, nLen);

    g.drawString(szText, (intx, (int) (m_nMaxHeight - y));
  }

  protected void drawGraphString(Graphics g, int nLen, String szText,
      double x, double y) {
    if (nLen > && szText.length() > nLen)
      szText = szText.substring(0, nLen);

    g.drawString(szText, (int) (m_nGraphInsetX + x)(int) (m_nGraphInsetY
        + m_nGraphMaxHeight - y));
  }

  protected void drawGraphLine(Graphics g, double x1, double y1, double x2,
      double y2) {
    g.drawLine((int) (m_nGraphInsetX + x1)(int) (m_nGraphInsetY
        + m_nGraphMaxHeight - y1)(int) (m_nGraphInsetX + x2),
        (int) (m_nGraphInsetY + m_nGraphMaxHeight - y2));
  }

  protected void drawGraphFillCircle(Graphics g, double x1, double y1,
      double radius) {
    g.fillOval((int) (m_nGraphInsetX + x1 - radius)(int) (m_nGraphInsetY
        + m_nGraphMaxHeight - y1 - radius)(int) (radius * 2),
        (int) (radius * 2));
  }

  protected void drawAxes(Graphics g, long lMaxTime) {
    // draw the frame
    drawAreaRect(g, 00, m_nMaxWidth, m_nMaxHeight);

    drawGraphString(g, -1"Alpha vs. Time (secs)", m_nGraphMaxWidth / 2,
        m_nGraphMaxHeight + 20);

    // draw the X axis
    drawGraphLine(g, 00, m_nGraphMaxWidth, 0);

    // draw the Y axis
    drawGraphLine(g, 000, m_nGraphMaxHeight);

    // draw the horizontal Y axis lines
    for (double yAxisTick = 0; yAxisTick <= 1.0; yAxisTick += 0.2) {
      double yTick = yAxisTick * m_nGraphMaxHeight;

      g.setColor(Color.gray);
      drawGraphLine(g, 0, yTick, m_nGraphMaxWidth, yTick);
      g.setColor(Color.black);

      drawGraphString(g, 3"" + yAxisTick, -20, yTick);
    }
  }

  protected void drawPhases(Graphics g, long lMaxTime) {
    double curTime = 0;

    g.setColor(Color.darkGray);

    int nLoop = 1;

    if (m_Alpha.getLoopCount() 0)
      nLoop = m_Alpha.getLoopCount();

    for (int n = 0; n < nLoop; n++) {
      for (int nValue = 0; nValue < m_Alpha.getNumValues(); nValue++) {
        curTime = n * m_Alpha.getMaxTime()
            + m_Alpha.getTimeForValue(nValue);

        g.setColor(Color.black);
        drawGraphString(g, -1"" (curTime / 1000), curTime
            * m_ScaleX, -20);
        g.setColor(Color.darkGray);

        drawGraphLine(g, curTime * m_ScaleX, 0, curTime * m_ScaleX,
            m_nGraphMaxHeight);
      }
    }

    g.setColor(Color.black);
  }

  protected void drawAlpha(Graphics g, long lMaxTime) {
    g.setColor(Color.blue);

    float value = 0;

    double x1 = 0;
    double y1 = 0;
    double x2 = 0;
    double y2 = 0;

    for (long lTime = 0; lTime <= lMaxTime; lTime += m_kTimeStep) {
      value = m_Alpha.value(lTime);

      x2 = lTime * m_ScaleX;
      y2 = value * m_nGraphMaxHeight;

      drawGraphLine(g, x1, y1, x2, y2);

      x1 = x2;
      y1 = y2;
    }

    g.setColor(Color.black);
  }

  protected void drawCurrentPosition(Graphics g) {
    drawGraphFillCircle(g, m_nInsetX + m_CurrentTime * m_ScaleX,
        m_CurrentValue * m_nGraphMaxHeight - m_nInsetY, 3);
  }

  public void onFileAlphaGetValue(long ltime, float value) {
    m_CurrentTime = ltime % m_Alpha.getStopTime();
    m_CurrentValue = value;

    int repaintX = (int) (m_nGraphInsetX + m_nInsetX + m_CurrentTime
        * m_ScaleX);
    int repaintY = (int) (m_nGraphInsetY + m_nGraphMaxHeight - (m_CurrentValue
        * m_nGraphMaxHeight - m_nInsetY));

    Graphics g = getGraphics();

    if (g != null) {
      repaint(repaintX - 5, repaintY - 51010);
      drawCurrentPosition(g);
    }
  }

  public void paint(Graphics g) {
    super.paint(g);

    if (m_Alpha != null) {
      drawGraph();
      g.drawImage(m_Image, m_nInsetX, m_nInsetY, this);
    }
  }

  public static void main(String[] args) {
    CustomAlphaTest alphaTest = new CustomAlphaTest();
    new MainFrame(alphaTest, m_kWidth, m_kHeight);
  }
}

//this class defines an Alpha class that reads time/alpha
//value pairs from a file and linearly interpolates between
//them. It illustrates creating your own Alpha class for
//interpolation.

class FileAlpha extends Alpha {
  // store a Vector of AlphaPairs that define
  // the Alpha value for each time
  protected Vector m_AlphaVector = null;

  // we override tracking of start and stop time
  protected long m_StartTime = 0;

  protected long m_StopTime = 0;

  // we override tracking of loop count
  protected int m_nLoopCount = -1;

  protected FileAlphaListener m_Listener = null;

  public FileAlpha(URL url) {
    this(url, null);
  }

  public FileAlpha(URL url, FileAlphaListener listener) {
    m_Listener = listener;

    // create the vector used to store the AlphaPairs
    m_AlphaVector = new Vector();

    // read the AlphaPairs from the text file
    readAlphaValues(url);

    System.out.println("Read " + getNumValues() " Alpha pairs.");

    // initialize the start/stop times
    m_StartTime = System.currentTimeMillis();
    m_StopTime = m_StartTime + getMaxTime();
  }

  // this method is overriden to update the stop time
  public void setStartTime(long l) {
    m_StartTime = l;

    if (m_nLoopCount > 0)
      m_StopTime = m_StartTime + m_nLoopCount * getMaxTime();
    else
      m_StopTime = m_StartTime + getMaxTime();
  }

  // overriden to return our member variable
  public long getStartTime() {
    return m_StartTime;
  }

  public long getStopTime() {
    return m_StopTime;
  }

  // overriden to update the stop time
  public void setLoopCount(int i) {
    m_nLoopCount = i;

    if (m_nLoopCount > 0)
      m_StopTime = m_StartTime + i * getMaxTime();
    else
      m_StopTime = m_StartTime + getMaxTime();
  }

  // overriden to return our member variable
  public int getLoopCount() {
    return m_nLoopCount;
  }

  // overriden to use our member variables
  public boolean finished() {
    if (m_nLoopCount == -1)
      return false;

    return (System.currentTimeMillis() - m_StartTime > m_StopTime);
  }

  // core method override
  // returns the Alpha value for a given time
  public float value(long time) {
    if (time >= m_StartTime)
      return valueFromStart(time - m_StartTime);

    return 0;
  }

  // helper method to retrieve the AlphaPair
  // to the left and right of the time and
  // linearly interpolate between them.
  //
  // Note: this method could be optimized!
  protected float valueFromStart(long time) {
    long modTime = time;
    float value = 0;

    if (time > getMaxTime() && getMaxTime() 0)
      modTime = time % getMaxTime();

    AlphaPair leftPair = getLeftPairFromTime(modTime);
    AlphaPair rightPair = getRightPairFromTime(modTime);

    if (leftPair != null && rightPair != null) {
      float deltaAlpha = rightPair.getAlpha() - leftPair.getAlpha();
      long deltaTime = rightPair.getTime() - leftPair.getTime();
      float slope = 0;

      if (deltaTime != 0)
        slope = deltaAlpha / deltaTime;

      long subTime = modTime - leftPair.getTime();
      value = leftPair.getAlpha() + subTime * slope;

      if (m_Listener != null)
        m_Listener.onFileAlphaGetValue(time, value);
    }

    return value;
  }

  // returns the AlphaPair for a given index
  protected AlphaPair getAlphaPairForIndex(int nIndex) {
    if (nIndex < || nIndex >= m_AlphaVector.size())
      return null;

    return (AlphaPairm_AlphaVector.get(nIndex);
  }

  // returns an AlphaPair immediately to the
  // left of the given time
  protected AlphaPair getLeftPairFromTime(long time) {
    AlphaPair alphaPair = null;

    for (int nIndex = 0; nIndex < getNumValues(); nIndex++) {
      alphaPair = getAlphaPairForIndex(nIndex);

      if (alphaPair != null) {
        if (alphaPair.getTime() == time)
          return alphaPair;

        if (alphaPair.getTime() > time) {
          if (nIndex > 0)
            return getAlphaPairForIndex(nIndex - 1);
          else
            break;
        }
      }
    }

    return alphaPair;
  }

  // returns an AlphaPair immediately to the
  // right of the given time
  protected AlphaPair getRightPairFromTime(long time) {
    AlphaPair alphaPair = null;

    for (int nIndex = 0; nIndex < getNumValues(); nIndex++) {
      alphaPair = getAlphaPairForIndex(nIndex);

      if (alphaPair != null && alphaPair.getTime() >= time)
        return alphaPair;
    }

    return alphaPair;
  }

  // returns the number of AlphaPairs loaded
  public int getNumValues() {
    return m_AlphaVector.size();
  }

  // returns the time for the AlphaPair at
  // a given index
  public long getTimeForValue(int nIndex) {
    AlphaPair alphaPair = getAlphaPairForIndex(nIndex);

    if (alphaPair != null) {
      return getAlphaPairForIndex(nIndex).getTime();
    }

    return 0;
  }

  // returns the maximum loaded AlphaPair time
  public long getMaxTime() {
    return getTimeForValue(getNumValues() 1);
  }

  // read the AlphaPairs from a file.
  protected void readAlphaValues(URL url) {
    // allocate a temporary buffer to store the input file
    StringBuffer szBufferData = new StringBuffer();

    try {
      InputStream inputStream = url.openStream();

      int nChar = 0;

      // read the entire file into the StringBuffer
      while (true) {
        nChar = inputStream.read();

        // if we have not hit the end of file
        // add the character to the StringBuffer
        if (nChar != -1)
          szBufferData.append((charnChar);
        else
          // EOF
          break;
      }

      inputStream.close();

      // create a tokenizer to tokenize the input file at whitespace
      java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(
          szBufferData.toString());

      // keep reading time/alpha pairs until we hit EOF
      while (true) {
        try {
          long time = Long.parseLong(tokenizer.nextToken());
          float alpha = Float.parseFloat(tokenizer.nextToken