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> 60 #include <type_traits> 63 #ifdef OPENVDB_TOOLS_RAYTRACER_USE_EXR 64 #include <OpenEXR/ImfPixelType.h> 65 #include <OpenEXR/ImfChannelList.h> 66 #include <OpenEXR/ImfOutputFile.h> 67 #include <OpenEXR/ImfHeader.h> 68 #include <OpenEXR/ImfFrameBuffer.h> 81 template<
typename Gr
idT>
85 size_t pixelSamples = 1,
86 unsigned int seed = 0,
87 bool threaded =
true);
90 template<
typename Gr
idT,
typename IntersectorT>
95 size_t pixelSamples = 1,
96 unsigned int seed = 0,
97 bool threaded =
true);
104 template<
typename Gr
idT,
typename IntersectorT = tools::LevelSetRayIntersector<Gr
idT> >
110 using RayType =
typename IntersectorT::RayType;
116 size_t pixelSamples = 1,
117 unsigned int seed = 0);
124 size_t pixelSamples = 1,
125 unsigned int seed = 0);
134 void setGrid(
const GridT& grid);
138 void setIntersector(
const IntersectorT& inter);
156 void setPixelSamples(
size_t pixelSamples,
unsigned int seed = 0);
159 void render(
bool threaded =
true)
const;
163 void operator()(
const tbb::blocked_range<size_t>& range)
const;
166 const bool mIsMaster;
169 std::unique_ptr<const BaseShader> mShader;
181 template <
typename IntersectorT,
typename SamplerT = tools::BoxSampler>
187 using RayType =
typename IntersectorT::RayType;
191 static_assert(std::is_floating_point<ValueType>::value,
192 "VolumeRender requires a floating-point-valued grid");
201 void render(
bool threaded=
true)
const;
208 void setIntersector(
const IntersectorT& inter);
240 void print(std::ostream& os = std::cout,
int verboseLevel = 1);
244 void operator()(
const tbb::blocked_range<size_t>& range)
const;
250 std::unique_ptr<IntersectorT> mPrimary, mShadow;
251 Real mPrimaryStep, mShadowStep, mCutOff, mLightGain;
252 Vec3R mLightDir, mLightColor, mAbsorption, mScattering;
268 RGBA() : r(0), g(0), b(0), a(1) {}
269 explicit RGBA(
ValueT intensity) : r(intensity), g(intensity), b(intensity), a(1) {}
271 r(_r), g(_g), b(_b), a(_a)
273 RGBA(
double _r,
double _g,
double _b,
double _a = 1.0)
274 : r(static_cast<
ValueT>(_r))
275 , g(static_cast<
ValueT>(_g))
276 , b(static_cast<
ValueT>(_b))
277 , a(static_cast<
ValueT>(_a))
287 const float s = rhs.
a*(1.0f-a);
298 Film(
size_t width,
size_t height)
299 : mWidth(width), mHeight(height), mSize(width*height), mPixels(new
RGBA[mSize])
303 : mWidth(width), mHeight(height), mSize(width*height), mPixels(new
RGBA[mSize])
312 return mPixels[w + h*mWidth];
319 return mPixels[w + h*mWidth];
322 void fill(
const RGBA& rgb=
RGBA(0)) {
for (
size_t i=0; i<mSize; ++i) mPixels[i] = rgb; }
325 RGBA *p = mPixels.get();
326 for (
size_t j = 0; j < mHeight; ++j) {
327 for (
size_t i = 0; i < mWidth; ++i, ++p) {
328 *p = ((i & size) ^ (j & size)) ? c1 : c2;
335 std::string name(fileName);
336 if (name.find_last_of(
".") == std::string::npos) name.append(
".ppm");
338 std::unique_ptr<unsigned char[]> buffer(
new unsigned char[3*mSize]);
339 unsigned char *tmp = buffer.get(), *q = tmp;
340 RGBA* p = mPixels.get();
343 *q++ =
static_cast<unsigned char>(255.0f*(*p ).r);
344 *q++ =
static_cast<unsigned char>(255.0f*(*p ).g);
345 *q++ =
static_cast<unsigned char>(255.0f*(*p++).b);
348 std::ofstream os(name.c_str(), std::ios_base::binary);
350 std::cerr <<
"Error opening PPM file \"" << name <<
"\"" << std::endl;
354 os <<
"P6\n" << mWidth <<
" " << mHeight <<
"\n255\n";
355 os.write(reinterpret_cast<const char*>(&(*tmp)), 3 * mSize *
sizeof(
unsigned char));
358 #ifdef OPENVDB_TOOLS_RAYTRACER_USE_EXR 359 void saveEXR(
const std::string& fileName,
size_t compression = 2,
size_t threads = 8)
361 std::string name(fileName);
362 if (name.find_last_of(
".") == std::string::npos) name.append(
".exr");
364 if (threads>0) Imf::setGlobalThreadCount(threads);
365 Imf::Header header(mWidth, mHeight);
366 if (compression==0) header.compression() = Imf::NO_COMPRESSION;
367 if (compression==1) header.compression() = Imf::RLE_COMPRESSION;
368 if (compression>=2) header.compression() = Imf::ZIP_COMPRESSION;
369 header.channels().insert(
"R", Imf::Channel(Imf::FLOAT));
370 header.channels().insert(
"G", Imf::Channel(Imf::FLOAT));
371 header.channels().insert(
"B", Imf::Channel(Imf::FLOAT));
372 header.channels().insert(
"A", Imf::Channel(Imf::FLOAT));
374 Imf::FrameBuffer framebuffer;
375 framebuffer.insert(
"R", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].r),
376 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
377 framebuffer.insert(
"G", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].g),
378 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
379 framebuffer.insert(
"B", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].b),
380 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
381 framebuffer.insert(
"A", Imf::Slice( Imf::FLOAT, (
char *) &(mPixels[0].a),
382 sizeof (
RGBA),
sizeof (
RGBA) * mWidth));
384 Imf::OutputFile file(name.c_str(), header);
385 file.setFrameBuffer(framebuffer);
386 file.writePixels(mHeight);
390 size_t width()
const {
return mWidth; }
391 size_t height()
const {
return mHeight; }
396 size_t mWidth, mHeight, mSize;
397 std::unique_ptr<RGBA[]> mPixels;
408 double frameWidth,
double nearPlane,
double farPlane)
410 , mScaleWidth(frameWidth)
411 , mScaleHeight(frameWidth * double(film.height()) / double(film.width()))
413 assert(nearPlane > 0 && farPlane > nearPlane);
414 mScreenToWorld.accumPostRotation(
math::X_AXIS, rotation[0] * M_PI / 180.0);
415 mScreenToWorld.accumPostRotation(
math::Y_AXIS, rotation[1] * M_PI / 180.0);
416 mScreenToWorld.accumPostRotation(
math::Z_AXIS, rotation[2] * M_PI / 180.0);
417 mScreenToWorld.accumPostTranslation(translation);
418 this->initRay(nearPlane, farPlane);
425 size_t width()
const {
return mFilm->width(); }
426 size_t height()
const {
return mFilm->height(); }
434 const Vec3R orig = mScreenToWorld.applyMap(
Vec3R(0.0));
435 const Vec3R dir = orig - xyz;
437 Mat4d xform = math::aim<Mat4d>(dir, up);
440 this->initRay(mRay.t0(), mRay.t1());
446 return Vec3R( (2 * i /
double(mFilm->width()) - 1) * mScaleWidth,
447 (1 - 2 * j / double(mFilm->height())) * mScaleHeight, z );
454 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const = 0;
459 mRay.setTimes(t0, t1);
460 mRay.setEye(mScreenToWorld.applyMap(
Vec3R(0.0)));
461 mRay.setDir(mScreenToWorld.applyJacobian(
Vec3R(0.0, 0.0, -1.0)));
492 double focalLength = 50.0,
493 double aperture = 41.2136,
494 double nearPlane = 1e-3,
496 :
BaseCamera(film,
rotation, translation, 0.5*aperture/focalLength, nearPlane, farPlane)
506 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const override 509 Vec3R dir = BaseCamera::rasterToScreen(
Real(i) + iOffset,
Real(j) + jOffset, -1.0);
510 dir = BaseCamera::mScreenToWorld.applyJacobian(dir);
521 return 360.0 / M_PI * atan(aperture/(2.0*length));
527 return aperture/(2.0*(tan(fov * M_PI / 360.0)));
550 double frameWidth = 1.0,
551 double nearPlane = 1e-3,
559 size_t i,
size_t j,
double iOffset = 0.5,
double jOffset = 0.5)
const override 562 Vec3R eye = BaseCamera::rasterToScreen(
Real(i) + iOffset,
Real(j) + jOffset, 0.0);
563 ray.
setEye(BaseCamera::mScreenToWorld.applyMap(eye));
600 MatteShader(
const GridT& grid) : mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
605 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
606 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
612 typename GridT::ConstAccessor mAcc;
617 template<
typename SamplerType>
647 NormalShader(
const GridT& grid) : mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
652 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
653 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
654 return Film::RGBA(v[0]*(normal[0]+1.0), v[1]*(normal[1]+1.0), v[2]*(normal[2]+1.0));
659 typename GridT::ConstAccessor mAcc;
664 template<
typename SamplerType>
673 return mRGBA *
Film::RGBA(normal[0] + 1.0, normal[1] + 1.0, normal[2] + 1.0);
696 , mInvDim(1.0/bbox.extents())
697 , mAcc(grid.getAccessor())
698 , mXform(&grid.transform())
705 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
706 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
707 const Vec3R rgb = (xyz - mMin) * mInvDim;
713 const Vec3R mMin, mInvDim;
714 typename GridT::ConstAccessor mAcc;
719 template<
typename SamplerType>
724 : mMin(bbox.
min()), mInvDim(1.0/bbox.extents()), mRGBA(c) {}
729 const Vec3R rgb = (xyz - mMin)*mInvDim;
730 return mRGBA*
Film::RGBA(rgb[0], rgb[1], rgb[2]);
735 const Vec3R mMin, mInvDim;
754 DiffuseShader(
const GridT& grid): mAcc(grid.getAccessor()), mXform(&grid.transform()) {}
759 typename GridT::ValueType v = zeroVal<typename GridT::ValueType>();
760 SamplerType::sample(mAcc, mXform->worldToIndex(xyz), v);
769 typename GridT::ConstAccessor mAcc;
774 template <
typename SamplerType>
803 template<
typename Gr
idT>
812 tracer(grid, shader, camera, pixelSamples, seed);
817 template<
typename Gr
idT,
typename IntersectorT>
819 const IntersectorT& inter,
834 template<
typename Gr
idT,
typename IntersectorT>
844 mShader(shader.copy()),
850 template<
typename Gr
idT,
typename IntersectorT>
860 mShader(shader.copy()),
866 template<
typename Gr
idT,
typename IntersectorT>
871 mInter(other.mInter),
872 mShader(other.mShader->copy()),
873 mCamera(other.mCamera),
874 mSubPixels(other.mSubPixels)
878 template<
typename Gr
idT,
typename IntersectorT>
882 if (mIsMaster)
delete [] mRand;
885 template<
typename Gr
idT,
typename IntersectorT>
890 mInter = IntersectorT(grid);
893 template<
typename Gr
idT,
typename IntersectorT>
901 template<
typename Gr
idT,
typename IntersectorT>
906 mShader.reset(shader.
copy());
909 template<
typename Gr
idT,
typename IntersectorT>
917 template<
typename Gr
idT,
typename IntersectorT>
922 if (pixelSamples == 0) {
925 mSubPixels = pixelSamples - 1;
927 if (mSubPixels > 0) {
928 mRand =
new double[16];
930 for (
size_t i=0; i<16; ++i) mRand[i] = rand();
936 template<
typename Gr
idT,
typename IntersectorT>
940 tbb::blocked_range<size_t> range(0, mCamera->
height());
941 threaded ? tbb::parallel_for(range, *
this) : (*this)(range);
944 template<
typename Gr
idT,
typename IntersectorT>
950 const float frac = 1.0f / (1.0f + mSubPixels);
951 for (
size_t j=range.begin(), n=0, je = range.end(); j<je; ++j) {
952 for (
size_t i=0, ie = mCamera->
width(); i<ie; ++i) {
955 Film::RGBA c = mInter.intersectsWS(ray, xyz, nml) ? shader(xyz, nml, ray.dir()) : bg;
956 for (
size_t k=0; k<mSubPixels; ++k, n +=2 ) {
957 ray = mCamera->
getRay(i, j, mRand[n & 15], mRand[(n+1) & 15]);
958 c += mInter.intersectsWS(ray, xyz, nml) ? shader(xyz, nml, ray.dir()) : bg;
967 template<
typename IntersectorT,
typename SampleT>
970 : mAccessor(inter.grid().getConstAccessor())
972 , mPrimary(new IntersectorT(inter))
973 , mShadow(new IntersectorT(inter))
979 , mLightColor(0.7, 0.7, 0.7)
985 template<
typename IntersectorT,
typename SampleT>
988 : mAccessor(other.mAccessor)
989 , mCamera(other.mCamera)
990 , mPrimary(new IntersectorT(*(other.mPrimary)))
991 , mShadow(new IntersectorT(*(other.mShadow)))
992 , mPrimaryStep(other.mPrimaryStep)
993 , mShadowStep(other.mShadowStep)
994 , mCutOff(other.mCutOff)
995 , mLightGain(other.mLightGain)
996 , mLightDir(other.mLightDir)
997 , mLightColor(other.mLightColor)
998 , mAbsorption(other.mAbsorption)
999 , mScattering(other.mScattering)
1003 template<
typename IntersectorT,
typename SampleT>
1005 print(std::ostream& os,
int verboseLevel)
1007 if (verboseLevel>0) {
1008 os <<
"\nPrimary step: " << mPrimaryStep
1009 <<
"\nShadow step: " << mShadowStep
1010 <<
"\nCutoff: " << mCutOff
1011 <<
"\nLightGain: " << mLightGain
1012 <<
"\nLightDir: " << mLightDir
1013 <<
"\nLightColor: " << mLightColor
1014 <<
"\nAbsorption: " << mAbsorption
1015 <<
"\nScattering: " << mScattering << std::endl;
1017 mPrimary->print(os, verboseLevel);
1020 template<
typename IntersectorT,
typename SampleT>
1024 mPrimary.reset(
new IntersectorT(inter));
1025 mShadow.reset(
new IntersectorT(inter));
1028 template<
typename IntersectorT,
typename SampleT>
1032 tbb::blocked_range<size_t> range(0, mCamera->
height());
1033 threaded ? tbb::parallel_for(range, *
this) : (*this)(range);
1036 template<
typename IntersectorT,
typename SampleT>
1040 SamplerType sampler(mAccessor, mShadow->grid().transform());
1043 const Vec3R extinction = -mScattering-mAbsorption, One(1.0);
1044 const Vec3R albedo = mLightColor*mScattering/(mScattering+mAbsorption);
1045 const Real sGain = mLightGain;
1046 const Real pStep = mPrimaryStep;
1047 const Real sStep = mShadowStep;
1048 const Real cutoff = mCutOff;
1057 std::vector<typename RayType::TimeSpan> pTS, sTS;
1062 for (
size_t j=range.begin(), je = range.end(); j<je; ++j) {
1063 for (
size_t i=0, ie = mCamera->
width(); i<ie; ++i) {
1065 bg.
a = bg.
r = bg.
g = bg.
b = 0;
1067 if( !mPrimary->setWorldRay(pRay))
continue;
1068 Vec3R pTrans(1.0), pLumi(0.0);
1071 while (mPrimary->march(pT0, pT1)) {
1072 for (
Real pT = pStep*ceil(pT0/pStep); pT <= pT1; pT += pStep) {
1074 mPrimary->hits(pTS);
1075 for (
size_t k=0; k<pTS.size(); ++k) {
1076 Real pT = pStep*ceil(pTS[k].t0/pStep), pT1=pTS[k].t1;
1077 for (; pT <= pT1; pT += pStep) {
1079 Vec3R pPos = mPrimary->getWorldPos(pT);
1080 const Real density = sampler.wsSample(pPos);
1081 if (density < cutoff)
continue;
1085 if( !mShadow->setWorldRay(sRay))
continue;
1088 while (mShadow->march(sT0, sT1)) {
1089 for (
Real sT = sStep*ceil(sT0/sStep); sT <= sT1; sT+= sStep) {
1092 for (
size_t l=0; l<sTS.size(); ++l) {
1093 Real sT = sStep*ceil(sTS[l].t0/sStep), sT1=sTS[l].t1;
1094 for (; sT <= sT1; sT+= sStep) {
1096 const Real d = sampler.wsSample(mShadow->getWorldPos(sT));
1097 if (d < cutoff)
continue;
1098 sTrans *=
math::Exp(extinction * d * sStep/(1.0+sT*sGain));
1099 if (sTrans.
lengthSqr()<cutoff)
goto Luminance;
1103 pLumi += albedo * sTrans * pTrans * (One-dT);
1105 if (pTrans.lengthSqr()<cutoff)
goto Pixel;
1121 #endif // OPENVDB_TOOLS_RAYTRACER_HAS_BEEN_INCLUDED
double Real
Definition: Types.h:67
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:204
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:523
Coord Abs(const Coord &xyz)
Definition: Coord.h:513
Type Exp(const Type &x)
Return ex.
Definition: Math.h:664
MatType unit(const MatType &mat, typename MatType::value_type eps=1.0e-8)
Return a copy of the given matrix with its upper 3×3 rows normalized.
Definition: Mat.h:680
Axis-aligned bounding box.
Definition: BBox.h:50
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:109
Vec3< T > unit(T eps=0) const
return normalized this, throws if null vector
Definition: Vec3.h:389
Mat4< double > Mat4d
Definition: Mat4.h:1361
void setDir(const Vec3Type &dir)
Definition: Ray.h:93
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition: version.h:136
math::Vec3< Real > Vec3R
Definition: Types.h:79
T dot(const Vec3< T > &v) const
Dot product.
Definition: Vec3.h:216
Definition: Exceptions.h:92
MatType scale(const Vec3< typename MatType::value_type > &s)
Return a matrix that scales by s.
Definition: Mat.h:647
Definition: Exceptions.h:40
bool normalize(T eps=T(1.0e-7))
this = normalized this
Definition: Vec3.h:377
void postTranslate(const Vec3< T0 > &tr)
Right multiplies by the specified translation matrix, i.e. (*this) * Trans.
Definition: Mat4.h:760
Simple generator of random numbers over the range [0, 1)
Definition: Math.h:135
const Vec3T & dir() const
Definition: Ray.h:126
void setEye(const Vec3Type &eye)
Definition: Ray.h:91
A general linear transform using homogeneous coordinates to perform rotation, scaling, shear and translation.
Definition: Maps.h:327
Mat3< typename promote< T0, T1 >::type > operator*(const Mat3< T0 > &m0, const Mat3< T1 > &m1)
Multiply m0 by m1 and return the resulting matrix.
Definition: Mat3.h:645
void scaleTimes(RealT scale)
Definition: Ray.h:111
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:188
T lengthSqr() const
Definition: Vec3.h:236