/******************************************************************************
 * Copyright 1986-2002 by mental images GmbH & Co.KG, Fasanenstr. 81, D-10623
 * Berlin, Germany. All rights reserved.
 ******************************************************************************
 * Created:	30.10.97
 * Module:	baseshader
 * Purpose:	base shaders for Phenomenon writers
 *
 * Exports:
 *	mib_dielectric
 *	mib_dielectric_version
 *
 * History:
 *
 * Description:
 *	Dielectric material
 *****************************************************************************/

#include <math.h>
#include <shader.h>


struct md {
	miColor		input;
	miColor		absorb;
	miScalar	refract;
	miScalar	ior;
};


DLLEXPORT int mib_dielectric_version(void) {return(1);}

DLLEXPORT miBoolean mib_dielectric(
	miColor		*result,
	miState		*state,
	struct md	*paras)
{
	miScalar	refract = *mi_eval_scalar(&paras->refract);
	miColor		inp, absorb;
	miVector	dir;
	miScalar	ior;

	if (refract == 0.0)
		*result = *mi_eval_color(&paras->input);
	else {
		ior = *mi_eval_scalar(&paras->ior);
		if (ior==0.0 || ior==1.0)
			mi_trace_transparent(result, state);
		else {
			mi_refraction_dir(&dir, state, 1.0, ior);
			mi_trace_refraction(result, state, &dir);
		}
		absorb     = *mi_eval_color(&paras->absorb);
		result->r *= exp(log(absorb.r) * state->dist);
		result->g *= exp(log(absorb.g) * state->dist);
		result->b *= exp(log(absorb.b) * state->dist);
		result->a *= exp(log(absorb.a) * state->dist);

		if (refract < 1.0) {
			inp = *mi_eval_color(&paras->input);
			result->r = result->r * refract + inp.r * (1-refract);
			result->g = result->g * refract + inp.g * (1-refract);
			result->b = result->b * refract + inp.b * (1-refract);
			result->a = result->a * refract + inp.a * (1-refract);
		}
	}
	return(miTRUE);
}
