import ij.*;
import ij.plugin.filter.PlugInFilter;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import java.util.*;

/** This plugin computes the gradient of an image in polar coordinates.
Bob Dougherty 3/23/05
 */
/*	License:
	Copyright (c) 2005, OptiNav, Inc.
	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 OptiNav, Inc. 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.
*/
public class Polar_Gradient implements PlugInFilter {

	ImagePlus imp;
	boolean canceled = false;
	static int[] kernelX = new int[]{-1,0,1,-2,0,2,-1,0,1};
	static int[] kernelY = new int[]{1,2,1,0,0,0,-1,-2,-1};
	double centX,centY;
	int hOld,wOld;

	public int setup(String arg, ImagePlus imp) {
		if (IJ.versionLessThan("1.32j"))
			return DONE;
		this.imp = imp;
		return DOES_32;
	}

	public void run(ImageProcessor ip) {

		int numSlices = imp.getStackSize();
		ImageStack stack = imp.getStack();
		int w = stack.getWidth();
		int h = stack.getHeight();

		//Get the center of the coordinate system
		if (!getCenter(w,h)) return;

		//Create new stacks for the output.
        ImageStack imsCirc = new ImageStack(w,h);
        ImageStack imsRad = new ImageStack(w,h);

        //Go through the slices of the input stack.
		for (int i = 0; i < numSlices; i++){

			//Get a slice and make copies of the pixel arrays.
 			ImageProcessor ipSlice = stack.getProcessor(i+1);
 			float[] gradX = (float[])ipSlice.getPixelsCopy();
  			float[] gradY = (float[])ipSlice.getPixelsCopy();

 			//Put the pixel arrays into image processors for the convolutions.
 			ImageProcessor ipGradX = new FloatProcessor(w,h);
 			ipGradX.setPixels(gradX);
  			ImageProcessor ipGradY = new FloatProcessor(w,h);
 			ipGradY.setPixels(gradY);

  			//Evaluate the gradients.
  			ipGradX.convolve3x3(kernelX);
  			ipGradY.convolve3x3(kernelY);

			//Make places for the results.
			FloatProcessor ipCirc = new FloatProcessor(w,h);
			FloatProcessor ipRad = new FloatProcessor(w,h);
			float[] circ = (float[])ipCirc.getPixels();
			float[] rad = (float[])ipRad.getPixels();

			//Compute the gradients
			for (int y = 0; y < h; y++){
				for (int x = 0; x < w; x++){
					int index = x + w*y;
					double cos = 1;
					double sin = 0;
					double r = Math.sqrt((x - centX)*(x - centX) + (y - centY)*(y - centY));
					if(r != 0){
						sin = -(y - centY)/(8*r);
						cos = (x - centX)/(8*r);
					}
					double gx = gradX[index];
					double gy = gradY[index];
					circ[index] = (float)(cos*gy - sin*gx);
					rad[index] = (float)(cos*gx + sin*gy);

					//circ[index] = (float)Math.sqrt(circ[index]*circ[index]);
					//rad[index] = (float)Math.sqrt(rad[index]*rad[index]);
				}
			}

			//Put the results in the destination stacks.
			ipCirc.setMinAndMax(0,0);
			ipRad.setMinAndMax(0,0);
			imsCirc.addSlice("Circ",ipCirc);
			imsRad.addSlice("Rad",ipRad);
		}

		// Create new images using the new stacks.
		ImagePlus impCirc = new ImagePlus("Circ",imsCirc);
		ImagePlus impRad = new ImagePlus("Rad",imsRad);
        impCirc.setStack(null,imsCirc);
        impRad.setStack(null,imsRad);

		// Display the new stacks.
		impCirc.show();
		impRad.show();
	}

	boolean getCenter(int w, int h) {
		centX = (double)Prefs.get("polar_gradient.centX", (w-1.)/2);
		centY = (double)Prefs.get("polar_gradient.centY", (h-1.)/2);
		hOld = (int)Prefs.get("polar_gradient.hOld", 0);
		wOld = (int)Prefs.get("polar_gradient.wOld", 0);
		if((h!=hOld)||(w!=wOld)){
			centX = (w-1.)/2;
			centY = (h-1.)/2;
		}
		GenericDialog gd = new GenericDialog("Polar Gradient...", IJ.getInstance());
		gd.addNumericField("Horizontal center, pixels", centX, 2);
		gd.addNumericField("Vertical center, pixels", centY, 2);
		gd.showDialog();
		if (gd.wasCanceled()) {
			return false;
		}
		centX = gd.getNextNumber();
		centY = gd.getNextNumber();
		Prefs.set("polar_gradient.centX", centX);
		Prefs.set("polar_gradient.centY", centY);
		Prefs.set("polar_gradient.wOld", w);
		Prefs.set("polar_gradient.hOld", h);
		return true;
	}
}


