// PhBRMLBackground.C: PhBRML Background handler
#ifndef NO_VRML

#include "readvrml.H"
#include "cie.h"
#include "PhBRMLBackground.H"
#include "PhBRML.H"

using namespace xrml;


static COLOR f_cvtcol(Spectrum s)
{
  COLOR col;
  cvtcol(s, col);
  return col;
}

static VECTOR f_cvtvec(Vec3 v)
{
  VECTOR vec;
  cvtvec(v, vec);
  return vec;
}

static COLOR PhBBKGRadiance(PhBBackground *bkg, VECTOR *pos, VECTOR *dir, float *pdf)
{
  return f_cvtcol(bkg->eval(pos ? Vec3(pos->x, pos->y, pos->z) : Vec3(0,0,0),
			    dir ? Vec3(dir->x, dir->y, dir->z) : Vec3(0,0,0),
			    Spectrum(1.,1.,1.),
			    pdf));
}

static VECTOR PhBBKGSample(PhBBackground *bkg, VECTOR *pos, float xi1, float xi2, COLOR *radiance, float *pdf)
{
  Spectrum val;
  Vec3 dir = bkg->sample(Spectrum(1.,1.,1.), 
			 pos ? Vec3(pos->x, pos->y, pos->z) : Vec3(0,0,0),
			 xi1, xi2,
			 radiance ? &val : (Spectrum*)0,
			 pdf);
  if (radiance) cvtcol(val, *radiance);
  return f_cvtvec(dir);
}

static COLOR PhBBKGPower(PhBBackground *bkg, VECTOR *pos)
{
  return f_cvtcol(bkg->power(pos ? Vec3(pos->x, pos->y, pos->z) : Vec3(0,0,0)));
}

static void PhBBKGDestroy(PhBBackground *)
{
  // does nothing
}

static void PhBBKGPrint(FILE *out, PhBBackground *bkg)
{
  fprintf(out, "%s", bkg->name());
}

static struct BACKGROUND_METHODS PhBBKGMethods = {
  (COLOR (*)(void *data, VECTOR *pos, VECTOR *dir, float *pdf))PhBBKGRadiance,
  (VECTOR (*)(void *data, VECTOR *pos, float xi1, float xi2, COLOR *radiance, float *pdf))PhBBKGSample,
  (COLOR (*)(void *data, VECTOR *pos))PhBBKGPower,
  (void (*)(FILE *out, void *data))PhBBKGPrint,
  (void (*)(void *data))PhBBKGDestroy
};

BACKGROUND *PhBRMLBackgroundCreate(PhBBackground *bkg)
{
  return BackgroundCreate((void *)bkg, &PhBBKGMethods);
}

#endif /*NO_VRML*/
