package fusionOptics.pointSpread;

import java.util.List;

import cache.randomAccessCache.RACache;
import cache.randomAccessCache.RACacheService;
import fusionOptics.MinervaOpticsSettings;
import fusionOptics.Util;
import fusionOptics.interfaces.Absorber;
import fusionOptics.optics.Box;
import fusionOptics.pointSpread.PSFGrid;
import fusionOptics.pointSpread.PSFStatsSourceInterpolation;
import fusionOptics.pointSpread.PointSpreadFunction;

import binaryMatrixFile.BinaryMatrixFile;

import oneLiners.OneLiners;

/** Generate images from PSF interpolation generated by GeneratePSFInterpolationExample  */
public class PSFImagingExample {
	
	final static String outPath = MinervaOpticsSettings.getAppsOutputPath() + "/rayTracing/imgTest";
	
	//Grids as used in SimpleImaging
	final static String psfSet = "imgTest";  //should match the one in GeneratePSFInterpolationExample
	
	final static double imageX[] = OneLiners.linSpace(-0.015, 0.015, 500);
	final static double imageY[] = OneLiners.linSpace(-0.015, 0.015, 500);
		
	public static void main(String[] args) {
		PSFGrid psfGrid = new PSFGrid(psfSet);
		
		PSFStatsSourceInterpolation psfInterp = new PSFStatsSourceInterpolation(psfGrid);
		
		reimageGrid(psfInterp);
		//if(true)return;
		
		Box box = new Box("box", new double[]{ 0, 0, 0}, 0.200, 0.200, 0.200, null, Absorber.ideal());
		Util.rotateOnX(box, new double[]{0,0,0}, 10*Math.PI/180);
		Util.rotateOnY(box, new double[]{0,0,0}, -30*Math.PI/180);
		Util.rotateOnZ(box, new double[]{0,0,0}, 45*Math.PI/180);
		
		reimage(psfInterp, Util.drawingToPoints(box.draw(), 0.0001));
		
	}
	
	public static void reimage(PSFStatsSourceInterpolation psfInterp, double obj[][]){
		
		double image[][] =  new double[imageX.length][imageY.length];
		
		for(int i=0; i < obj.length; i++) {
			PointSpreadFunction psf = psfInterp.getInterpolatedPSF(obj[i][0], obj[i][1], obj[i][2]);
			
			//PointSpreadFunction psf = psfColl.getPSFExact(new double[]{ gX[3], gY[iX], gZ[iY] });
			if(psf != null)
				psf.addToGrid(imageX, imageY, image, 1);
				
			System.out.print(".");
		}
		
		BinaryMatrixFile.mustWrite(outPath + "/reimageBox.bin", imageX, imageY, image, false);
		
	}
	
	public static void reimageGrid(PSFStatsSourceInterpolation psfInterp){
		double x[] = OneLiners.linSpace(-1.500, 1.500, 50);
		double y[] = OneLiners.linSpace(-1.500, 1.500, 50);
		
		double image[][] =  new double[imageX.length][imageY.length];
		
		for(int iX=0; iX < x.length; iX++) {
			for(int iY=0; iY < y.length; iY++) {
				PointSpreadFunction psf = psfInterp.getInterpolatedPSF(0.0, x[iX], y[iY]);
				
				//PointSpreadFunction psf = psfColl.getPSFExact(new double[]{ gX[3], gY[iX], gZ[iY] });
				if(psf != null)
					psf.addToGrid(imageX, imageY, image, 1);
			}	
			System.out.print(".");
		}
		
		BinaryMatrixFile.mustWrite(outPath + "/reimage.bin", imageX, imageY, image, false);
		
	}		
}
