/*
 * FSDefineMorphShape.java
 * Transform
 * 
 * Copyright (c) 2001-2008 Flagstone Software Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 *  * Neither the name of Flagstone Software Ltd. nor the names of its contributors 
 *    may be used to endorse or promote products derived from this software 
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.flagstone.transform;

import java.util.*;

/**
 * FSDefineMorphShape defines a shape that will morph from one form into
 * another.
 * 
 * <p>
 * Only the start and end shapes are defined the Flash Player will perform the
 * interpolation that transforms the shape at each staging in the morphing
 * process.
 * </p>
 * 
 * <p>
 * Morphing can be applied to any shape, however there are a few restrictions:
 * </p>
 * 
 * <ul>
 * <li>The start and end shapes must have the same number of edges (FSLine and
 * FSCurve objects).</li>
 * <li>The fill style (Solid, Bitmap or Gradient) must be the same in the start
 * and end shape.</li>
 * <li>If a bitmap fill style is used then the same image must be used in the
 * start and end shapes.</li>
 * <li>If a gradient fill style is used then the gradient must contain the same
 * number of points in the start and end shape.</li>
 * <li>The start and end shape must contain the same set of FSShapeStyle
 * objects.</li>
 * </ul>
 * 
 * <p>
 * To perform the morphing of a shape the shape is placed in the display list
 * using a FSPlaceObject2 object. The ratio attribute in the FSPlaceObject2
 * object defines the progress of the morphing process. The ratio ranges between
 * 0.0 and 1.0 where 0 represents the start of the morphing process and 1.0, the
 * end.
 * </p>
 * 
 * <table class="datasheet">
 * 
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>type</td>
 * <td>Identifies the data structure when it is encoded. The type attribute is
 * read-only and may be used when iterating through the objects in an FSMovie
 * object to identify the object class without using run-time type checking.</td>
 * </tr>
 * 
 * <tr>
 * <td>identifier</td>
 * <td>An unique identifier for this object in the range 1..65535.</td>
 * </tr>
 * 
 * <tr>
 * <td>startBounds</td>
 * <td>A rectangle (FSBounds) defining the bounding area in which the shape is
 * drawn at the start of the morph process.</td>
 * </tr>
 * 
 * <tr>
 * <td>endBounds</td>
 * <td>A rectangle (FSBounds) defining the bounding area in which the shape is
 * drawn at the end of the morph process.</td>
 * </tr>
 * 
 * <tr>
 * <td>fillStyles</td>
 * <td>An array of fill styles.</td>
 * </tr>
 * 
 * <tr>
 * <td>lineStyles</td>
 * <td>An array of line styles.</td>
 * </tr>
 * 
 * <tr>
 * <td>startShape</td>
 * <td>An FSShape object containing the shape records (FSLine, FSCurve and
 * FSShapeStyle objects) that describe the shape at the start of the morphing
 * process.</td>
 * </tr>
 * 
 * <tr>
 * <td>endShape</td>
 * <td>The shape at the end of the morphing process containing the FSLine and
 * FSCurve objects that define the edges of the shape.FSShapeStyle objects may
 * only be included if they are used to move the current point and may <b>not</b>
 * change the style being used to draw the shape.</td>
 * </tr>
 * </table>
 * 
 * <p>
 * The edges may change their type when a shape is morphed. Straight edges can
 * become curves and vice versa.
 * </p>
 * 
 * <h1 class="datasheet">Examples</h1>
 * 
 * <p>
 * This simple example morphs a rectangle into a square. While this example is
 * trivial it illustrates how the FSDefineMorphShape class is used.
 * </p>
 * 
 * <p>
 * This rectangle is 200 twips wide and 100 twips high, drawing using a black
 * outline 1 twip wide and filled with a transparent red colour. The square is
 * 150 x 150 twips. The origin of the shape is at the bottom left corner of the
 * rectangle.
 * </p>
 * 
 * <pre>
 *  // Create the bounding rectangle for the start shape (rectangle).
 *  FSBounds startBounds = new FSBounds(0, 0, 200, 100);
 * 
 *  // Create the bounding rectangle for the end shape (square).
 *  FSBounds endBounds = new FSBounds(0, 0, 150, 150);
 * 
 *  // Define the styles for the shape.
 * 
 *  ArrayList fillStyles = new ArrayList();
 *  ArrayList lineStyles = new ArrayList();
 * 
 *  fillStyles.push_back(new FSSolidFill(new FSColor((FSColorTable.red)));
 * 
 *  lineStyles.push_back(new FSSolidLine(1, FColor.black()));
 * 
 *  // Draw the rectangle.
 * 
 *  FSShape rectangle = new FSShape();
 * 
 *  rectangle.add(new FSShapeStyle(1, 1, 0, 0, 0));
 *  rectangle.add(new FSLine(200,0));
 *  rectangle.add(new FSLine(0,100));
 *  rectangle.add(new FSLine(-200,0));
 *  rectangle.add(new FSLine(0,-100));
 * 
 *  // Draw the square.
 * 
 *  FSShape square = new FSShape();
 * 
 *  square.add(new FSLine(150,0));
 *  square.add(new FSLine(0,150));
 *  square.add(new FSLine(-150,0));
 *  square.add(new FSLine(0,-150));
 * 
 *  FSDefineMorphShape shape = FSDefineMorphShape(movie.newIdentifier(), startBounds, endBounds, fillStyles, lineStyles, rectangle, square);
 * 
 *  // The morphing process is controlled by the FSPlaceObject2 class using the ratio attribute.
 *  // Place the shape on layer 1 of the display list at coordinates (0,0).
 * 
 *  movie.add(new FSPlaceObject2(shape.getIdentifier(), 1, 0.0, 0,0));
 *  movie.add(new FSShowFrame());
 * 
 *  // Morph the shape over 5 steps without changing its location.
 * 
 *  for (float i=0.2; i&lt;1.0; i+= 0.2)
 *  {
 *  movie.add(new FSPlaceObject2(1, i, 0,0));
 *  movie.add(new FSShowFrame());
 *  }
 * </pre>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSDefineMorphShape class represents the DefineMorphShape tag from the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 3.
 * </p>
 */
public class FSDefineMorphShape extends FSDefineObject
{
	private FSBounds startBounds = null;
	private FSBounds endBounds = null;
	private ArrayList fillStyles = null;
	private ArrayList lineStyles = null;
	private FSShape startShape = null;
	private FSShape endShape = null;

	/**
	 * Construct an FSDefineJPEGImage object, initialising it with values decoded
	 * from an encoded object.
	 * 
	 * @param coder
	 *            an FSCoder containing the binary data.
	 */
	public FSDefineMorphShape(FSCoder coder)
	{
		super(DefineMorphShape, 0);
		decode(coder);
	}

	/**
	 * Constructs an FSDefineMorphShape object.
	 * 
	 * @param anIdentifier
	 *            an unique identifier for this object.
	 * @param startBounds
	 *            the bounding rectangle enclosing the start shape.
	 * @param endBounds
	 *            the bounding rectangle enclosing the end shape.
	 * @param fillStyleArray
	 *            an array of FSMorphSolidFill, FSMorphBitmapFill and
	 *            FSMorphGradientFill objects.
	 * @param lineStyleArray
	 *            an array of FSMorphLineStyle objects.
	 * @param startShape
	 *            the shape at the start of the morphing process.
	 * @param endShape
	 *            the shape at the end of the morphing process.
	 */
	public FSDefineMorphShape(int anIdentifier, FSBounds startBounds,
								FSBounds endBounds, ArrayList fillStyleArray,
								ArrayList lineStyleArray, FSShape startShape,
								FSShape endShape)
	{
		super(DefineMorphShape, anIdentifier);
		setStartBounds(startBounds);
		setEndBounds(endBounds);
		setFillStyles(fillStyleArray);
		setLineStyles(lineStyleArray);
		setStartShape(startShape);
		setEndShape(endShape);
	}

	/**
	 * Constructs an FSDefineJPEGImage object by copying values from an existing
	 * object.
	 * 
	 * @param obj
	 *            an FSDefineJPEGImage object.
	 */
	public FSDefineMorphShape(FSDefineMorphShape obj)
	{
		super(obj);
		startBounds = new FSBounds(obj.startBounds);
		endBounds = new FSBounds(obj.endBounds);

		fillStyles = new ArrayList();

		for (Iterator i = obj.fillStyles.iterator(); i.hasNext();)
			fillStyles.add(((FSFillStyle) i.next()).clone());

		lineStyles = new ArrayList();

		for (Iterator i = obj.lineStyles.iterator(); i.hasNext();)
			lineStyles.add(((FSLineStyle) i.next()).clone());

		startShape = new FSShape(obj.startShape);
		endShape = new FSShape(obj.endShape);
	}

	/**
	 * Add a FSSolidLine object to the array of line styles.
	 * 
	 * @param aLineStyle
	 *            and FSSolidLine object.
	 */
	public void add(FSLineStyle aLineStyle)
	{
		lineStyles.add(aLineStyle);
	}

	/**
	 * Add the fill style object to the array of fill styles.
	 * 
	 * @param aFillStyle
	 *            an FSFillStyle object.
	 */
	public void add(FSFillStyle aFillStyle)
	{
		fillStyles.add(aFillStyle);
	}

	/**
	 * Gets the FSBounds object that defines the bounding rectangle enclosing
	 * the start shape.
	 * 
	 * @return the bounds of the start shape.
	 */
	public FSBounds getStartBounds()
	{
		return startBounds;
	}

	/**
	 * Gets the FSBounds object that defines the bounding rectangle enclosing
	 * the end shape.
	 * 
	 * @return the bounds of the end shape.
	 */
	public FSBounds getEndBounds()
	{
		return endBounds;
	}

	/**
	 * Gets the array of FSMorphSolidFill, FSMorphBitmapFill and
	 * FSMorphGradientFill objects that define the fill styles for the shapes.
	 * 
	 * @return the array morph fill styles.
	 */
	public ArrayList getFillStyles()
	{
		return fillStyles;
	}

	/**
	 * Gets the array of FSMorphLineStyle objects that define the line styles
	 * for the shapes.
	 * 
	 * @return the array morph line styles.
	 */
	public ArrayList getLineStyles()
	{
		return lineStyles;
	}

	/**
	 * Gets the starting shape.
	 * 
	 * @return the start shape.
	 */
	public FSShape getStartShape()
	{
		return startShape;
	}

	/**
	 * Gets the ending shape.
	 * 
	 * @return the end shape.
	 */
	public FSShape getEndShape()
	{
		return endShape;
	}

	/**
	 * Sets the starting bounds of the shape.
	 * 
	 * @param aBounds
	 *            the bounding rectangle enclosing the start shape.
	 */
	public void setStartBounds(FSBounds aBounds)
	{
		startBounds = aBounds;
	}

	/**
	 * Sets the ending bounds of the shape.
	 * 
	 * @param aBounds
	 *            the bounding rectangle enclosing the end shape.
	 */
	public void setEndBounds(FSBounds aBounds)
	{
		endBounds = aBounds;
	}

	/**
	 * Sets the array of morph fill styles.
	 * 
	 * @param anArray
	 *            an array of FSMorphSolidFill, FSMorphBitmapFill and
	 *            FSMorphGradientFill objects.
	 */
	public void setFillStyles(ArrayList anArray)
	{
		fillStyles = anArray;
	}

	/**
	 * Sets the array of morph line styles.
	 * 
	 * @param anArray
	 *            an array of FSMorphLineStyle objects.
	 */
	public void setLineStyles(ArrayList anArray)
	{
		lineStyles = anArray;
	}

	/**
	 * Sets the starting shape.
	 * 
	 * @param aShape
	 *            the shape at the start of the morphing process.
	 */
	public void setStartShape(FSShape aShape)
	{
		startShape = aShape;
	}

	/**
	 * Sets the ending shape.
	 * 
	 * @param aShape
	 *            the shape at the end of the morphing process.
	 */
	public void setEndShape(FSShape aShape)
	{
		endShape = aShape;
	}

	public Object clone()
	{
		FSDefineMorphShape anObject = (FSDefineMorphShape) super.clone();

		anObject.startBounds = (startBounds != null) ? (FSBounds) startBounds
						.clone() : null;
		anObject.endBounds = (endBounds != null) ? (FSBounds) endBounds.clone()
						: null;

		anObject.fillStyles = new ArrayList();

		for (Iterator i = fillStyles.iterator(); i.hasNext();)
			anObject.fillStyles.add(((FSFillStyle) i.next()).clone());

		anObject.lineStyles = new ArrayList();

		for (Iterator i = lineStyles.iterator(); i.hasNext();)
			anObject.lineStyles.add(((FSLineStyle) i.next()).clone());

		anObject.startShape = (startShape != null) ? (FSShape) startShape
						.clone() : null;
		anObject.endShape = (endShape != null) ? (FSShape) endShape.clone()
						: null;

		return anObject;
	}

	public boolean equals(Object anObject)
	{
		boolean result = false;

		if (super.equals(anObject))
		{
			FSDefineMorphShape typedObject = (FSDefineMorphShape) anObject;

			if (startBounds != null)
				result = startBounds.equals(typedObject.startBounds);
			else
				result = startBounds == typedObject.startBounds;

			if (endBounds != null)
				result = result && endBounds.equals(typedObject.endBounds);
			else
				result = result && endBounds == typedObject.endBounds;

			if (fillStyles != null)
				result = result && fillStyles.equals(typedObject.fillStyles);
			else
				result = result && fillStyles == typedObject.fillStyles;

			if (lineStyles != null)
				result = result && lineStyles.equals(typedObject.lineStyles);
			else
				result = result && lineStyles == typedObject.lineStyles;

			if (startShape != null)
				result = result && startShape.equals(typedObject.startShape);
			else
				result = result && startShape == typedObject.startShape;

			if (endShape != null)
				result = result && endShape.equals(typedObject.endShape);
			else
				result = result && endShape == typedObject.endShape;
		}
		return result;
	}

	public void appendDescription(StringBuffer buffer, int depth)
	{
		buffer.append(name());

		if (depth > 0)
		{
			buffer.append(": { ");
			Transform.append(buffer, "startBounds", startBounds, depth);
			Transform.append(buffer, "endBounds", endBounds, depth);
			Transform.append(buffer, "fillStyles", fillStyles, depth);
			Transform.append(buffer, "lineStyles", lineStyles, depth);
			Transform.append(buffer, "startShape", startShape, depth);
			Transform.append(buffer, "endShape", endShape, depth);
			buffer.append("}");
		}
	}

	public int length(FSCoder coder)
	{
		int numberOfFillBits = FSCoder.size(fillStyles.size(), false);
		int numberOfLineBits = FSCoder.size(lineStyles.size(), false);

		super.length(coder);

		coder.context[FSCoder.TransparentColors] = 1;

		length += startBounds.length(coder);
		length += endBounds.length(coder);
		length += 4;

		length += (fillStyles.size() >= 255) ? 3 : 1;

		for (Iterator styleIterator = fillStyles.iterator(); styleIterator
						.hasNext();)
			length += ((FSTransformObject) styleIterator.next()).length(coder);

		length += (lineStyles.size() >= 255) ? 3 : 1;

		for (Iterator styleIterator = lineStyles.iterator(); styleIterator
						.hasNext();)
			length += ((FSTransformObject) styleIterator.next()).length(coder);

		coder.context[FSCoder.ArrayCountExtended] = 1;
		coder.context[FSCoder.NumberOfFillBits] = numberOfFillBits;
		coder.context[FSCoder.NumberOfLineBits] = numberOfLineBits;

		length += startShape.length(coder);

		// Number of Fill and Line bits is zero for end shape.
		coder.context[FSCoder.NumberOfFillBits] = 0;
		coder.context[FSCoder.NumberOfLineBits] = 0;

		length += endShape.length(coder);

		coder.context[FSCoder.ArrayCountExtended] = 0;
		coder.context[FSCoder.TransparentColors] = 0;

		return length;
	}

	public void encode(FSCoder coder)
	{
		int numberOfFillBits = FSCoder.size(fillStyles.size(), false);
		int numberOfLineBits = FSCoder.size(lineStyles.size(), false);

		super.encode(coder);

		coder.context[FSCoder.TransparentColors] = 1;

		startBounds.encode(coder);
		endBounds.encode(coder);

		int offsetStart = coder.getPointer();
		coder.writeWord(0, 4);

		if (fillStyles.size() >= 255)
		{
			coder.writeWord(0xFF, 1);
			coder.writeWord(fillStyles.size(), 2);
		} else
		{
			coder.writeWord(fillStyles.size(), 1);
		}

		for (Iterator styleIterator = fillStyles.iterator(); styleIterator
						.hasNext();)
			((FSTransformObject) styleIterator.next()).encode(coder);

		if (lineStyles.size() >= 255)
		{
			coder.writeWord(0xFF, 1);
			coder.writeWord(lineStyles.size(), 2);
		} else
		{
			coder.writeWord(lineStyles.size(), 1);
		}

		for (Iterator styleIterator = lineStyles.iterator(); styleIterator
						.hasNext();)
			((FSTransformObject) styleIterator.next()).encode(coder);

		coder.context[FSCoder.ArrayCountExtended] = 1;
		coder.context[FSCoder.NumberOfFillBits] = numberOfFillBits;
		coder.context[FSCoder.NumberOfLineBits] = numberOfLineBits;

		startShape.encode(coder);

		int offsetEnd = (coder.getPointer() - offsetStart) >> 3;
		int currentCursor = coder.getPointer();

		coder.setPointer(offsetStart);
		coder.writeWord(offsetEnd - 4, 4);
		coder.setPointer(currentCursor);

		// Number of Fill and Line bits is zero for end shape.

		coder.context[FSCoder.NumberOfFillBits] = 0;
		coder.context[FSCoder.NumberOfLineBits] = 0;

		endShape.encode(coder);

		coder.context[FSCoder.ArrayCountExtended] = 0;
		coder.context[FSCoder.TransparentColors] = 0;

		coder.endObject(name());
	}

	public void decode(FSCoder coder)
	{
		int fillStyleCount = 0;
		int lineStyleCount = 0;

		super.decode(coder);

		coder.context[FSCoder.TransparentColors] = 1;
		coder.context[FSCoder.ArrayCountExtended] = 1;

		int start = coder.getPointer() - 16;

		startBounds = new FSBounds(coder);
		endBounds = new FSBounds(coder);

		int offset = coder.readWord(4, false);
		int first = coder.getPointer();

		fillStyleCount = coder.readWord(1, false);

		if (coder.context[FSCoder.ArrayCountExtended] != 0
						&& fillStyleCount == 0xFF)
			fillStyleCount = coder.readWord(2, false);

		fillStyles = new ArrayList(fillStyleCount);

		for (int i = 0; i < fillStyleCount; i++)
		{
			switch (coder.scanWord(1, false))
			{
				case FSFillStyle.Solid:
					fillStyles.add(new FSMorphSolidFill(coder));
					break;
				case FSFillStyle.Linear:
					fillStyles.add(new FSMorphGradientFill(coder));
					break;
				case FSFillStyle.Radial:
					fillStyles.add(new FSMorphGradientFill(coder));
					break;
				case FSFillStyle.Tiled:
					fillStyles.add(new FSMorphBitmapFill(coder));
					break;
				case FSFillStyle.Clipped:
					fillStyles.add(new FSMorphBitmapFill(coder));
					break;
				case FSFillStyle.Unsmoothed_Tiled:
					fillStyles.add(new FSBitmapFill(coder));
					break;
				case FSFillStyle.Unsmoothed_Clipped:
					fillStyles.add(new FSBitmapFill(coder));
					break;
				default:
					break;
			}
		}

		lineStyleCount = coder.readWord(1, false);

		if (coder.context[FSCoder.ArrayCountExtended] != 0
						&& lineStyleCount == 0xFF)
			lineStyleCount = coder.readWord(2, false);

		lineStyles = new ArrayList(lineStyleCount);

		for (int i = 0; i < lineStyleCount; i++)
			lineStyles.add(new FSMorphSolidLine(coder));

		int bytesDecoded = (coder.getPointer() - first) >> 3;

		startShape = new FSShape(coder, offset - bytesDecoded);

		bytesDecoded = (coder.getPointer() - start) >> 3;

		endShape = new FSShape(coder, length - bytesDecoded);

		coder.context[FSCoder.TransparentColors] = 0;
		coder.context[FSCoder.ArrayCountExtended] = 0;

		coder.endObject(name());
	}
}
