package org.cocos2d.actions.grid;

import org.cocos2d.cocoa.CCGeometry.CCPoint;
import org.cocos2d.cocoa.CCGeometry.CCSize;
import org.cocos2d.support.CCPointExtension;
import org.cocos2d.types.CCVertex3D;

/** CCTwirl action */
public class CCTwirl extends CCGrid3DAction {
	/** twirl center */
	CCPoint	position = new CCPoint();

	int		twirls;
	/** amplitude */
	float	amplitude;
	/** amplitude rate */
	float	amplitudeRate;
	

	/** creates the action with center position, number of twirls, amplitude, a grid size and duration */
	public static CCTwirl action(CCPoint pos, int t, float amp, CCSize gridSize, float d) {
		return new CCTwirl(pos, t, amp, gridSize, d);
	}

	/** initializes the action with center position, number of twirls, amplitude, a grid size and duration */
	public CCTwirl(CCPoint pos, int t, float amp, CCSize gSize, float d) {
		super(gSize, d);
			position.setPoint(pos);
			twirls = t;
			amplitude = amp;
			amplitudeRate = 1.0f;
	}

	@Override
	public void update (float time) {
		int i, j;
		final CCPoint c = position;

		CCPoint	d = new CCPoint();
		
		for( i = 0; i < (gridSize.width+1); i++ ) {
			for( j = 0; j < (gridSize.height+1); j++ ) {
				CCVertex3D	v = originalVertex(CCPointExtension.ccp(i,j));
				
				CCPoint	avg = CCPointExtension.ccp(i-(gridSize.width/2.0f), j-(gridSize.height/2.0f));
				float r = CCPointExtension.ccpLength( avg );
				
				float amp = 0.1f * amplitude * amplitudeRate;
				float a = (float)(r * Math.cos(Math.PI/2.0f + time * Math.PI * twirls * 2 ) * amp);
				
				
				d.x = (float)(Math.sin(a) * (v.y-c.y) + Math.cos(a) * (v.x-c.x));
				d.y = (float)(Math.cos(a) * (v.y-c.y) - Math.sin(a) * (v.x-c.x));
				
				v.x = c.x + d.x;
				v.y = c.y + d.y;
				
				setVertex(CCPointExtension.ccp(i,j), v);
			}
		}
	}

	@Override
	public CCTwirl copy() {
		CCTwirl copy = new CCTwirl(position, twirls, amplitude, gridSize, duration);
		return copy;
	}

}
