
/*
 * Implementation of realistic camera model.
 * 2006 Chia-Kai Liang
 */

// realistic.cpp*
#include <fstream>
#include <cstring>
using namespace std;

#include "camera.h"
#include "film.h"
#include "paramset.h"
// Declarations
struct LensBall{
	float oz;
	float radius;
	float radius2;
	float stop;
	float stop2;
	float nRight;
	float nLeft;
	float nRatio;
	float nRatio2;
	bool isStop;
};
float finvsqrtf(float number) {
    long i;
    float x, y;
    const float f = 1.5F;
    x  = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;
    i  = 0x5f3759df - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( f - ( x * y * y ) );
    y  = y * ( f - ( x * y * y ) );
    return y;
}

float fsqrtf(float number) {
    long i;
    float x, y;
    const float f = 1.5F;
    x  = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;
    i  = 0x5f3759df - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( f - ( x * y * y ) );
    y  = y * ( f - ( x * y * y ) );
    return number * y;
}
// RealisticCamera Declarations
class RealisticCamera : public ProjectiveCamera {
public:
	// PerspectiveCamera Public Methods
	RealisticCamera(const string cameraFile, 
		const Transform &world2cam,
		const float Screen[4], 
		float hither, float yon,
		float sopen, float sclose,
		float lensr, float focald, float fov,
		Film *film);
	~RealisticCamera();
	float GenerateRay(const Sample &sample, Ray *) const;
private:
	bool ParseCameraParameter(const string cameraFile);
	int lensNumber;
	LensBall *lensBall;
};
// RealisticCamera Method Definitions
RealisticCamera::
    RealisticCamera(const string cameraFile, 
	    const Transform &world2cam,
		const float Screen[4], 
		float hither, float yon,
		float sopen, float sclose,
		float lensr, float focald, float fov, 
		Film *f)
	: ProjectiveCamera(world2cam,
		Orthographic(hither, yon),
	    //Perspective(fov, hither, yon),
		Screen, hither, yon, sopen, sclose,
		lensr, focald, f) {
	//Parse the camera file
	if(!ParseCameraParameter(cameraFile)){
		cerr << "Parse camera parameter file " << cameraFile << " failed" << endl;
		exit(1);
	}
}
float RealisticCamera::GenerateRay(const Sample &sample,
		Ray *ray) const {
	// Generate raster and camera samples
	Point Pras(sample.imageX, sample.imageY, 0);
	Point Pcamera;
	RasterToCamera(Pras, &Pcamera);
	ray->o = Pcamera;	
	// Set ray time value
	ray->time = Lerp(sample.time, ShutterOpen, ShutterClose);
	// Sample point on the final lens surface
	float lensU, lensV;
	ConcentricSampleDisk(sample.lensU, sample.lensV,
		                    &lensU, &lensV);
	lensU *= LensRadius;
	lensV *= LensRadius;
	ray->d = Vector(lensU - Pcamera.x, lensU - Pcamera.y, FocalDistance - Pcamera.z);
	// Calaulate cos^4(theta) weighting first
	float weighting = ray->d.z/fsqrtf(ray->d.LengthSquared());
	weighting = weighting*weighting*weighting*weighting;
	// Trace the ray through the lens system
	float d_norm2, invd_norm2, invd_norm;
	float t2, s2, s, o2, tca, t0;
	float c1, c2;
	Point P;
	for(int i = 0; i < lensNumber; i++){
		LensBall *lens = &lensBall[i];
		if(lens->isStop){
			// Calculate the intersection
			float t = (lens->oz - ray->o.z)/ray->d.z;
			float x = ray->o.x + t * ray->d.x;
			float y = ray->o.y + t * ray->d.y;
			// Check if the ray is inside the stop
			float r2 = x*x + y*y;
			if(r2 > lens->stop2){
				weighting = 0.f;
				break;
			}
		}
		else{
			// Calculate the intersection
			o2 = ray->o.x*ray->o.x + ray->o.y*ray->o.y + ray->o.z*ray->o.z;
			tca = -(ray->o.x*ray->d.x + ray->o.y*ray->d.y + ray->o.z*ray->d.z);
			d_norm2 = ray->d.x*ray->d.x + ray->d.y*ray->d.y + ray->d.z*ray->d.z;
			invd_norm2 = 1.f/d_norm2;
			invd_norm = fsqrtf(invd_norm2);
			t2 = tca*tca*invd_norm2;
			s2 = lens->radius2 - o2 + t2;
			s = fsqrtf(s2)*invd_norm;
			if(o2 > lens->radius2) t0 = tca*invd_norm2 - s;
			/*{
				//if(tca < 0) return false; // This should never happen
				//if(s2 < 0) return false; // This should never happen
				
				//if(t0 > ray->maxt) return false; // This should never happen
				if(t0 < ray->mint){
					t1 = tca*invd_norm2 + s;
					if(t1 < ray.mint)
						return false;
					else
						thit = t1;	
				} 
				float thit = t0;// This should never happen
			}*/
			else t0 = tca*invd_norm2 + s;
			P = ray->o + t0*ray->d;
			// Calculate the normal at the intersection
			Vector N(P.x, P.y, P.z - lens->oz);			
			// Calculate the refracted ray
			Vector I = Normalize(ray->d);
			c1 = -Dot(N, I);
			c2 = fsqrtf(1 - lens->nRatio2*(1 - c1*c1));
			Vector T = lens->nRatio*I + (lens->nRatio * c1 - c2)*N;
			// Update the ray origin and direction
			ray->d = T;
			ray->o = P;
			// Update the weighting if necessary
		}
	}
	// Post processing the ray
	ray->d = Normalize(ray->d);
	ray->mint = 0.f;
	ray->maxt = (ClipYon - ClipHither) / ray->d.z;
	CameraToWorld(*ray, ray);
	return weighting;
}
RealisticCamera::~RealisticCamera(){
	if(lensNumber != 0)
		delete []lensBall;
}
bool RealisticCamera::ParseCameraParameter(const string cameraFile){
	char *line = new char[256];
	const char *cameraFilename = cameraFile.c_str();
	ifstream fin;
	fin.open(cameraFilename, ios::in);
	if(!fin) return false;
	// Read the parameters as front to rear order
	vector<float> radiusV;
	vector<float> axposV;
	vector<float> NV;
	vector<float> apertureV;
	int count = 0;
	float rad, axpos, N, aperture;
	fin.getline(line, 256);
	while(!fin.eof()){
		//cerr << line << endl;
		if(!(line[0] == '#')){
			char *token;
			token = strtok(line, "\t");			
			rad = float(atof(token));
			token = strtok(NULL, "\t");
			axpos = float(atof(token));
			token = strtok(NULL, "\t");
			N = float(atof(token));
			token = strtok(NULL, "\t");
			aperture = float(atof(token));
			radiusV.push_back(rad);
			axposV.push_back(axpos);
			NV.push_back(N);
			apertureV.push_back(aperture);
			count++;
		}
		fin.getline(line, 256);
	}
	fin.close();
	delete []line;
	// Calculte the meaningful parameters
	lensNumber = count; 
	lensBall = new LensBall[lensNumber];
	float t_total = 0;
	int j = 0;
	for(int i = count-1; i>=0; i--){		
		t_total += axposV[i];
		lensBall[j].oz = t_total - radiusV[i];
		lensBall[j].radius = fabs(radiusV[i]);
		if(lensBall[j].radius == 0.f)
			lensBall[j].isStop = true;
		else
			lensBall[j].isStop = false;
		lensBall[j].radius2 = lensBall[j].radius*lensBall[j].radius;
		lensBall[j].stop = apertureV[i]/2.f;
		lensBall[j].stop2 = lensBall[j].stop*lensBall[j].stop;
		if(i == count) lensBall[j].nRight = 1.f;
		else lensBall[j].nRight = NV[i];
		if(i == 0) lensBall[j].nLeft = 1.f;
		else lensBall[j].nLeft = NV[i-1];
		lensBall[j].nRatio = lensBall[j].nRight/lensBall[j].nLeft;
		lensBall[j].nRatio2 = lensBall[j].nRatio*lensBall[j].nRatio;
		j++;
	}
	// Update _LensRadius_ and _FocalDistance_
	LensRadius = lensBall[0].stop;
	FocalDistance = axposV[lensNumber-1];
	return true;
}
extern "C" DLLEXPORT Camera *CreateCamera(const ParamSet &params,
		const Transform &world2cam, Film *film) {	
	// Extract camera parameter file
	string cameraFile = params.FindOneString("camera","cameras/dgauss.50mm.dat");
	// Extract common camera parameters from _ParamSet_
	float hither = max(1e-4f, params.FindOneFloat("hither", 1e-3f));
	float yon = min(params.FindOneFloat("yon", 1e30f), 1e30f);
	float shutteropen = params.FindOneFloat("shutteropen", 0.f);
	float shutterclose = params.FindOneFloat("shutterclose", 1.f);
	// Useless parameters
	float lensradius = params.FindOneFloat("lensradius", 0.f);
	float focaldistance = params.FindOneFloat("focaldistance", 1e30f);
	float frame = params.FindOneFloat("frameaspectratio",
		float(film->xResolution)/float(film->yResolution));
	float fov = params.FindOneFloat("fov", 90.);
	// Screen parameters are necessary now
	float screen[4];
	if (frame > 1.f) {
		screen[0] = -frame;
		screen[1] =  frame;
		screen[2] = -1.f;
		screen[3] =  1.f;
	}
	else {
		screen[0] = -1.f;
		screen[1] =  1.f;
		screen[2] = -1.f / frame;
		screen[3] =  1.f / frame;
	}
	int swi;
	const float *sw = params.FindFloat("screenwindow", &swi);
	if (sw && swi == 4)
		memcpy(screen, sw, 4*sizeof(float));	
	return new RealisticCamera(cameraFile, world2cam, screen, hither, yon,
		shutteropen, shutterclose, 
		lensradius, focaldistance, fov, 
		film);
}
