home *** CD-ROM | disk | FTP | other *** search
/ Ultra Pack / UltraComputing Technology Demos and Tools.iso / java / demo / MoleculeViewer / XYZApp.java < prev    next >
Encoding:
Java Source  |  1996-04-26  |  12.6 KB  |  480 lines

  1. /*
  2.  * @(#)XYZApp.java
  3.  * 
  4.  *
  5.  * Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved.
  6.  *
  7.  * Permission to use, copy, modify, and distribute this software
  8.  * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
  9.  * without fee is hereby granted. 
  10.  * Please refer to the file http://www.javasoft.com/copy_trademarks.html
  11.  * for further important copyright and trademark information and to
  12.  * http://www.javasoft.com/licensing.html for further important licensing
  13.  * information for the Java (tm) Technology.
  14.  * 
  15.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  16.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  17.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  18.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  19.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  20.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  21.  * 
  22.  * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
  23.  * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
  24.  * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
  25.  * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
  26.  * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
  27.  * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
  28.  * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES").  SUN
  29.  * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
  30.  * HIGH RISK ACTIVITIES.
  31.  */
  32.  
  33. /*
  34.  * A set of classes to parse, represent and display Chemical compounds in
  35.  * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html)
  36.  */
  37.  
  38. import java.applet.Applet;
  39. import java.awt.Image;
  40. import java.awt.Event;
  41. import java.awt.Graphics;
  42. import java.io.StreamTokenizer;
  43. import java.io.InputStream;
  44. import java.io.BufferedInputStream;
  45. import java.io.IOException;
  46. import java.net.URL;
  47. import java.util.Hashtable;
  48. import java.awt.image.IndexColorModel;
  49. import java.awt.image.ColorModel;
  50. import java.awt.image.MemoryImageSource;
  51.  
  52.  
  53. /** The representation of a Chemical .xyz model */
  54. class XYZChemModel {
  55.     float vert[];
  56.     Atom atoms[];
  57.     int tvert[];
  58.     int ZsortMap[];
  59.     int nvert, maxvert;
  60.  
  61.     static Hashtable atomTable = new Hashtable();
  62.     static Atom defaultAtom;
  63.     static {
  64.     atomTable.put("c", new Atom(0, 0, 0));
  65.     atomTable.put("h", new Atom(210, 210, 210));
  66.     atomTable.put("n", new Atom(0, 0, 255));
  67.     atomTable.put("o", new Atom(255, 0, 0));
  68.     atomTable.put("p", new Atom(255, 0, 255));
  69.     atomTable.put("s", new Atom(255, 255, 0));
  70.     atomTable.put("hn", new Atom(150, 255, 150)); /* !!*/
  71.     defaultAtom = new Atom(255, 100, 200);
  72.     }
  73.  
  74.     boolean transformed;
  75.     Matrix3D mat;
  76.  
  77.     float xmin, xmax, ymin, ymax, zmin, zmax;
  78.  
  79.  
  80.     XYZChemModel () {
  81.     mat = new Matrix3D();
  82.     mat.xrot(20);
  83.     mat.yrot(30);
  84.     }
  85.  
  86.  
  87.     /** Create a Cehmical model by parsing an input stream */
  88.     XYZChemModel (InputStream is) throws Exception
  89.     {
  90.        this();
  91.        StreamTokenizer st;
  92.        st = new StreamTokenizer(new BufferedInputStream(is, 4000));
  93.        st.eolIsSignificant(true);
  94.        st.commentChar('#');
  95.        int slot = 0;
  96.       
  97.        try
  98.        {
  99. scan:
  100.           while (true)
  101.           {
  102.              switch ( st.nextToken() ) 
  103.              {
  104.                 case StreamTokenizer.TT_EOF:
  105.                    break scan;
  106.                 default:
  107.                    break;
  108.                 case StreamTokenizer.TT_WORD:
  109.                    String name = st.sval;
  110.                    double x = 0, y = 0, z = 0;
  111.                    if (st.nextToken() == StreamTokenizer.TT_NUMBER) 
  112.                    {
  113.                       x = st.nval;
  114.                       if (st.nextToken() == StreamTokenizer.TT_NUMBER) 
  115.                       {
  116.                          y = st.nval;
  117.                          if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  118.                             z = st.nval;
  119.                       }
  120.                    }
  121.                    addVert(name, (float) x, (float) y, (float) z);
  122.                    while( st.ttype != StreamTokenizer.TT_EOL &&
  123.                           st.ttype != StreamTokenizer.TT_EOF )
  124.                       st.nextToken();
  125.  
  126.              }   // end Switch
  127.  
  128.           }  // end while
  129.  
  130.           is.close();
  131.  
  132.        }  // end Try
  133.        catch( IOException e) {}
  134.  
  135.        if (st.ttype != StreamTokenizer.TT_EOF)
  136.           throw new Exception(st.toString());
  137.  
  138.     }  // end XYZChemModel()
  139.  
  140.     /** Add a vertex to this model */
  141.     int addVert(String name, float x, float y, float z) {
  142.     int i = nvert;
  143.     if (i >= maxvert)
  144.         if (vert == null) {
  145.         maxvert = 100;
  146.         vert = new float[maxvert * 3];
  147.         atoms = new Atom[maxvert];
  148.         } else {
  149.         maxvert *= 2;
  150.         float nv[] = new float[maxvert * 3];
  151.         System.arraycopy(vert, 0, nv, 0, vert.length);
  152.         vert = nv;
  153.         Atom na[] = new Atom[maxvert];
  154.         System.arraycopy(atoms, 0, na, 0, atoms.length);
  155.         atoms = na;
  156.         }
  157.     Atom a = (Atom) atomTable.get(name.toLowerCase());
  158.     if (a == null) a = defaultAtom;
  159.     atoms[i] = a;
  160.     i *= 3;
  161.     vert[i] = x;
  162.     vert[i + 1] = y;
  163.     vert[i + 2] = z;
  164.     return nvert++;
  165.     }
  166.  
  167.     /** Transform all the points in this model */
  168.     void transform() {
  169.     if (transformed || nvert <= 0)
  170.         return;
  171.     if (tvert == null || tvert.length < nvert * 3)
  172.         tvert = new int[nvert * 3];
  173.     mat.transform(vert, tvert, nvert);
  174.     transformed = true;
  175.     }
  176.  
  177.  
  178.     /** Paint this model to a graphics context.  It uses the matrix associated
  179.     with this model to map from model space to screen space.
  180.     The next version of the browser should have double buffering,
  181.     which will make this *much* nicer */
  182.     void paint(Graphics g) {
  183.     if (vert == null || nvert <= 0)
  184.         return;
  185.     transform();
  186.     int v[] = tvert;
  187.     int zs[] = ZsortMap;
  188.     if (zs == null) {
  189.         ZsortMap = zs = new int[nvert];
  190.         for (int i = nvert; --i >= 0;)
  191.         zs[i] = i * 3;
  192.     }
  193.  
  194.     /*
  195.      * I use a bubble sort since from one iteration to the next, the sort
  196.      * order is pretty stable, so I just use what I had last time as a
  197.      * "guess" of the sorted order.  With luck, this reduces O(N log N)
  198.      * to O(N)
  199.      */
  200.  
  201.     for (int i = nvert - 1; --i >= 0;) {
  202.         boolean flipped = false;
  203.         for (int j = 0; j <= i; j++) {
  204.         int a = zs[j];
  205.         int b = zs[j + 1];
  206.         if (v[a + 2] > v[b + 2]) {
  207.             zs[j + 1] = a;
  208.             zs[j] = b;
  209.             flipped = true;
  210.         }
  211.         }
  212.         if (!flipped)
  213.         break;
  214.     }
  215.  
  216.     int lg = 0;
  217.     int lim = nvert;
  218.     Atom ls[] = atoms;
  219.     if (lim <= 0 || nvert <= 0)
  220.         return;
  221.     for (int i = 0; i < lim; i++) {
  222.         int j = zs[i];
  223.         int grey = v[j + 2];
  224.         if (grey < 0)
  225.         grey = 0;
  226.         if (grey > 15)
  227.         grey = 15;
  228.         // g.drawString(names[i], v[j], v[j+1]);
  229.         atoms[j/3].paint(g, v[j], v[j + 1], grey);
  230.         // g.drawImage(iBall, v[j] - (iBall.width >> 1), v[j + 1] -
  231.         // (iBall.height >> 1));
  232.     }
  233.     }
  234.  
  235.     /** Find the bounding box of this model */
  236.     void findBB() {
  237.     if (nvert <= 0)
  238.         return;
  239.     float v[] = vert;
  240.     float xmin = v[0], xmax = xmin;
  241.     float ymin = v[1], ymax = ymin;
  242.     float zmin = v[2], zmax = zmin;
  243.     for (int i = nvert * 3; (i -= 3) > 0;) {
  244.         float x = v[i];
  245.         if (x < xmin)
  246.         xmin = x;
  247.         if (x > xmax)
  248.         xmax = x;
  249.         float y = v[i + 1];
  250.         if (y < ymin)
  251.         ymin = y;
  252.         if (y > ymax)
  253.         ymax = y;
  254.         float z = v[i + 2];
  255.         if (z < zmin)
  256.         zmin = z;
  257.         if (z > zmax)
  258.         zmax = z;
  259.     }
  260.     this.xmax = xmax;
  261.     this.xmin = xmin;
  262.     this.ymax = ymax;
  263.     this.ymin = ymin;
  264.     this.zmax = zmax;
  265.     this.zmin = zmin;
  266.     }
  267. }
  268.  
  269. /** An applet to put a Cehmical model into a page */
  270. public class XYZApp extends Applet implements Runnable {
  271.     XYZChemModel md;
  272.     boolean painted = true;
  273.     float xfac;
  274.     int prevx, prevy;
  275.     float xtheta, ytheta;
  276.     float scalefudge = 1;
  277.     Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
  278.     String mdname = null;
  279.     String message = null;
  280.     Image backBuffer;
  281.     Graphics backGC;
  282.  
  283.  
  284.     public void init() {
  285.     mdname = getParameter("model");
  286.     try {
  287.         scalefudge = Float.valueOf(getParameter("scale")).floatValue();
  288.     } catch(Exception e) {
  289.     };
  290.     amat.yrot(20);
  291.     amat.xrot(20);
  292.     if (mdname == null)
  293.         mdname = "model.obj";
  294.     resize(size().width <= 20 ? 400 : size().width,
  295.            size().height <= 20 ? 400 : size().height);
  296.     }
  297.     public void run() {
  298.     InputStream is = null;
  299.     try {
  300.         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  301.         is = new URL(getDocumentBase(), mdname).openStream();
  302.         XYZChemModel m = new XYZChemModel (is);
  303.         Atom.setApplet(this);
  304.         md = m;
  305.         m.findBB();
  306.         float xw = m.xmax - m.xmin;
  307.         float yw = m.ymax - m.ymin;
  308.         float zw = m.zmax - m.zmin;
  309.         if (yw > xw)
  310.         xw = yw;
  311.         if (zw > xw)
  312.         xw = zw;
  313.         float f1 = size().width / xw;
  314.         float f2 = size().height / xw;
  315.         xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
  316.         backBuffer = createImage(size().width, size().height);
  317.         backGC = backBuffer.getGraphics();
  318.     } catch(Exception e) {
  319.         e.printStackTrace();
  320.         md = null;
  321.         message = e.toString();
  322.     }
  323.     try {
  324.         if (is != null)
  325.         is.close();
  326.     } catch(Exception e) {
  327.     }
  328.     repaint();
  329.     }
  330.     public void start() {
  331.     if (md == null && message == null)
  332.         new Thread(this).start();
  333.     }
  334.     public void stop() {
  335.     }
  336.     public boolean mouseDown(Event e, int x, int y) {
  337.     prevx = x;
  338.     prevy = y;
  339.     return true;
  340.     }
  341.     public boolean mouseDrag(Event e, int x, int y) {
  342.     tmat.unit();
  343.     float xtheta = (prevy - y) * (360.0f / size().width);
  344.     float ytheta = (x - prevx) * (360.0f / size().height);
  345.     tmat.xrot(xtheta);
  346.     tmat.yrot(ytheta);
  347.     amat.mult(tmat);
  348.     if (painted) {
  349.         painted = false;
  350.         repaint();
  351.     }
  352.     prevx = x;
  353.     prevy = y;
  354.     return true;
  355.     }
  356.     public void update(Graphics g) {
  357.     if (backBuffer == null)
  358.         g.clearRect(0, 0, size().width, size().height);
  359.     paint(g);
  360.     }
  361.     public void paint(Graphics g) {
  362.     if (md != null) {
  363.         md.mat.unit();
  364.         md.mat.translate(-(md.xmin + md.xmax) / 2,
  365.                  -(md.ymin + md.ymax) / 2,
  366.                  -(md.zmin + md.zmax) / 2);
  367.         md.mat.mult(amat);
  368.         // md.mat.scale(xfac, -xfac, 8 * xfac / size().width);
  369.         md.mat.scale(xfac, -xfac, 16 * xfac / size().width);
  370.         md.mat.translate(size().width / 2, size().height / 2, 8);
  371.         md.transformed = false;
  372.         if (backBuffer != null) {
  373.         backGC.setColor(getBackground());
  374.         backGC.fillRect(0,0,size().width,size().height);
  375.         md.paint(backGC);
  376.         g.drawImage(backBuffer, 0, 0, this);
  377.         } else
  378.         md.paint(g);
  379.         setPainted();
  380.     } else if (message != null) {
  381.         g.drawString("Error in model:", 3, 20);
  382.         g.drawString(message, 10, 40);
  383.     }
  384.     }
  385.     private synchronized void setPainted() {
  386.     painted = true;
  387.     notifyAll();
  388.     }
  389.  
  390.     private synchronized void waitPainted() 
  391.     {
  392.        while (!painted)
  393.        {
  394.           try
  395.           {
  396.              wait();
  397.           }
  398.           catch (InterruptedException e) {}
  399.        }
  400.        painted = false;
  401.     }
  402. }   // end class XYZApp
  403.  
  404. class Atom {
  405.     private static Applet applet;
  406.     private static byte[] data;
  407.     private final static int R = 40;
  408.     private final static int hx = 15;
  409.     private final static int hy = 15;
  410.     private final static int bgGrey = 192;
  411.     private final static int nBalls = 16;
  412.     private static int maxr;
  413.  
  414.     private int Rl;
  415.     private int Gl;
  416.     private int Bl;
  417.     private Image balls[];
  418.  
  419.     static {
  420.     data = new byte[R * 2 * R * 2];
  421.     int mr = 0;
  422.     for (int Y = 2 * R; --Y >= 0;) {
  423.         int x0 = (int) (Math.sqrt(R * R - (Y - R) * (Y - R)) + 0.5);
  424.         int p = Y * (R * 2) + R - x0;
  425.         for (int X = -x0; X < x0; X++) {
  426.         int x = X + hx;
  427.         int y = Y - R + hy;
  428.         int r = (int) (Math.sqrt(x * x + y * y) + 0.5);
  429.         if (r > mr)
  430.             mr = r;
  431.         data[p++] = r <= 0 ? 1 : (byte) r;
  432.         }
  433.     }
  434.     maxr = mr;
  435.     }
  436.     static void setApplet(Applet app) {
  437.     applet = app;
  438.     }
  439.     Atom(int Rl, int Gl, int Bl) {
  440.     this.Rl = Rl;
  441.     this.Gl = Gl;
  442.     this.Bl = Bl;
  443.     }
  444.     private final int blend(int fg, int bg, float fgfactor) {
  445.     return (int) (bg + (fg - bg) * fgfactor);
  446.     }
  447.     private void Setup() {
  448.     balls = new Image[nBalls];
  449.     byte red[] = new byte[256];
  450.     red[0] = (byte) bgGrey;
  451.     byte green[] = new byte[256];
  452.     green[0] = (byte) bgGrey;
  453.     byte blue[] = new byte[256];
  454.     blue[0] = (byte) bgGrey;
  455.     for (int r = 0; r < nBalls; r++) {
  456.         float b = (float) (r+1) / nBalls;
  457.         for (int i = maxr; i >= 1; --i) {
  458.         float d = (float) i / maxr;
  459.         red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b);
  460.         green[i] = (byte) blend(blend(Gl, 255, d), bgGrey, b);
  461.         blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b);
  462.         }
  463.         IndexColorModel model = new IndexColorModel(8, maxr + 1,
  464.                             red, green, blue, 0);
  465.         balls[r] = applet.createImage(
  466.         new MemoryImageSource(R*2, R*2, model, data, 0, R*2));
  467.     }
  468.     }
  469.     void paint(Graphics gc, int x, int y, int r) {
  470.     Image ba[] = balls;
  471.     if (ba == null) {
  472.         Setup();
  473.         ba = balls;
  474.     }
  475.     Image i = ba[r];
  476.     int size = 10 + r;
  477.     gc.drawImage(i, x - (size >> 1), y - (size >> 1), size, size, applet);
  478.     }
  479. }
  480.