/*
 *  HexAutomatonCanvas.
 *  Copyright (C) 2002  Frank Buß (fb@frank-buss.de)
 *
 *  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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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.
 *
 *  You can get the GNU General Public License at
 *  http://www.gnu.org/licenses/gpl.html
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;

/**
 * Hex cellular automaton canvas.
 *
 * @author      Frank Buß
 * @see step() for the rules for this CA.
 */
public class HexAutomatonCanvas
	extends Canvas
	implements ImageProducer, MouseListener, MouseMotionListener {

	/**
	 * Width of the CA state array.
	 */
	private final static int width = 128;

	/**
	 * Height of the CA state array.
	 */
	private final static int height = 128;

	/**
	 * Current CA state array.
	 */
	private byte current[];

	/**
	 * Destination CA state array, used by step(), swapped with 'current', after
	 * filled.
	 */
	private byte next[];

	/**
	 * Display with and height for one CA cell.
	 */
	private final static int zoom = 16;

	/**
	 * Colors for every state.
	 */
	private final static int colors[] = { 0, 0x00ffff, 0xffff00, 0xffffff };

	/**
	 * Image buffer.
	 */
	private final int pixels[];

	/**
	 * ColorModel for the pixels array.
	 */
	private final ColorModel cm =
		new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF);

	/**
	 * Image for displaying the CA.
	 */
	private Image image;

	/**
	 * Reference to the consumer of the image for displaying the CA.
	 */
	private ImageConsumer consumer;

	/**
	 * Creates a new automaton canvas.
	 */
	public HexAutomatonCanvas() {
		// init arrays
		current = new byte[width * height];
		next = new byte[width * height];
		pixels = new int[width * height * zoom * zoom];

		// add listener
		addMouseListener(this);
		addMouseMotionListener(this);

		// init CA
		init();

		// create rendering image with this as ImageProducer
		image = createImage(this);
	}

	/**
	 * Clears the CA array and initialized it with my serialized initials.
	 */
	public void init() {
		for (int i = 0; i < width * height; i++)
			current[i] = 0;

		// spinning emitter
		current[width * 20 + 20] = 2;
		current[width * 20 + 21] = 1;
		current[width * 21 + 20] = 1;
		current[width * 22 + 19] = 1;
		current[width * 22 + 20] = 1;
		current[width * 23 + 19] = 2;
		current[width * 23 + 21] = 1;
		current[width * 24 + 19] = 1;
		current[width * 24 + 20] = 1;
		current[width * 25 + 20] = 2;
		current[width * 25 + 21] = 2;

		// random
		for (int x = 70; x < 120; x++) {
			for (int y = 70; y < 120; y++) {
				current[width * y + x] = (byte) (Math.random() * 3.0);
			}
		}
	}

	/**
	 * Calculate next CA step.
	 */
	public void step() {
		int adr = width + 1;
		for (int y = 1; y < height - 1; y++) {
			int ofs = y & 1;
			int inverseOfs = 1 - ofs;
			for (int x = 1; x < width - 1; x++) {
				// calculate number of states in cells around the center
				byte center = current[adr];
				int c0 = current[adr - ofs - width];
				int c1 = current[adr + inverseOfs - width];
				int c2 = current[adr + 1];
				int c3 = current[adr + inverseOfs + width];
				int c4 = current[adr - ofs + width];
				int c5 = current[adr - 1];
				int s0 = 0;
				if (c0 == 0)
					s0++;
				if (c1 == 0)
					s0++;
				if (c2 == 0)
					s0++;
				if (c3 == 0)
					s0++;
				if (c4 == 0)
					s0++;
				if (c5 == 0)
					s0++;
				int s1 = 0;
				if (c0 == 1)
					s1++;
				if (c1 == 1)
					s1++;
				if (c2 == 1)
					s1++;
				if (c3 == 1)
					s1++;
				if (c4 == 1)
					s1++;
				if (c5 == 1)
					s1++;
				int s2 = 0;
				if (c0 == 2)
					s2++;
				if (c1 == 2)
					s2++;
				if (c2 == 2)
					s2++;
				if (c3 == 2)
					s2++;
				if (c4 == 2)
					s2++;
				if (c5 == 2)
					s2++;
				int s3 = 0;
				if (c0 == 3)
					s3++;
				if (c1 == 3)
					s3++;
				if (c2 == 3)
					s3++;
				if (c3 == 3)
					s3++;
				if (c4 == 3)
					s3++;
				if (c5 == 3)
					s3++;

				// calculate next state
				byte result = center;
				if (s1 == 0 && s2 == 1 && center == 0) {
					result = 2;
				} else if (s1 == 1 && s2 == 1) {
					result = 1;
				} else if (s2 == 2) {
					result = 1;
				} else if (s2 == 3) {
					result = 2;
				} else {
					result = 0;
				}

				// set next state
				next[adr++] = result;
			}
			adr += 2;
		}

		// swap buffers
		byte tmp[] = next;
		next = current;
		current = tmp;
	}

	/**
	 * Show current CA state array.
	 * @see java.awt.Component#update(Graphics)
	 */
	synchronized public void update(Graphics g) {
		// copy to pixels
		int adr = width + 1;
		for (int y = 1; y < height - 1; y++) {
			int adr2 = zoom * zoom * width * y + zoom - zoom / 2 * (y & 1);
			for (int x = 1; x < width - 1; x++) {
				int c = colors[current[adr++]];
				int i = adr2;
				for (int cy = 0; cy < zoom; cy++) {
					for (int cx = 0; cx < zoom; cx++) {
						pixels[i++] = c;
					}
					i += (width - 1) * zoom;
				}
				adr2 += zoom;
			}
			adr += 2;
		}

		// draw
		if (consumer != null)
			startProduction(consumer);
		g.drawImage(image, 0, 0, null);
	}

	/**
	 * Set states.
	 * @param x x coordinate in the state array.
	 * @param y y coordinate in the state array.
	 * @param pixel true, if state should be set, false otherwise.
	 */
	private void mouseCellAction(int x, int y, boolean pixel) {
		x /= zoom;
		y /= zoom;
		if (x >= 0 && x < width && y >= 0 && y < height) {
			if (pixel) {
				current[x + y * width]--;
			} else {
				current[x + y * width]++;
			}
			if (current[x+y*width]<0)current[x+y*width]=0;
			if (current[x+y*width]>2)current[x+y*width]=2;
		}
		repaint();
	}

	// Java specific code (listeners etc.)

	/**
	 * @see java.awt.Component#getPreferredSize()
	 */
	public Dimension getPreferredSize() {
		return new Dimension(width * zoom, height * zoom);
	}

	/**
	 * @see java.awt.Component#getMinimumSize()
	 */
	public Dimension getMinimumSize() {
		return getPreferredSize();
	}

	/**
	 * @see java.awt.Component#getMaximumSize()
	 */
	public Dimension getMaximumSize() {
		return getPreferredSize();
	}

	/**
	 * @see java.awt.image.ImageProducer#addConsumer(java.awt.image.ImageConsumer)
	 */
	public void addConsumer(ImageConsumer c) {
	}

	/**
	 * @see java.awt.image.ImageProducer#isConsumer(java.awt.image.ImageConsumer)
	 */
	public boolean isConsumer(ImageConsumer consumer) {
		return consumer != null;
	}

	/**
	 * @see java.awt.image.ImageProducer#removeConsumer(java.awt.image.ImageConsumer)
	 */
	public void removeConsumer(ImageConsumer consumer) {
	}

	/**
	 * @see java.awt.image.ImageProducer#startProduction(java.awt.image.ImageConsumer)
	 */
	public void startProduction(ImageConsumer c) {
		if (c != null)
			consumer = c;
		if (consumer != null) {
			consumer.setDimensions(width * zoom, height * zoom);
			consumer.setProperties(null);
			consumer.setColorModel(cm);
			consumer.setHints(
				ImageConsumer.TOPDOWNLEFTRIGHT
					| ImageConsumer.COMPLETESCANLINES
					| ImageConsumer.SINGLEPASS
					| ImageConsumer.SINGLEFRAME);
			consumer.setPixels(
				0,
				0,
				width * zoom,
				height * zoom,
				cm,
				pixels,
				0,
				width * zoom);
			consumer.imageComplete(ImageConsumer.SINGLEFRAMEDONE);
		}
	}

	/**
	 * @see java.awt.image.ImageProducer#requestTopDownLeftRightResend(java.awt.image.ImageConsumer)
	 */
	public void requestTopDownLeftRightResend(ImageConsumer consumer) {
	}

	/**
	 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
	 */
	public void mouseClicked(MouseEvent e) {
	}

	/**
	 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
	 */
	public void mousePressed(MouseEvent e) {
		mouseCellAction(
			e.getX(),
			e.getY(),
			(e.getModifiers() & MouseEvent.META_MASK) > 0);
	}

	/**
	 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
	 */
	public void mouseReleased(MouseEvent e) {
	}

	/**
	 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
	 */
	public void mouseEntered(MouseEvent e) {
	}

	/**
	 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
	 */
	public void mouseExited(MouseEvent e) {
	}

	/**
	 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
	 */
	public void mouseDragged(MouseEvent e) {
		mouseCellAction(
			e.getX(),
			e.getY(),
			(e.getModifiers() & MouseEvent.META_MASK) > 0);
	}
	/**
	 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
	 */
	public void mouseMoved(MouseEvent e) {
	}
}
