home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / 3rdParty / jbuilder / unsupported / JDK1.2beta3 / SOURCE / DEMO / APPLETS / FRACTAL / CLSFractal.java < prev    next >
Encoding:
Java Source  |  1998-03-20  |  11.5 KB  |  422 lines

  1. /*
  2.  * @(#)CLSFractal.java    1.3 97/11/18
  3.  *
  4.  * Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
  7.  * modify and redistribute this software in source and binary code form,
  8.  * provided that i) this copyright notice and license appear on all copies of
  9.  * the software; and ii) Licensee does not utilize the software in a manner
  10.  * which is disparaging to Sun.
  11.  *
  12.  * This software is provided "AS IS," without a warranty of any kind. ALL
  13.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  14.  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  15.  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
  16.  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
  17.  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
  18.  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
  19.  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
  20.  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
  21.  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
  22.  * POSSIBILITY OF SUCH DAMAGES.
  23.  *
  24.  * This software is not designed or intended for use in on-line control of
  25.  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
  26.  * the design, construction, operation or maintenance of any nuclear
  27.  * facility. Licensee represents and warrants that it will not use or
  28.  * redistribute the Software for such purposes.
  29.  */
  30.  
  31. import java.awt.Graphics;
  32. import java.util.Stack;
  33. import java.util.Vector;
  34. import java.awt.event.*;
  35.  
  36. /**
  37.  * A (not-yet) Context sensitive L-System Fractal applet class.
  38.  *
  39.  * The rules for the Context L-system are read from the java.applet.Applet's
  40.  * attributes and then the system is iteratively applied for the
  41.  * given number of levels, possibly drawing each generation as it
  42.  * is generated.  Note that the ContextLSystem class does not yet
  43.  * handle the lContext and rContext attributes, although this
  44.  * class is already designed to parse the '[' and ']' characters
  45.  * typically used in Context sensitive L-Systems.
  46.  *
  47.  * @author     Jim Graham
  48.  * @version     1.1f, 27 Mar 1995
  49.  */
  50. public class CLSFractal 
  51.     extends java.applet.Applet 
  52.     implements Runnable, MouseListener {
  53.     ContextLSystem cls;
  54.     int fractLevel = 1;
  55.     int repaintDelay = 50;
  56.     boolean incrementalUpdates;
  57.     float startAngle = 0;
  58.     float rotAngle = 45;
  59.     float Xmin;
  60.     float Xmax;
  61.     float Ymin;
  62.     float Ymax;
  63.     int border;
  64.     boolean normalizescaling;
  65.  
  66.     public void init() {
  67.     String s;
  68.     cls = new ContextLSystem(this);
  69.     s = getParameter("level");
  70.     if (s != null) fractLevel = Integer.parseInt(s);
  71.     s = getParameter("incremental");
  72.     if (s != null) incrementalUpdates = s.equalsIgnoreCase("true");
  73.     s = getParameter("delay");
  74.     if (s != null) repaintDelay = Integer.parseInt(s);
  75.     s = getParameter("startAngle");
  76.     if (s != null) startAngle = Float.valueOf(s).floatValue();
  77.     s = getParameter("rotAngle");
  78.     if (s != null) rotAngle = Float.valueOf(s).floatValue();
  79.     rotAngle = rotAngle / 360 * 2 * 3.14159265358f;
  80.     s = getParameter("border");
  81.     if (s != null) border = Integer.parseInt(s);
  82.     s = getParameter("normalizescale");
  83.     if (s != null) normalizescaling = s.equalsIgnoreCase("true");
  84.     addMouseListener(this);
  85.     }
  86.  
  87.     Thread kicker;
  88.  
  89.     public void run() {
  90.     Thread me = Thread.currentThread();
  91.     boolean needsRepaint = false;
  92.     while (kicker == me && cls.getLevel() < fractLevel) {
  93.         cls.generate();
  94.         if (kicker == me && incrementalUpdates) {
  95.         repaint();
  96.         try {Thread.sleep(repaintDelay);} catch (InterruptedException e){}
  97.         } else {
  98.         needsRepaint = true;
  99.         }
  100.     }
  101.     if (kicker == me) {
  102.         kicker = null;
  103.         if (needsRepaint) {
  104.         repaint();
  105.         }
  106.     }
  107.     }
  108.  
  109.     public void start() {
  110.     kicker = new Thread(this);
  111.     kicker.start();
  112.     }
  113.  
  114.     public void stop() {
  115.     kicker = null;
  116.     }
  117.  
  118.       /*1.1 event handling */
  119.   public void mouseClicked(MouseEvent e) {
  120.   }   
  121.   public void mousePressed(MouseEvent e) {
  122.   } 
  123.   public void mouseReleased(MouseEvent e) {
  124.     cls = new ContextLSystem(this);
  125.     savedPath = null;
  126.     start();
  127.     e.consume();
  128.   }
  129.   public void mouseEntered(MouseEvent e) {
  130.   }
  131.   public void mouseExited(MouseEvent e) {
  132.   }  
  133.       
  134.     String savedPath;
  135.  
  136.     public void paint(Graphics g) {
  137.     String fractalPath = cls.getPath();
  138.     if (fractalPath == null) {
  139.         super.paint(g);
  140.         return;
  141.     }
  142.     if (savedPath == null || !savedPath.equals(fractalPath)) {
  143.         savedPath = fractalPath;
  144.         render(null, fractalPath);
  145.     }
  146.  
  147.     for (int i = 0; i < border; i++) {
  148.         g.draw3DRect(i, i, getSize().width - i * 2, getSize().height - i * 2,false);
  149.     }
  150.     render(g, fractalPath);
  151.     }
  152.  
  153.     void render(Graphics g, String path) {
  154.     Stack turtleStack = new Stack();
  155.     CLSTurtle turtle;
  156.  
  157.     if (g == null) {
  158.         Xmin = 1E20f;
  159.         Ymin = 1E20f;
  160.         Xmax = -1E20f;
  161.         Ymax = -1E20f;
  162.         turtle = new CLSTurtle(startAngle, 0, 0, 0, 0, 1, 1);
  163.     } else {
  164.         float frwidth = Xmax - Xmin;
  165.         if (frwidth == 0)
  166.         frwidth = 1;
  167.         float frheight = Ymax - Ymin;
  168.         if (frheight == 0)
  169.         frheight = 1;
  170.         float xscale = (getSize().width - border * 2 - 1) / frwidth;
  171.         float yscale = (getSize().height - border * 2 - 1) / frheight;
  172.         int xoff = border;
  173.         int yoff = border;
  174.         if (normalizescaling) {
  175.         if (xscale < yscale) {
  176.             yoff += ((getSize().height - border * 2)
  177.                  - ((Ymax - Ymin) * xscale)) / 2;
  178.             yscale = xscale;
  179.         } else if (yscale < xscale) {
  180.             xoff += ((getSize().width - border * 2)
  181.                  - ((Xmax - Xmin) * yscale)) / 2;
  182.             xscale = yscale;
  183.         }
  184.         }
  185.         turtle = new CLSTurtle(startAngle, 0 - Xmin, 0 - Ymin,
  186.                    xoff, yoff, xscale, yscale);
  187.     }
  188.  
  189.     for (int pos = 0; pos < path.length(); pos++) {
  190.         switch (path.charAt(pos)) {
  191.         case '+':
  192.         turtle.rotate(rotAngle);
  193.         break;
  194.         case '-':
  195.         turtle.rotate(-rotAngle);
  196.         break;
  197.         case '[':
  198.         turtleStack.push(turtle);
  199.         turtle = new CLSTurtle(turtle);
  200.         break;
  201.         case ']':
  202.         turtle = (CLSTurtle) turtleStack.pop();
  203.         break;
  204.         case 'f':
  205.         turtle.jump();
  206.         break;
  207.         case 'F':
  208.         if (g == null) {
  209.             includePt(turtle.X, turtle.Y);
  210.             turtle.jump();
  211.             includePt(turtle.X, turtle.Y);
  212.         } else {
  213.             turtle.draw(g);
  214.         }
  215.         break;
  216.         default:
  217.         break;
  218.         }
  219.     }
  220.     }
  221.  
  222.     void includePt(float x, float y) {
  223.     if (x < Xmin)
  224.         Xmin = x;
  225.     if (x > Xmax)
  226.         Xmax = x;
  227.     if (y < Ymin)
  228.         Ymin = y;
  229.     if (y > Ymax)
  230.         Ymax = y;
  231.     }
  232.   
  233.   public String getAppletInfo() {
  234.     return "Title: CLSFractal 1.1f, 27 Mar 1995 \nAuthor: Jim Graham \nA (not yet) Context Sensitive L-System production rule. \nThis class encapsulates a production rule for a Context Sensitive\n L-System \n(pred, succ, lContext, rContext).  The matches() method, however, does not \n(yet) verify the lContext and rContext parts of the rule.";
  235.   }
  236.   
  237.   public String[][] getParameterInfo() {
  238.     String[][] info = {
  239.       {"level", "int", "Maximum number of recursions.  Default is 1."},
  240.       {"incremental","boolean","Whether or not to repaint between recursions.  Default is true."},
  241.       {"delay","integer","Sets delay between repaints.  Default is 50."},
  242.       {"startAngle","float","Sets the starting angle.  Default is 0."},
  243.       {"rotAngle","float","Sets the rotation angle.  Default is 45."},
  244.       {"border","integer","Width of border.  Default is 2."},
  245.       {"normalizeScale","boolean","Whether or not to normalize the scaling.  Default is true."},
  246.       {"pred","String","Initializes the rules for Context Sensitive L-Systems."},
  247.       {"succ","String","Initializes the rules for Context Sensitive L-Systems."},
  248.       {"lContext","String","Initializes the rules for Context Sensitive L-Systems."},
  249.       {"rContext","String","Initializes the rules for Context Sensitive L-Systems."}
  250.     };
  251.     return info;
  252.   }
  253. }
  254.  
  255. /**
  256.  * A Logo turtle class designed to support Context sensitive L-Systems.
  257.  *
  258.  * This turtle performs a few basic maneuvers needed to support the
  259.  * set of characters used in Context sensitive L-Systems "+-fF[]".
  260.  *
  261.  * @author     Jim Graham
  262.  * @version     1.1f, 27 Mar 1995
  263.  */
  264. class CLSTurtle {
  265.     float angle;
  266.     float X;
  267.     float Y;
  268.     float scaleX;
  269.     float scaleY;
  270.     int xoff;
  271.     int yoff;
  272.  
  273.     public CLSTurtle(float ang, float x, float y,
  274.              int xorg, int yorg, float sx, float sy) {
  275.     angle = ang;
  276.     scaleX = sx;
  277.     scaleY = sy;
  278.     X = x * sx;
  279.     Y = y * sy;
  280.     xoff = xorg;
  281.     yoff = yorg;
  282.     }
  283.  
  284.     public CLSTurtle(CLSTurtle turtle) {
  285.     angle = turtle.angle;
  286.     X = turtle.X;
  287.     Y = turtle.Y;
  288.     scaleX = turtle.scaleX;
  289.     scaleY = turtle.scaleY;
  290.     xoff = turtle.xoff;
  291.     yoff = turtle.yoff;
  292.     }
  293.  
  294.     public void rotate(float theta) {
  295.     angle += theta;
  296.     }
  297.  
  298.     public void jump() {
  299.     X += (float) Math.cos(angle) * scaleX;
  300.     Y += (float) Math.sin(angle) * scaleY;
  301.     }
  302.  
  303.     public void draw(Graphics g) {
  304.     float x = X + (float) Math.cos(angle) * scaleX;
  305.     float y = Y + (float) Math.sin(angle) * scaleY;
  306.     g.drawLine((int) X + xoff, (int) Y + yoff,
  307.            (int) x + xoff, (int) y + yoff);
  308.     X = x;
  309.     Y = y;
  310.     }
  311. }
  312.  
  313. /**
  314.  * A (non-)Context sensitive L-System class.
  315.  *
  316.  * This class initializes the rules for Context sensitive L-Systems
  317.  * (pred, succ, lContext, rContext) from the given java.applet.Applet's attributes.
  318.  * The generate() method, however, does not (yet) apply the lContext
  319.  * and rContext parts of the rules.
  320.  *
  321.  * @author     Jim Graham
  322.  * @version     1.1f, 27 Mar 1995
  323.  */
  324. class ContextLSystem {
  325.     String axiom;
  326.     Vector rules = new Vector();
  327.     int level;
  328.  
  329.     public ContextLSystem(java.applet.Applet app) {
  330.     axiom = app.getParameter("axiom");
  331.     int num = 1;
  332.     while (true) {
  333.         String pred = app.getParameter("pred"+num);
  334.         String succ = app.getParameter("succ"+num);
  335.         if (pred == null || succ == null) {
  336.         break;
  337.         }
  338.         rules.addElement(new CLSRule(pred, succ,
  339.                      app.getParameter("lContext"+num),
  340.                      app.getParameter("rContext"+num)));
  341.         num++;
  342.     }
  343.     currentPath = new StringBuffer(axiom);
  344.     level = 0;
  345.     }
  346.  
  347.     public int getLevel() {
  348.     return level;
  349.     }
  350.  
  351.     StringBuffer currentPath;
  352.  
  353.     public synchronized String getPath() {
  354.     return ((currentPath == null) ? null : currentPath.toString());
  355.     }
  356.  
  357.     private synchronized void setPath(StringBuffer path) {
  358.     currentPath = path;
  359.     level++;
  360.     }
  361.  
  362.     public void generate() {
  363.     StringBuffer newPath = new StringBuffer();
  364.     int pos = 0;
  365.     while (pos < currentPath.length()) {
  366.         CLSRule rule = findRule(pos);
  367.         if (rule == null) {
  368.         newPath.append(currentPath.charAt(pos));
  369.         pos++;
  370.         } else {
  371.         newPath.append(rule.succ);
  372.         pos += rule.pred.length();
  373.         }
  374.     }
  375.     setPath(newPath);
  376.     }
  377.  
  378.     public CLSRule findRule(int pos) {
  379.     for (int i = 0; i < rules.size(); i++) {
  380.         CLSRule rule = (CLSRule) rules.elementAt(i);
  381.         if (rule.matches(currentPath, pos)) {
  382.         return rule;
  383.         }
  384.     }
  385.     return null;
  386.     }
  387. }
  388.  
  389. /**
  390.  * A Context sensitive L-System production rule.
  391.  *
  392.  * This class encapsulates a production rule for a Context sensitive
  393.  * L-System (pred, succ, lContext, rContext).
  394.  * The matches() method, however, does not (yet) verify the lContext
  395.  * and rContext parts of the rule.
  396.  *
  397.  * @author     Jim Graham
  398.  * @version     1.1f, 27 Mar 1995
  399.  */
  400. class CLSRule {
  401.     String pred;
  402.     String succ;
  403.     String lContext;
  404.     String rContext;
  405.  
  406.     public CLSRule(String p, String d, String l, String r) {
  407.     pred = p;
  408.     succ = d;
  409.     lContext = l;
  410.     rContext = r;
  411.     }
  412.  
  413.     public boolean matches(StringBuffer sb, int pos) {
  414.     if (pos + pred.length() > sb.length()) {
  415.         return false;
  416.     }
  417.     char cb[] = new char[pred.length()];
  418.     sb.getChars(pos, pos + pred.length(), cb, 0);
  419.     return pred.equals(new String(cb));
  420.     }
  421. }
  422.