home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / JBuilder8.iso / Solaris / resource / jre / demo / plugin / applets / MoleculeViewer / XYZApp.java < prev    next >
Encoding:
Java Source  |  2002-09-06  |  14.1 KB  |  533 lines

  1. /*
  2.  * Copyright (c) 2002 Sun Microsystems, Inc. All  Rights Reserved.
  3.  * 
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  * 
  8.  * -Redistributions of source code must retain the above copyright
  9.  *  notice, this list of conditions and the following disclaimer.
  10.  * 
  11.  * -Redistribution in binary form must reproduct the above copyright
  12.  *  notice, this list of conditions and the following disclaimer in
  13.  *  the documentation and/or other materials provided with the distribution.
  14.  * 
  15.  * Neither the name of Sun Microsystems, Inc. or the names of contributors
  16.  * may be used to endorse or promote products derived from this software
  17.  * without specific prior written permission.
  18.  * 
  19.  * This software is provided "AS IS," without a warranty of any kind. ALL
  20.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
  21.  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  22.  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
  23.  * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
  24.  * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
  25.  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
  26.  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
  27.  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
  28.  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
  29.  * IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  30.  * 
  31.  * You acknowledge that Software is not designed, licensed or intended for
  32.  * use in the design, construction, operation or maintenance of any nuclear
  33.  * facility.
  34.  */
  35.  
  36. /*
  37.  * @(#)XYZApp.java    1.12 02/06/13
  38.  */
  39.  
  40. /*
  41.  * A set of classes to parse, represent and display Chemical compounds in
  42.  * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html)
  43.  */
  44.  
  45. import java.applet.Applet;
  46. import java.awt.Image;
  47. import java.awt.Event;
  48. import java.awt.Graphics;
  49. import java.awt.Dimension;
  50. import java.io.*;
  51. import java.net.URL;
  52. import java.util.Hashtable;
  53. import java.awt.image.IndexColorModel;
  54. import java.awt.image.ColorModel;
  55. import java.awt.image.MemoryImageSource;
  56. import java.awt.event.*;
  57.  
  58. /** The representation of a Chemical .xyz model */
  59. class XYZChemModel {
  60.     float vert[];
  61.     Atom atoms[];
  62.     int tvert[];
  63.     int ZsortMap[];
  64.     int nvert, maxvert;
  65.  
  66.     static Hashtable atomTable = new Hashtable();
  67.     static Atom defaultAtom;
  68.     static {
  69.     atomTable.put("c", new Atom(0, 0, 0));
  70.     atomTable.put("h", new Atom(210, 210, 210));
  71.     atomTable.put("n", new Atom(0, 0, 255));
  72.     atomTable.put("o", new Atom(255, 0, 0));
  73.     atomTable.put("p", new Atom(255, 0, 255));
  74.     atomTable.put("s", new Atom(255, 255, 0));
  75.     atomTable.put("hn", new Atom(150, 255, 150)); /* !!*/
  76.     defaultAtom = new Atom(255, 100, 200);
  77.     }
  78.  
  79.     boolean transformed;
  80.     Matrix3D mat;
  81.  
  82.     float xmin, xmax, ymin, ymax, zmin, zmax;
  83.  
  84.  
  85.     XYZChemModel () {
  86.     mat = new Matrix3D();
  87.     mat.xrot(20);
  88.     mat.yrot(30);
  89.     }
  90.  
  91.  
  92.     /** Create a Cehmical model by parsing an input stream */
  93.     XYZChemModel (InputStream is) throws Exception
  94.     {
  95.        this();
  96.        StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
  97.        st.eolIsSignificant(true);
  98.        st.commentChar('#');
  99.        int slot = 0;
  100.  
  101.        try
  102.        {
  103. scan:
  104.           while (true)
  105.           {
  106.              switch ( st.nextToken() )
  107.              {
  108.                 case StreamTokenizer.TT_EOF:
  109.                    break scan;
  110.                 default:
  111.                    break;
  112.                 case StreamTokenizer.TT_WORD:
  113.                    String name = st.sval;
  114.                    double x = 0, y = 0, z = 0;
  115.                    if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  116.                    {
  117.                       x = st.nval;
  118.                       if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  119.                       {
  120.                          y = st.nval;
  121.                          if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  122.                             z = st.nval;
  123.                       }
  124.                    }
  125.                    addVert(name, (float) x, (float) y, (float) z);
  126.                    while( st.ttype != StreamTokenizer.TT_EOL &&
  127.                           st.ttype != StreamTokenizer.TT_EOF )
  128.                       st.nextToken();
  129.  
  130.              }   // end Switch
  131.  
  132.           }  // end while
  133.  
  134.           is.close();
  135.  
  136.        }  // end Try
  137.        catch( IOException e) {}
  138.  
  139.        if (st.ttype != StreamTokenizer.TT_EOF)
  140.           throw new Exception(st.toString());
  141.  
  142.     }  // end XYZChemModel()
  143.  
  144.     /** Add a vertex to this model */
  145.     int addVert(String name, float x, float y, float z) {
  146.     int i = nvert;
  147.     if (i >= maxvert)
  148.         if (vert == null) {
  149.         maxvert = 100;
  150.         vert = new float[maxvert * 3];
  151.         atoms = new Atom[maxvert];
  152.         } else {
  153.         maxvert *= 2;
  154.         float nv[] = new float[maxvert * 3];
  155.         System.arraycopy(vert, 0, nv, 0, vert.length);
  156.         vert = nv;
  157.         Atom na[] = new Atom[maxvert];
  158.         System.arraycopy(atoms, 0, na, 0, atoms.length);
  159.         atoms = na;
  160.         }
  161.     Atom a = (Atom) atomTable.get(name.toLowerCase());
  162.     if (a == null) a = defaultAtom;
  163.     atoms[i] = a;
  164.     i *= 3;
  165.     vert[i] = x;
  166.     vert[i + 1] = y;
  167.     vert[i + 2] = z;
  168.     return nvert++;
  169.     }
  170.  
  171.     /** Transform all the points in this model */
  172.     void transform() {
  173.     if (transformed || nvert <= 0)
  174.         return;
  175.     if (tvert == null || tvert.length < nvert * 3)
  176.         tvert = new int[nvert * 3];
  177.     mat.transform(vert, tvert, nvert);
  178.     transformed = true;
  179.     }
  180.  
  181.  
  182.     /** Paint this model to a graphics context.  It uses the matrix associated
  183.     with this model to map from model space to screen space.
  184.     The next version of the browser should have double buffering,
  185.     which will make this *much* nicer */
  186.     void paint(Graphics g) {
  187.     if (vert == null || nvert <= 0)
  188.         return;
  189.     transform();
  190.     int v[] = tvert;
  191.     int zs[] = ZsortMap;
  192.     if (zs == null) {
  193.         ZsortMap = zs = new int[nvert];
  194.         for (int i = nvert; --i >= 0;)
  195.         zs[i] = i * 3;
  196.     }
  197.  
  198.     /*
  199.      * I use a bubble sort since from one iteration to the next, the sort
  200.      * order is pretty stable, so I just use what I had last time as a
  201.      * "guess" of the sorted order.  With luck, this reduces O(N log N)
  202.      * to O(N)
  203.      */
  204.  
  205.     for (int i = nvert - 1; --i >= 0;) {
  206.         boolean flipped = false;
  207.         for (int j = 0; j <= i; j++) {
  208.         int a = zs[j];
  209.         int b = zs[j + 1];
  210.         if (v[a + 2] > v[b + 2]) {
  211.             zs[j + 1] = a;
  212.             zs[j] = b;
  213.             flipped = true;
  214.         }
  215.         }
  216.         if (!flipped)
  217.         break;
  218.     }
  219.  
  220.     int lg = 0;
  221.     int lim = nvert;
  222.     Atom ls[] = atoms;
  223.     if (lim <= 0 || nvert <= 0)
  224.         return;
  225.     for (int i = 0; i < lim; i++) {
  226.         int j = zs[i];
  227.         int grey = v[j + 2];
  228.         if (grey < 0)
  229.         grey = 0;
  230.         if (grey > 15)
  231.         grey = 15;
  232.         // g.drawString(names[i], v[j], v[j+1]);
  233.         atoms[j/3].paint(g, v[j], v[j + 1], grey);
  234.         // g.drawImage(iBall, v[j] - (iBall.width >> 1), v[j + 1] -
  235.         // (iBall.height >> 1));
  236.     }
  237.     }
  238.  
  239.     /** Find the bounding box of this model */
  240.     void findBB() {
  241.     if (nvert <= 0)
  242.         return;
  243.     float v[] = vert;
  244.     float xmin = v[0], xmax = xmin;
  245.     float ymin = v[1], ymax = ymin;
  246.     float zmin = v[2], zmax = zmin;
  247.     for (int i = nvert * 3; (i -= 3) > 0;) {
  248.         float x = v[i];
  249.         if (x < xmin)
  250.         xmin = x;
  251.         if (x > xmax)
  252.         xmax = x;
  253.         float y = v[i + 1];
  254.         if (y < ymin)
  255.         ymin = y;
  256.         if (y > ymax)
  257.         ymax = y;
  258.         float z = v[i + 2];
  259.         if (z < zmin)
  260.         zmin = z;
  261.         if (z > zmax)
  262.         zmax = z;
  263.     }
  264.     this.xmax = xmax;
  265.     this.xmin = xmin;
  266.     this.ymax = ymax;
  267.     this.ymin = ymin;
  268.     this.zmax = zmax;
  269.     this.zmin = zmin;
  270.     }
  271. }
  272.  
  273. /** An applet to put a Chemical model into a page */
  274. public class XYZApp
  275.     extends Applet
  276.     implements Runnable, MouseListener, MouseMotionListener {
  277.     XYZChemModel md;
  278.     boolean painted = true;
  279.     float xfac;
  280.     int prevx, prevy;
  281.     float xtheta, ytheta;
  282.     float scalefudge = 1;
  283.     Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
  284.     String mdname = null;
  285.     String message = null;
  286.     Image backBuffer;
  287.     Graphics backGC;
  288.     Dimension backSize;
  289.  
  290.  
  291.     private synchronized void newBackBuffer() {
  292.     backBuffer = createImage(getSize().width, getSize().height);
  293.     if (backGC != null) {
  294.         backGC.dispose();
  295.     }
  296.     backGC = backBuffer.getGraphics();
  297.     backSize = getSize();
  298.     }
  299.  
  300.     public void init() {
  301.     mdname = getParameter("model");
  302.     try {
  303.         scalefudge = Float.valueOf(getParameter("scale")).floatValue();
  304.     } catch(Exception e) {
  305.     };
  306.     amat.yrot(20);
  307.     amat.xrot(20);
  308.     if (mdname == null)
  309.         mdname = "model.obj";
  310.     resize(getSize().width <= 20 ? 400 : getSize().width,
  311.            getSize().height <= 20 ? 400 : getSize().height);
  312.     newBackBuffer();
  313.     addMouseListener(this);
  314.     addMouseMotionListener(this);
  315.     }
  316.  
  317.     public void destroy() {
  318.         removeMouseListener(this);
  319.         removeMouseMotionListener(this);
  320.     }
  321.  
  322.     public void run() {
  323.     InputStream is = null;
  324.     try {
  325.         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  326.         is = new URL(getDocumentBase(), mdname).openStream();
  327.         XYZChemModel m = new XYZChemModel (is);
  328.         Atom.setApplet(this);
  329.         md = m;
  330.         m.findBB();
  331.         float xw = m.xmax - m.xmin;
  332.         float yw = m.ymax - m.ymin;
  333.         float zw = m.zmax - m.zmin;
  334.         if (yw > xw)
  335.         xw = yw;
  336.         if (zw > xw)
  337.         xw = zw;
  338.         float f1 = getSize().width / xw;
  339.         float f2 = getSize().height / xw;
  340.         xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
  341.     } catch(Exception e) {
  342.         e.printStackTrace();
  343.         md = null;
  344.         message = e.toString();
  345.     }
  346.     try {
  347.         if (is != null)
  348.         is.close();
  349.     } catch(Exception e) {
  350.     }
  351.     repaint();
  352.     }
  353.     public void start() {
  354.     if (md == null && message == null)
  355.         new Thread(this).start();
  356.     }
  357.     public void stop() {
  358.     }
  359.       /* event handling */
  360.   public void mouseClicked(MouseEvent e) {
  361.   }
  362.   public void mousePressed(MouseEvent e) {
  363.     prevx = e.getX();
  364.     prevy = e.getY();
  365.     e.consume();
  366.   }
  367.   public void mouseReleased(MouseEvent e) {
  368.   }
  369.   public void mouseEntered(MouseEvent e) {
  370.   }
  371.   public void mouseExited(MouseEvent e) {
  372.   }
  373.   public void mouseDragged(MouseEvent e) {
  374.     int x = e.getX();
  375.     int y = e.getY();
  376.     tmat.unit();
  377.     float xtheta = (prevy - y) * (360.0f / getSize().width);
  378.     float ytheta = (x - prevx) * (360.0f / getSize().height);
  379.     tmat.xrot(xtheta);
  380.     tmat.yrot(ytheta);
  381.     amat.mult(tmat);
  382.     if (painted) {
  383.       painted = false;
  384.       repaint();
  385.     }
  386.     prevx = x;
  387.     prevy = y;
  388.     e.consume();
  389.   }
  390.   public void mouseMoved(MouseEvent e) {
  391.   }
  392.  
  393.     public void update(Graphics g) {
  394.     if (backBuffer == null)
  395.         g.clearRect(0, 0, getSize().width, getSize().height);
  396.     paint(g);
  397.     }
  398.  
  399.     public void paint(Graphics g) {
  400.     if (md != null) {
  401.         md.mat.unit();
  402.         md.mat.translate(-(md.xmin + md.xmax) / 2,
  403.                  -(md.ymin + md.ymax) / 2,
  404.                  -(md.zmin + md.zmax) / 2);
  405.         md.mat.mult(amat);
  406.         // md.mat.scale(xfac, -xfac, 8 * xfac / getSize().width);
  407.         md.mat.scale(xfac, -xfac, 16 * xfac / getSize().width);
  408.         md.mat.translate(getSize().width / 2, getSize().height / 2, 8);
  409.         md.transformed = false;
  410.         if (backBuffer != null) {
  411.         if (!backSize.equals(getSize()))
  412.             newBackBuffer();
  413.         backGC.setColor(getBackground());
  414.         backGC.fillRect(0,0,getSize().width,getSize().height);
  415.         md.paint(backGC);
  416.         g.drawImage(backBuffer, 0, 0, this);
  417.         }
  418.         else
  419.         md.paint(g);
  420.         setPainted();
  421.     } else if (message != null) {
  422.         g.drawString("Error in model:", 3, 20);
  423.         g.drawString(message, 10, 40);
  424.     }
  425.     }
  426.     private synchronized void setPainted() {
  427.     painted = true;
  428.     notifyAll();
  429.     }
  430.  
  431.     private synchronized void waitPainted()
  432.     {
  433.        while (!painted)
  434.        {
  435.           try
  436.           {
  437.              wait();
  438.           }
  439.           catch (InterruptedException e) {}
  440.        }
  441.        painted = false;
  442.     }
  443.  
  444.   public String getAppletInfo() {
  445.     return "Title: XYZApp \nAuthor: James Gosling \nAn applet to put a Chemical model into a page.";
  446.   }
  447.  
  448.   public String[][] getParameterInfo() {
  449.     String[][] info = {
  450.       {"model", "path string", "The path to the model to be displayed in .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html).  Default is model.obj."},
  451.       {"scale", "float", "Scale factor.  Default is 1 (i.e. no scale)."}
  452.     };
  453.     return info;
  454.   }
  455. }   // end class XYZApp
  456.  
  457. class Atom {
  458.     private static Applet applet;
  459.     private static byte[] data;
  460.     private final static int R = 40;
  461.     private final static int hx = 15;
  462.     private final static int hy = 15;
  463.     private final static int bgGrey = 192;
  464.     private final static int nBalls = 16;
  465.     private static int maxr;
  466.  
  467.     private int Rl;
  468.     private int Gl;
  469.     private int Bl;
  470.     private Image balls[];
  471.  
  472.     static {
  473.     data = new byte[R * 2 * R * 2];
  474.     int mr = 0;
  475.     for (int Y = 2 * R; --Y >= 0;) {
  476.         int x0 = (int) (Math.sqrt(R * R - (Y - R) * (Y - R)) + 0.5);
  477.         int p = Y * (R * 2) + R - x0;
  478.         for (int X = -x0; X < x0; X++) {
  479.         int x = X + hx;
  480.         int y = Y - R + hy;
  481.         int r = (int) (Math.sqrt(x * x + y * y) + 0.5);
  482.         if (r > mr)
  483.             mr = r;
  484.         data[p++] = r <= 0 ? 1 : (byte) r;
  485.         }
  486.     }
  487.     maxr = mr;
  488.     }
  489.     static void setApplet(Applet app) {
  490.     applet = app;
  491.     }
  492.     Atom(int Rl, int Gl, int Bl) {
  493.     this.Rl = Rl;
  494.     this.Gl = Gl;
  495.     this.Bl = Bl;
  496.     }
  497.     private final int blend(int fg, int bg, float fgfactor) {
  498.     return (int) (bg + (fg - bg) * fgfactor);
  499.     }
  500.     private void Setup() {
  501.     balls = new Image[nBalls];
  502.     byte red[] = new byte[256];
  503.     red[0] = (byte) bgGrey;
  504.     byte green[] = new byte[256];
  505.     green[0] = (byte) bgGrey;
  506.     byte blue[] = new byte[256];
  507.     blue[0] = (byte) bgGrey;
  508.     for (int r = 0; r < nBalls; r++) {
  509.         float b = (float) (r+1) / nBalls;
  510.         for (int i = maxr; i >= 1; --i) {
  511.         float d = (float) i / maxr;
  512.         red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b);
  513.         green[i] = (byte) blend(blend(Gl, 255, d), bgGrey, b);
  514.         blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b);
  515.         }
  516.         IndexColorModel model = new IndexColorModel(8, maxr + 1,
  517.                             red, green, blue, 0);
  518.         balls[r] = applet.createImage(
  519.         new MemoryImageSource(R*2, R*2, model, data, 0, R*2));
  520.     }
  521.     }
  522.     void paint(Graphics gc, int x, int y, int r) {
  523.     Image ba[] = balls;
  524.     if (ba == null) {
  525.         Setup();
  526.         ba = balls;
  527.     }
  528.     Image i = ba[r];
  529.     int size = 10 + r;
  530.     gc.drawImage(i, x - (size >> 1), y - (size >> 1), size, size, applet);
  531.     }
  532. }
  533.