45 #ifndef OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED
46 #define OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED
48 #include <openvdb/Types.h>
49 #include <openvdb/math/BBox.h>
50 #include <openvdb/math/Ray.h>
51 #include <openvdb/math/Math.h>
52 #include <openvdb/tools/RayIntersector.h>
53 #include <openvdb/tools/Interpolation.h>
54 #include <boost/scoped_ptr.hpp>
55 #include <boost/scoped_array.hpp>
60 #ifdef OPENVDB_TOOLS_RAYTRACER_USE_EXR
61 #include <OpenEXR/ImfPixelType.h>
62 #include <OpenEXR/ImfChannelList.h>
63 #include <OpenEXR/ImfOutputFile.h>
64 #include <OpenEXR/ImfHeader.h>
65 #include <OpenEXR/ImfFrameBuffer.h>
78 template<
typename Gr
idT>
82 size_t pixelSamples = 1,
83 unsigned int seed = 0,
84 bool threaded =
true);
87 template<
typename Gr
idT,
typename IntersectorT>
92 size_t pixelSamples = 1,
93 unsigned int seed = 0,
94 bool threaded =
true);
101 template<
typename Gr
idT,
typename IntersectorT = tools::LevelSetRayIntersector<Gr
idT> >
107 typedef typename IntersectorT::RayType
RayType;
113 size_t pixelSamples = 1,
114 unsigned int seed = 0);
121 size_t pixelSamples = 1,
122 unsigned int seed = 0);
131 void setGrid(
const GridT& grid);
135 void setIntersector(
const IntersectorT& inter);
153 void setPixelSamples(
size_t pixelSamples,
unsigned int seed = 0);
156 void render(
bool threaded =
true)
const;
160 void operator()(
const tbb::blocked_range<size_t>& range)
const;
163 const bool mIsMaster;
166 boost::scoped_ptr<const BaseShader> mShader;
178 template <
typename IntersectorT,
typename SamplerT = tools::BoxSampler>
184 typedef typename IntersectorT::RayType
RayType;
188 BOOST_STATIC_ASSERT(boost::is_floating_point<ValueType>::value);
197 void render(
bool threaded=
true)
const;
204 void setIntersector(
const IntersectorT& inter);
236 void print(std::ostream& os = std::cout,
int verboseLevel = 1);
240 void operator()(
const tbb::blocked_range<size_t>& range)
const;
244 AccessorType mAccessor;
246 boost::scoped_ptr<IntersectorT> mPrimary, mShadow;
247 Real mPrimaryStep, mShadowStep, mCutOff, mLightGain;
248 Vec3R mLightDir, mLightColor, mAbsorption, mScattering;
264 RGBA() : r(0), g(0), b(0), a(1) {}
265 explicit RGBA(ValueT intensity) : r(intensity), g(intensity), b(intensity), a(1) {}
266 RGBA(ValueT _r, ValueT _g, ValueT _b, ValueT _a = static_cast<ValueT>(1.0)):
267 r(_r), g(_g), b(_b), a(_a)
277 const float s = rhs.
a*(1.0f-a);
288 Film(
size_t width,
size_t height)
289 : mWidth(width), mHeight(height), mSize(width*height), mPixels(new
RGBA[mSize])
293 : mWidth(width), mHeight(height), mSize(width*height), mPixels(new
RGBA[mSize])
302 return mPixels[w + h*mWidth];
309 return mPixels[w + h*mWidth];
312 void fill(
const RGBA& rgb=
RGBA(0)) {
for (
size_t i=0; i<mSize; ++i) mPixels[i] = rgb; }
315 RGBA *p = mPixels.get();
316 for (
size_t j = 0; j < mHeight; ++j) {
317 for (
size_t i = 0; i < mWidth; ++i, ++p) {
318 *p = ((i & size) ^ (j & size)) ? c1 : c2;
325 std::string name(fileName +
".ppm");
326 boost::scoped_array<unsigned char> buffer(
new unsigned char[3*mSize]);
327 unsigned char *tmp = buffer.get(), *q = tmp;
328 RGBA* p = mPixels.get();
331 *q++ =
static_cast<unsigned char>(255.0f*(*p ).r);
332 *q++ =
static_cast<unsigned char>(255.0f*(*p ).g);
333 *q++ =
static_cast<unsigned char>(255.0f*(*p++).b);
336 std::ofstream os(name.c_str(), std::ios_base::binary);
338 std::cerr <<
"Error opening PPM file \"" << name <<
"\"" << std::endl;
342 os <<
"P6\n" << mWidth <<
" " << mHeight <<
"\n255\n";
343 os.write((
const char *)&(*tmp), 3*mSize*
sizeof(
unsigned char));
346 #ifdef OPENVDB_TOOLS_RAYTRACER_USE_EXR
347 void saveEXR(
const std::string& fileName,
size_t compression = 2,
size_t threads = 8)
349 std::string name(fileName +
".exr");
351 if (threads>0) Imf::setGlobalThreadCount(threads);
352 Imf::Header header(mWidth, mHeight);
353 if (compression==0) header.compression() = Imf::NO_COMPRESSION;
354 if (compression==1) header.compression() = Imf::RLE_COMPRESSION;
355 if (compression>=2) header.compression() = Imf::ZIP_COMPRESSION;
356 header.channels().insert(
"R", Imf::Channel(Imf::FLOAT));
357 header.channels().insert(
"G", Imf::Channel(Imf::FLOAT));
358 header.channels().insert(
"B", Imf::Channel(Imf::FLOAT));
359 header.channels().insert(
"A", Imf::Channel(Imf::FLOAT));
361 Imf::FrameBuffer framebuffer;
362 framebuffer.insert(
"R", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].r),
363 sizeof (RGBA),
sizeof (RGBA) * mWidth));
364 framebuffer.insert(
"G", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].g),
365 sizeof (RGBA),
sizeof (RGBA) * mWidth));
366 framebuffer.insert(
"B", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].b),
367 sizeof (RGBA),
sizeof (RGBA) * mWidth));
368 framebuffer.insert(
"A", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].a),
369 sizeof (RGBA),
sizeof (RGBA) * mWidth));
371 Imf::OutputFile file(name.c_str(), header);
372 file.setFrameBuffer(framebuffer);
373 file.writePixels(mHeight);
377 size_t width()
const {
return mWidth; }
378 size_t height()
const {
return mHeight; }
383 size_t mWidth, mHeight, mSize;
384 boost::scoped_array<RGBA> mPixels;
395 double frameWidth,
double nearPlane,
double farPlane)
397 , mScaleWidth(frameWidth)
398 , mScaleHeight(frameWidth * double(film.height()) / double(film.width()))
400 assert(nearPlane > 0 && farPlane > nearPlane);
401 mScreenToWorld.accumPostRotation(
math::X_AXIS, rotation[0] * M_PI / 180.0);
402 mScreenToWorld.accumPostRotation(
math::Y_AXIS, rotation[1] * M_PI / 180.0);
403 mScreenToWorld.accumPostRotation(
math::Z_AXIS, rotation[2] * M_PI / 180.0);
404 mScreenToWorld.accumPostTranslation(translation);
405 this->initRay(nearPlane, farPlane);
412 size_t width()
const {
return mFilm->width(); }
413 size_t height()
const {
return mFilm->height(); }
421 const Vec3R orig = mScreenToWorld.applyMap(
Vec3R(0.0));
422 const Vec3R dir = orig - xyz;
424 Mat4d xform = math::aim<Mat4d>(dir, up);
427 this->initRay(mRay.t0(), mRay.t1());
433 return Vec3R( (2 * i /
double(mFilm->width()) - 1) * mScaleWidth,
434 (1 - 2 * j / double(mFilm->height())) * mScaleHeight, z );
441 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const = 0;
446 mRay.setTimes(t0, t1);
447 mRay.setEye(mScreenToWorld.applyMap(
Vec3R(0.0)));
448 mRay.setDir(mScreenToWorld.applyJacobian(
Vec3R(0.0, 0.0, -1.0)));
479 double focalLength = 50.0,
480 double aperture = 41.2136,
481 double nearPlane = 1e-3,
483 :
BaseCamera(film,
rotation, translation, 0.5*aperture/focalLength, nearPlane, farPlane)
493 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const
496 Vec3R dir = BaseCamera::rasterToScreen(
Real(i) + iOffset,
Real(j) + jOffset, -1.0);
497 dir = BaseCamera::mScreenToWorld.applyJacobian(dir);
508 return 360.0 / M_PI * atan(aperture/(2.0*length));
514 return aperture/(2.0*(tan(fov * M_PI / 360.0)));
537 double frameWidth = 1.0,
538 double nearPlane = 1e-3,
546 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const
549 Vec3R eye = BaseCamera::rasterToScreen(
Real(i) + iOffset,
Real(j) + jOffset, 0.0);
550 ray.
setEye(BaseCamera::mScreenToWorld.applyMap(eye));
581 template <
typename GridT = Film::RGBA,
586 MatteShader(
const GridT& grid) : mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
590 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
591 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
593 static_cast<Film::RGBA::ValueT>(v[0]),
594 static_cast<Film::RGBA::ValueT>(v[1]),
595 static_cast<Film::RGBA::ValueT>(v[2]));
600 typename GridT::ConstAccessor mAcc;
604 template <
typename SamplerType>
628 template <
typename GridT = Film::RGBA,
633 NormalShader(
const GridT& grid) : mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
637 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
638 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
639 return Film::RGBA(v[0]*(normal[0]+1.0f), v[1]*(normal[1]+1.0f), v[2]*(normal[2]+1.0f));
644 typename GridT::ConstAccessor mAcc;
648 template <
typename SamplerType>
656 return mRGBA*
Film::RGBA(normal[0]+1.0f, normal[1]+1.0f, normal[2]+1.0f);
672 template <
typename GridT = Film::RGBA,
679 , mInvDim(1.0/bbox.extents())
680 , mAcc(grid.getAccessor())
681 , mXform(&grid.transform())
687 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
688 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
689 const Vec3R rgb = (xyz - mMin)*mInvDim;
695 const Vec3R mMin, mInvDim;
696 typename GridT::ConstAccessor mAcc;
700 template <
typename SamplerType>
705 : mMin(bbox.
min()), mInvDim(1.0/bbox.extents()), mRGBA(c) {}
709 const Vec3R rgb = (xyz - mMin)*mInvDim;
710 return mRGBA*
Film::RGBA(rgb[0], rgb[1], rgb[2]);
715 const Vec3R mMin, mInvDim;
728 template <
typename GridT = Film::RGBA,
733 DiffuseShader(
const GridT& grid): mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
737 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
738 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
746 typename GridT::ConstAccessor mAcc;
750 template <
typename SamplerType>
777 template<
typename Gr
idT>
786 tracer(grid, shader, camera, pixelSamples, seed);
791 template<
typename Gr
idT,
typename IntersectorT>
793 const IntersectorT& inter,
808 template<
typename Gr
idT,
typename IntersectorT>
809 inline LevelSetRayTracer<GridT, IntersectorT>::
810 LevelSetRayTracer(
const GridT& grid,
818 mShader(shader.copy()),
824 template<
typename Gr
idT,
typename IntersectorT>
834 mShader(shader.copy()),
840 template<
typename Gr
idT,
typename IntersectorT>
845 mInter(other.mInter),
846 mShader(other.mShader->copy()),
847 mCamera(other.mCamera),
848 mSubPixels(other.mSubPixels)
852 template<
typename Gr
idT,
typename IntersectorT>
856 if (mIsMaster)
delete [] mRand;
859 template<
typename Gr
idT,
typename IntersectorT>
864 mInter = IntersectorT(grid);
867 template<
typename Gr
idT,
typename IntersectorT>
875 template<
typename Gr
idT,
typename IntersectorT>
880 mShader.reset(shader.
copy());
883 template<
typename Gr
idT,
typename IntersectorT>
891 template<
typename Gr
idT,
typename IntersectorT>
896 if (pixelSamples == 0) {
899 mSubPixels = pixelSamples - 1;
901 if (mSubPixels > 0) {
902 mRand =
new double[16];
904 for (
size_t i=0; i<16; ++i) mRand[i] = rand();
910 template<
typename Gr
idT,
typename IntersectorT>
914 tbb::blocked_range<size_t> range(0, mCamera->height());
915 threaded ? tbb::parallel_for(range, *
this) : (*this)(range);
918 template<
typename Gr
idT,
typename IntersectorT>
924 const float frac = 1.0f / (1.0f + mSubPixels);
925 for (
size_t j=range.begin(), n=0, je = range.end(); j<je; ++j) {
926 for (
size_t i=0, ie = mCamera->width(); i<ie; ++i) {
928 RayType ray = mCamera->getRay(i, j);
929 Film::RGBA c = mInter.intersectsWS(ray, xyz, nml) ? shader(xyz, nml, ray.dir()) : bg;
930 for (
size_t k=0; k<mSubPixels; ++k, n +=2 ) {
931 ray = mCamera->getRay(i, j, mRand[n & 15], mRand[(n+1) & 15]);
932 c += mInter.intersectsWS(ray, xyz, nml) ? shader(xyz, nml, ray.dir()) : bg;
941 template<
typename IntersectorT,
typename SampleT>
944 : mAccessor(inter.grid().getConstAccessor())
946 , mPrimary(new IntersectorT(inter))
947 , mShadow(new IntersectorT(inter))
953 , mLightColor(0.7, 0.7, 0.7)
959 template<
typename IntersectorT,
typename SampleT>
962 : mAccessor(other.mAccessor)
963 , mCamera(other.mCamera)
964 , mPrimary(new IntersectorT(*(other.mPrimary)))
965 , mShadow(new IntersectorT(*(other.mShadow)))
966 , mPrimaryStep(other.mPrimaryStep)
967 , mShadowStep(other.mShadowStep)
968 , mCutOff(other.mCutOff)
969 , mLightGain(other.mLightGain)
970 , mLightDir(other.mLightDir)
971 , mLightColor(other.mLightColor)
972 , mAbsorption(other.mAbsorption)
973 , mScattering(other.mScattering)
977 template<
typename IntersectorT,
typename SampleT>
979 print(std::ostream& os,
int verboseLevel)
981 if (verboseLevel>0) {
982 os <<
"\nPrimary step: " << mPrimaryStep
983 <<
"\nShadow step: " << mShadowStep
984 <<
"\nCutoff: " << mCutOff
985 <<
"\nLightGain: " << mLightGain
986 <<
"\nLightDir: " << mLightDir
987 <<
"\nLightColor: " << mLightColor
988 <<
"\nAbsorption: " << mAbsorption
989 <<
"\nScattering: " << mScattering << std::endl;
991 mPrimary->print(os, verboseLevel);
994 template<
typename IntersectorT,
typename SampleT>
998 mPrimary.reset(
new IntersectorT(inter));
999 mShadow.reset(
new IntersectorT(inter));
1002 template<
typename IntersectorT,
typename SampleT>
1006 tbb::blocked_range<size_t> range(0, mCamera->height());
1007 threaded ? tbb::parallel_for(range, *
this) : (*this)(range);
1010 template<
typename IntersectorT,
typename SampleT>
1014 SamplerType sampler(mAccessor, mShadow->grid().transform());
1017 const Vec3R extinction = -mScattering-mAbsorption, One(1.0);
1018 const Vec3R albedo = mLightColor*mScattering/(mScattering+mAbsorption);
1019 const Real sGain = mLightGain;
1020 const Real pStep = mPrimaryStep;
1021 const Real sStep = mShadowStep;
1022 const Real cutoff = mCutOff;
1031 std::vector<typename RayType::TimeSpan> pTS, sTS;
1036 for (
size_t j=range.begin(), je = range.end(); j<je; ++j) {
1037 for (
size_t i=0, ie = mCamera->width(); i<ie; ++i) {
1039 bg.
a = bg.
r = bg.
g = bg.
b = 0;
1040 RayType pRay = mCamera->getRay(i, j);
1041 if( !mPrimary->setWorldRay(pRay))
continue;
1042 Vec3R pTrans(1.0), pLumi(0.0);
1045 while (mPrimary->march(pT0, pT1)) {
1046 for (
Real pT = pStep*ceil(pT0/pStep); pT <= pT1; pT += pStep) {
1048 mPrimary->hits(pTS);
1049 for (
size_t k=0; k<pTS.size(); ++k) {
1050 Real pT = pStep*ceil(pTS[k].t0/pStep), pT1=pTS[k].t1;
1051 for (; pT <= pT1; pT += pStep) {
1053 Vec3R pPos = mPrimary->getWorldPos(pT);
1054 const Real density = sampler.wsSample(pPos);
1055 if (density < cutoff)
continue;
1059 if( !mShadow->setWorldRay(sRay))
continue;
1062 while (mShadow->march(sT0, sT1)) {
1063 for (
Real sT = sStep*ceil(sT0/sStep); sT <= sT1; sT+= sStep) {
1066 for (
size_t l=0; l<sTS.size(); ++l) {
1067 Real sT = sStep*ceil(sTS[l].t0/sStep), sT1=sTS[l].t1;
1068 for (; sT <= sT1; sT+= sStep) {
1070 const Real d = sampler.wsSample(mShadow->getWorldPos(sT));
1071 if (d < cutoff)
continue;
1072 sTrans *=
math::Exp(extinction * d * sStep/(1.0+sT*sGain));
1073 if (sTrans.
lengthSqr()<cutoff)
goto Luminance;
1077 pLumi += albedo * sTrans * pTrans * (One-dT);
1079 if (pTrans.lengthSqr()<cutoff)
goto Pixel;
1095 #endif // OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED
int32_t Abs(int32_t i)
Return the absolute value of the given quantity.
Definition: Math.h:284
void postTranslate(const Vec3< T0 > &tr)
Right multiplies by the specified translation matrix, i.e. (*this) * Trans.
Definition: Mat4.h:726
A general linear transform using homogeneous coordinates to perform rotation, scaling, shear and translation.
Definition: Maps.h:324
MatType rotation(const Quat< typename MatType::value_type > &q, typename MatType::value_type eps=static_cast< typename MatType::value_type >(1.0e-8))
Return the rotation matrix specified by the given quaternion.
Definition: Mat.h:153
Simple generator of random numbers over the range [0, 1)
Definition: Math.h:134
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:97
Axis-aligned bounding box.
Definition: BBox.h:47
Mat3< typename promote< T0, T1 >::type > operator*(const Mat3< T0 > &m0, const Mat3< T1 > &m1)
Matrix multiplication.
Definition: Mat3.h:608
double Real
Definition: Types.h:65
const Vec3T & dir() const
Definition: Ray.h:121
void setEye(const Vec3Type &eye)
Definition: Ray.h:88
void scaleTimes(RealT scale)
Definition: Ray.h:107
Vec3< T > unit(T eps=0) const
return normalized this, throws if null vector
Definition: Vec3.h:360
#define OPENVDB_VERSION_NAME
Definition: version.h:43
math::Vec3< Real > Vec3R
Definition: Types.h:77
T dot(const Vec3< T > &v) const
Dot product.
Definition: Vec3.h:203
bool normalize(T eps=T(1.0e-7))
this = normalized this
Definition: Vec3.h:348
Definition: Exceptions.h:39
MatType unit(const MatType &mat, typename MatType::value_type eps=1.0e-8)
Return a copy of the given matrix with its upper 3x3 rows normalized.
Definition: Mat.h:627
OPENVDB_API Hermite min(const Hermite &, const Hermite &)
min and max operations done directly on the compressed data.
void setDir(const Vec3Type &dir)
Definition: Ray.h:90
Definition: Exceptions.h:88
MatType scale(const Vec3< typename MatType::value_type > &s)
Return a matrix that scales by s.
Definition: Mat.h:594
OPENVDB_API Hermite max(const Hermite &, const Hermite &)
min and max operations done directly on the compressed data.
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:71
Type Exp(const Type &x)
Return .
Definition: Math.h:660
T lengthSqr() const
Definition: Vec3.h:223
Vec3< typename promote< T, typename Coord::ValueType >::type > operator+(const Vec3< T > &v0, const Coord &v1)
Allow a Coord to be added to or subtracted from a Vec3.
Definition: Coord.h:382