SLProject  4.2.000
A platform independent 3D computer graphics framework for desktop OS, Android, iOS and online in web browsers
SLPathtracer Class Reference

Classic Monte Carlo Pathtracing algorithm for real global illumination. More...

#include <SLPathtracer.h>

Inheritance diagram for SLPathtracer:
[legend]

Public Member Functions

 SLPathtracer ()
 
 ~SLPathtracer ()
 
SLbool render (SLSceneView *sv)
 
void renderSlices (bool isMainThread, SLint currentSample, SLuint threadNum)
 
SLCol4f trace (SLRay *ray, SLbool em)
 
SLCol4f shade (SLRay *ray, SLCol4f *mat)
 
void saveImage ()
 Saves the current PT image as PNG image. More...
 
void calcDirect (SLbool di)
 
void calcIndirect (SLbool ii)
 
SLbool calcDirect () const
 
SLbool calcIndirect () const
 
- Public Member Functions inherited from SLRaytracer
 SLRaytracer ()
 
 ~SLRaytracer () override
 
SLbool renderClassic (SLSceneView *sv)
 
SLbool renderDistrib (SLSceneView *sv)
 
void renderSlices (bool isMainThread, SLuint threadNum)
 
void renderSlicesMS (bool isMainThread, SLuint threadNum)
 
SLCol4f trace (SLRay *ray)
 
SLCol4f shade (SLRay *ray)
 
void sampleAAPixels (bool isMainThread, SLuint threadNum)
 
void renderUIBeforeUpdate ()
 Must be called before an inbetween frame updateRec. More...
 
void setPrimaryRay (SLfloat x, SLfloat y, SLRay *primaryRay)
 Set the parameters of a primary ray for a pixel position at x, y. More...
 
void getAAPixels ()
 
SLCol4f fogBlend (SLfloat z, SLCol4f color)
 
virtual void printStats (SLfloat sec)
 
virtual void initStats (SLint depth)
 
void state (SLRTState state)
 
void maxDepth (SLint depth)
 
void resolutionFactor (SLfloat rf)
 
void doDistributed (SLbool distrib)
 
void doContinuous (SLbool cont)
 
void doFresnel (SLbool fresnel)
 
void aaSamples (SLint samples)
 
void gamma (SLfloat g)
 
SLRTState state () const
 
SLint maxDepth () const
 
SLbool doDistributed () const
 
SLbool doContinuous () const
 
SLbool doFresnel () const
 
SLint aaSamples () const
 
SLint progressPC () const
 
SLfloat aaThreshold () const
 
SLfloat renderSec () const
 
SLfloat gamma () const
 
SLfloat oneOverGamma () const
 
SLfloat resolutionFactor () const
 
SLint resolutionFactorPC () const
 
SLfloat raysPerMS ()
 
virtual void prepareImage ()
 
virtual void renderImage (bool updateTextureGL)
 
- Public Member Functions inherited from SLGLTexture
 SLGLTexture ()
 Default ctor for all stack instances (not created with new) More...
 
 SLGLTexture (SLAssetManager *assetMgr, const SLVCol4f &colors, SLint min_filter=GL_LINEAR, SLint mag_filter=GL_LINEAR, SLint wrapS=GL_REPEAT, const SLstring &name="2D-Texture")
 ctor for 1D texture with internal image allocation More...
 
 SLGLTexture (SLAssetManager *assetMgr, SLint min_filter, SLint mag_filter, SLint wrapS, SLint wrapT, SLenum target=GL_TEXTURE_2D)
 ctor for empty 2D textures More...
 
 SLGLTexture (SLAssetManager *assetMgr, unsigned char *data, int width, int height, int cvtype, SLint min_filter, SLint mag_filter, SLTextureType type, SLint wrapS, SLint wrapT)
 ctor for 2D textures from byte pointer More...
 
 SLGLTexture (SLAssetManager *assetMgr, const SLstring &imageFilename, SLint min_filter=GL_LINEAR_MIPMAP_LINEAR, SLint mag_filter=GL_LINEAR, SLTextureType type=TT_unknown, SLint wrapS=GL_REPEAT, SLint wrapT=GL_REPEAT)
 ctor for 2D textures with internal image allocation More...
 
 SLGLTexture (SLAssetManager *assetMgr, const SLVstring &imageFilenames, SLint min_filter=GL_LINEAR, SLint mag_filter=GL_LINEAR, SLint wrapS=GL_REPEAT, SLint wrapT=GL_REPEAT, const SLstring &name="3D-Texture", SLbool loadGrayscaleIntoAlpha=false)
 ctor for 3D texture with internal image allocation More...
 
 SLGLTexture (SLAssetManager *assetMgr, SLint depth, const SLstring &imageFilename, SLint min_filter=GL_LINEAR, SLint mag_filter=GL_LINEAR, SLint wrapS=GL_REPEAT, SLint wrapT=GL_REPEAT, const SLstring &name="3D-Texture", SLbool loadGrayscaleIntoAlpha=false)
 ctor for 3D texture from a single file with depth as 3rd dimension More...
 
 SLGLTexture (SLAssetManager *assetMgr, const SLstring &imageFilenameXPos, const SLstring &imageFilenameXNeg, const SLstring &imageFilenameYPos, const SLstring &imageFilenameYNeg, const SLstring &imageFilenameZPos, const SLstring &imageFilenameZNeg, SLint min_filter=GL_LINEAR, SLint mag_filter=GL_LINEAR, SLTextureType type=TT_unknown)
 ctor for cube mapping with internal image allocation More...
 
 ~SLGLTexture () override
 
virtual void build (SLint texUnit)
 
void deleteData (SLbool deleteAlsoOnGPU)
 Delete all data (CVImages and GPU textures) More...
 
void deleteDataGpu ()
 Deletes the OpenGL texture objects and releases the memory on the GPU. More...
 
void deleteImages ()
 Deletes the CVImages in _images. No more texture mapping in ray tracing. More...
 
void bindActive (SLuint texUnit=0)
 
void fullUpdate ()
 
void drawSprite (SLbool doUpdate, SLfloat x, SLfloat y, SLfloat w, SLfloat h)
 Draws the texture as 2D sprite with OpenGL buffers. More...
 
void cubeUV2XYZ (SLint index, SLfloat u, SLfloat v, SLfloat &x, SLfloat &y, SLfloat &z)
 Computes the unnormalised vector x,y,z from tex. coords. uv with cubemap index. More...
 
void cubeXYZ2UV (SLfloat x, SLfloat y, SLfloat z, SLint &index, SLfloat &u, SLfloat &v)
 Computes the uv and cubemap image index from a unnormalised vector x,y,z. More...
 
SLstring filterString (SLint glFilter)
 Returns OpenGL texture filter as string. More...
 
void texType (SLTextureType bt)
 
void uvIndex (SLbyte i)
 
void bumpScale (SLfloat bs)
 
void minFiler (SLint minF)
 
void magFiler (SLint magF)
 
void needsUpdate (SLbool update)
 
void textureSize (int width, int height)
 
void deleteImageAfterBuild (SLbool delImg)
 If deleteImageAfterBuild is set to true you won't be able to ray trace the scene. More...
 
SLuint width ()
 
SLuint height ()
 
SLuint depth ()
 
SLbyte uvIndex ()
 
SLint bytesPerPixel ()
 
SLint bytesOnGPU ()
 
SLint bytesInFile ()
 
CVVImageimages ()
 
SLenum target () const
 
SLuint texID () const
 
SLTextureType texType ()
 
SLfloat bumpScale () const
 
SLCol4f getTexelf (SLfloat u, SLfloat v, SLuint imgIndex=0)
 SLGLTexture::getTexelf returns a pixel color from u & v texture coordinates. More...
 
SLCol4f getTexelf (const SLVec3f &cubemapDir)
 SLGLTexture::getTexelf returns a pixel color at the specified cubemap direction. More...
 
SLbool hasAlpha ()
 
SLMat4f tm ()
 
SLbool autoCalcTM3D () const
 
SLbool needsUpdate ()
 
SLstring typeName ()
 Returns the texture type as string. More...
 
SLstring typeShortName ()
 Returns the texture type short. More...
 
bool isTexture ()
 
SLstring minificationFilterName ()
 
SLstring magnificationFilterName ()
 
void build2DMipmaps (SLint target, SLuint index)
 
SLbool copyVideoImage (SLint camWidth, SLint camHeight, CVPixelFormatGL glFormat, SLuchar *data, SLbool isContinuous, SLbool isTopLeft)
 Copies the image data from a video camera into the current video image. More...
 
SLbool copyVideoImage (SLint camWidth, SLint camHeight, CVPixelFormatGL srcFormat, CVPixelFormatGL dstFormat, SLuchar *data, SLbool isContinuous, SLbool isTopLeft)
 
void calc3DGradients (SLint sampleRadius, const function< void(int)> &onUpdateProgress=nullptr)
 
void smooth3DGradients (SLint smoothRadius, function< void(int)> onUpdateProgress=nullptr)
 
SLVec2f dudv (SLfloat u, SLfloat v)
 
- Public Member Functions inherited from SLObject
 SLObject (const SLstring &Name="", const SLstring &url="")
 
virtual ~SLObject ()
 
void name (const SLstring &Name)
 
void url (const SLstring &url)
 
const SLstringname () const
 
const SLstringurl () const
 
- Public Member Functions inherited from SLEventHandler
 SLEventHandler ()
 
virtual ~SLEventHandler ()
 
virtual SLbool onMouseDown (const SLMouseButton button, const SLint x, const SLint y, const SLKey mod)
 
virtual SLbool onMouseUp (const SLMouseButton button, const SLint x, const SLint y, const SLKey mod)
 
virtual SLbool onMouseMove (const SLMouseButton button, const SLint x, const SLint y, const SLKey mod)
 
virtual SLbool onDoubleClick (const SLMouseButton button, const SLint x, const SLint y, const SLKey mod)
 
virtual SLbool onMouseWheel (const SLint delta, const SLKey mod)
 
virtual SLbool onTouch2Down (const SLint x1, const SLint y1, const SLint x2, const SLint y2)
 
virtual SLbool onTouch2Move (const SLint x1, const SLint y1, const SLint x2, const SLint y2)
 
virtual SLbool onTouch2Up (const SLint x1, const SLint y1, const SLint x2, const SLint y2)
 
virtual SLbool onTouch3Down (const SLint x1, const SLint y1)
 
virtual SLbool onTouch3Move (const SLint x1, const SLint y1)
 
virtual SLbool onTouch3Up (const SLint x1, const SLint y1)
 
virtual SLbool onKeyPress (const SLKey key, const SLKey mod)
 
virtual SLbool onKeyRelease (const SLKey key, const SLKey mod)
 
virtual SLbool onRotationPYR (const SLfloat pitchRAD, const SLfloat yawRAD, const SLfloat rollRAD)
 
void mouseRotationFactor (SLfloat rf)
 
SLfloat mouseRotationFactor ()
 

Private Attributes

function< void(bool, int, SLuint)> renderSlicesPTAsync
 
SLbool _calcDirect
 flag to calculate direct illumination More...
 
SLbool _calcIndirect
 flag to calculate indirect illumination More...
 

Additional Inherited Members

- Static Public Member Functions inherited from SLRaytracer
static SLuint numThreads ()
 
- Static Public Member Functions inherited from SLGLTexture
static SLTextureType detectType (const SLstring &filename)
 Detects the texture type from the filename appendix (See SLTexType def.) More...
 
static string internalFormatStr (int internalFormat)
 Returns the internal pixel format from OpenGL. More...
 
- Static Public Attributes inherited from SLGLTexture
static SLfloat maxAnisotropy = -1.0f
 Returns the derivation as [s,t]. More...
 
static SLuint totalNumBytesOnGPU = 0
 Total NO. of bytes used for textures on GPU. More...
 
- Protected Member Functions inherited from SLGLTexture
void load (const SLstring &filename, SLbool flipVertical=true, SLbool loadGrayscaleIntoAlpha=false)
 Loads the texture, converts color depth & applies vertical mirroring. More...
 
void load (const SLVCol4f &colors)
 Loads the 1D color data into an image of height 1. More...
 
- Protected Attributes inherited from SLRaytracer
function< void(bool, SLuint)> renderSlicesAsync
 
function< void(bool, SLuint)> sampleAAPixelsAsync
 
SLSceneView_sv
 Parent sceneview. More...
 
SLRTState _state
 RT state;. More...
 
SLCamera_cam
 shortcut to the camera More...
 
SLfloat _resolutionFactor
 screen to RT image size factor (default 1.0) More...
 
SLint _maxDepth
 Max. allowed recursion depth. More...
 
SLbool _doContinuous
 if true state goes into ready again More...
 
SLbool _doDistributed
 Flag for parallel distributed RT. More...
 
SLbool _doFresnel
 Flag for Fresnel reflection. More...
 
SLint _progressPC
 progress in % More...
 
SLfloat _renderSec
 Rendering time in seconds. More...
 
AvgFloat _raysPerMS
 Averaged rays per ms. More...
 
SLfloat _pxSize
 Pixel size. More...
 
SLVec3f _eye
 Camera position. More...
 
SLVec3f _la
 
SLVec3f _lu
 
SLVec3f _lr
 Camera lookat, lookup, lookright. More...
 
SLVec3f _bl
 Bottom left vector. More...
 
SLint _nextLine
 next line index to render RT in a thread More...
 
SLVPixel _aaPixels
 Vector for antialiasing pixels. More...
 
SLfloat _gamma
 gamma correction value More...
 
SLfloat _oneOverGamma
 one over gamma correction value More...
 
SLfloat _aaThreshold
 threshold for anti aliasing More...
 
SLint _aaSamples
 SQRT of uneven num. of AA samples. More...
 
- Protected Attributes inherited from SLGLTexture
CVVImage _images
 Vector of CVImage pointers. More...
 
SLuint _texID
 OpenGL texture ID. More...
 
SLTextureType _texType
 See SLTextureType. More...
 
SLint _width
 Texture image width in pixels (images exist either in _images or on the GPU or on both) More...
 
SLint _height
 Texture image height in pixels (images exist either in _images or on the GPU or on both) More...
 
SLint _depth
 3D Texture image depth (images exist either in _images or on the GPU or on both) More...
 
SLbyte _uvIndex
 Texture coordinate index in SLMesh (0 = default) More...
 
SLint _internalFormat
 Internal OpenGL format. More...
 
SLint _bytesPerPixel
 Bytes per texture image pixel (images exist either in _images or on the GPU or on both) More...
 
SLint _min_filter
 Minification filter. More...
 
SLint _mag_filter
 Magnification filter. More...
 
SLint _wrap_s
 Wrapping in s direction. More...
 
SLint _wrap_t
 Wrapping in t direction. More...
 
SLenum _target
 texture target More...
 
SLMat4f _tm
 texture matrix More...
 
SLuint _bytesOnGPU
 NO. of bytes on GPU. More...
 
SLuint _bytesInFile
 NO. of bytes in file. More...
 
SLbool _autoCalcTM3D
 Flag if texture matrix should be calculated from AABB for 3D mapping. More...
 
SLfloat _bumpScale
 Bump mapping scale factor. More...
 
SLbool _resizeToPow2
 Flag if image should be resized to n^2. More...
 
SLGLVertexArray _vaoSprite
 Vertex array object for sprite rendering. More...
 
std::atomic< bool > _needsUpdate {}
 Flag if image needs an single update. More...
 
std::mutex _mutex
 Mutex to protect parallel access (used in ray tracing) More...
 
SLbool _deleteImageAfterBuild
 Flag if images should be deleted after build on GPU. More...
 
SLbool _compressedTexture = false
 True for compressed texture format on GPU. More...
 
- Protected Attributes inherited from SLObject
SLstring _name
 name of an object More...
 
SLstring _url
 uniform resource locator More...
 
- Protected Attributes inherited from SLEventHandler
SLfloat _mouseRotationFactor
 Mouse rotation sensibility. More...
 
SLfloat _keyboardDeltaPos
 Delta dist. for keyboard translation. More...
 

Detailed Description

Classic Monte Carlo Pathtracing algorithm for real global illumination.

Definition at line 17 of file SLPathtracer.h.

Constructor & Destructor Documentation

◆ SLPathtracer()

SLPathtracer::SLPathtracer ( )

Definition at line 23 of file SLPathtracer.cpp.

24 {
25  name("PathTracer");
26  _calcDirect = true;
27  _calcIndirect = true;
28  gamma(2.2f);
29 }
const SLstring & name() const
Definition: SLObject.h:38
SLbool _calcIndirect
flag to calculate indirect illumination
Definition: SLPathtracer.h:44
SLbool _calcDirect
flag to calculate direct illumination
Definition: SLPathtracer.h:43
SLfloat gamma() const
Definition: SLRaytracer.h:123

◆ ~SLPathtracer()

SLPathtracer::~SLPathtracer ( )
inline

Definition at line 21 of file SLPathtracer.h.

21 { SL_LOG("Destructor : ~SLPathtracer"); }
#define SL_LOG(...)
Definition: SL.h:233

Member Function Documentation

◆ calcDirect() [1/2]

SLbool SLPathtracer::calcDirect ( ) const
inline

Definition at line 37 of file SLPathtracer.h.

37 { return _calcDirect; }

◆ calcDirect() [2/2]

void SLPathtracer::calcDirect ( SLbool  di)
inline

Definition at line 33 of file SLPathtracer.h.

33 { _calcDirect = di; }

◆ calcIndirect() [1/2]

SLbool SLPathtracer::calcIndirect ( ) const
inline

Definition at line 38 of file SLPathtracer.h.

38 { return _calcIndirect; }

◆ calcIndirect() [2/2]

void SLPathtracer::calcIndirect ( SLbool  ii)
inline

Definition at line 34 of file SLPathtracer.h.

34 { _calcIndirect = ii; }

◆ render()

SLbool SLPathtracer::render ( SLSceneView sv)

Main render function. The Path Tracing algorithm starts from here

Definition at line 34 of file SLPathtracer.cpp.

35 {
36  _sv = sv;
37  _state = rtBusy; // From here we state the PT as busy
38  _renderSec = 0.0f; // reset time
39  _progressPC = 0; // % rendered
40 
41  initStats(0); // init statistics
42  prepareImage();
43 
44  // Set second image for render update to the same size
45  while (_images.size() > 1)
46  {
47  delete _images[_images.size() - 1];
48  _images.pop_back();
49  }
50  _images.push_back(new CVImage(_sv->viewportW(),
51  _sv->viewportH(),
52  PF_rgb,
53  "Pathtracer"));
54  // Measure time
55  double t1 = GlobalTimer::timeS();
56 
57  // Lambda function for async slice rendering
58  renderSlicesPTAsync = [this](bool isMainThread, SLint curSample, SLuint threadNum)
59  {
60  SLPathtracer::renderSlices(isMainThread, curSample, threadNum);
61  };
62 
63  // Do multi-threading only in release config
64  SL_LOG("\n\nRendering with %d samples", _aaSamples);
65  SL_LOG("\nCurrent Sample: ");
66  for (int currentSample = 1; currentSample <= _aaSamples; currentSample++)
67  {
68  vector<thread> threads; // vector for additional threads
69  _nextLine = 0;
70 
71  // Start additional threads on the renderSlices function
72  for (SLuint t = 0; t < Utils::maxThreads() - 1; t++)
73  threads.emplace_back(renderSlicesPTAsync, false, currentSample, t);
74 
75  // Do the same work in the main thread
76  renderSlicesPTAsync(true, currentSample, 0);
77 
78  for (auto& thread : threads)
79  thread.join();
80 
81  _progressPC = (SLint)((SLfloat)currentSample / (SLfloat)_aaSamples * 100.0f);
82  }
83 
85  _raysPerMS.set((float)SLRay::totalNumRays() / _renderSec / 1000.0f);
86  _progressPC = 100;
87 
88  SL_LOG("\nTime to render image: %6.3fsec", _renderSec);
89 
91  return true;
92 }
@ PF_rgb
Definition: CVImage.h:36
float SLfloat
Definition: SL.h:173
unsigned int SLuint
Definition: SL.h:171
int SLint
Definition: SL.h:170
SLSceneView * sv
Definition: SLGLImGui.h:28
@ rtBusy
Definition: SLRaytracer.h:30
@ rtFinished
Definition: SLRaytracer.h:31
OpenCV image class with the same interface as the former SLImage class.
Definition: CVImage.h:64
static float timeS()
Definition: GlobalTimer.cpp:20
CVVImage _images
Vector of CVImage pointers.
Definition: SLGLTexture.h:302
void renderSlices(bool isMainThread, SLint currentSample, SLuint threadNum)
function< void(bool, int, SLuint)> renderSlicesPTAsync
Definition: SLPathtracer.h:41
static SLuint totalNumRays()
Total NO. of rays shot during RT.
Definition: SLRay.h:84
virtual void prepareImage()
SLSceneView * _sv
Parent sceneview.
Definition: SLRaytracer.h:138
SLint _nextLine
next line index to render RT in a thread
Definition: SLRaytracer.h:154
SLRTState _state
RT state;.
Definition: SLRaytracer.h:139
SLfloat _renderSec
Rendering time in seconds.
Definition: SLRaytracer.h:147
SLint _aaSamples
SQRT of uneven num. of AA samples.
Definition: SLRaytracer.h:161
virtual void initStats(SLint depth)
SLint _progressPC
progress in %
Definition: SLRaytracer.h:146
AvgFloat _raysPerMS
Averaged rays per ms.
Definition: SLRaytracer.h:148
SLint viewportH() const
Definition: SLSceneView.h:180
SLint viewportW() const
Definition: SLSceneView.h:179
void set(T value)
Sets the current value in the value array and builds the average.
Definition: Averaged.h:53
unsigned int maxThreads()
Returns in release config the max. NO. of threads otherwise 1.
Definition: Utils.cpp:1191

◆ renderSlices()

void SLPathtracer::renderSlices ( bool  isMainThread,
SLint  currentSample,
SLuint  threadNum 
)

Renders a slice of 4px width.

Definition at line 97 of file SLPathtracer.cpp.

100 {
101  if (!isMainThread)
102  {
103  PROFILE_THREAD(string("PT-Worker-") + std::to_string(threadNum));
104  }
105 
107 
108  // Time points
109  double t1 = 0;
110 
111  while (_nextLine < (SLint)_images[0]->width())
112  {
113  // The next section must be protected
114  // Making _nextLine an atomic was not sufficient.
115  _mutex.lock();
116  SLint minX = _nextLine;
117  _nextLine += 4;
118  _mutex.unlock();
119 
120  for (SLint x = minX; x < minX + 4; ++x)
121  {
122  for (SLuint y = 0; y < _images[0]->height(); ++y)
123  {
124  SLCol4f color(SLCol4f::BLACK);
125 
126  // calculate direction for primary ray - scatter with random variables for anti aliasing
127  SLRay primaryRay;
128  setPrimaryRay((SLfloat)((SLfloat)x - rnd01() + 0.5f),
129  (SLfloat)((SLfloat)y - rnd01() + 0.5f),
130  &primaryRay);
131 
132  ///////////////////////////////////
133  color += trace(&primaryRay, false);
134  ///////////////////////////////////
135 
136  // weight old and new color for continuous rendering
137  SLCol4f oldColor;
138  if (currentSample > 1)
139  {
140  CVVec4f c4f = _images[1]->getPixeli(x, (SLint)y);
141  oldColor.set(c4f[0], c4f[1], c4f[2], c4f[3]);
142 
143  // weight old color (examp. 3/4, 4/5, 5/6)
144  oldColor /= (SLfloat)currentSample;
145  oldColor *= (SLfloat)(currentSample - 1);
146 
147  // weight new color (examp. 1/4, 1/5, 1/6)
148  color /= (SLfloat)currentSample;
149 
150  // bring them together (examp. 4/4, 5/5, 6/6)
151  color += oldColor;
152  }
153 
154  color.clampMinMax(0.0f, 1.0f);
155 
156  // save image without gamma
157  _images[1]->setPixeliRGB(x,
158  (SLint)y,
159  CVVec4f(color.r,
160  color.g,
161  color.b,
162  color.a));
163 
164  color.gammaCorrect(_oneOverGamma);
165 
166  // image to render
167  _images[0]->setPixeliRGB(x,
168  (SLint)y,
169  CVVec4f(color.r,
170  color.g,
171  color.b,
172  color.a));
173  }
174 
175  // update image after 500 ms
176  if (_sv->onWndUpdate && isMainThread)
177  {
178  if (GlobalTimer::timeS() - t1 > 0.5f)
179  {
181  _sv->onWndUpdate(); // update window
182  t1 = GlobalTimer::timeS();
183  }
184  }
185  }
186  }
187 }
cv::Vec4f CVVec4f
Definition: CVTypedefs.h:54
#define PROFILE_FUNCTION()
Definition: Instrumentor.h:41
#define PROFILE_THREAD(name)
Definition: Profiler.h:38
SLfloat rnd01()
Definition: SLRay.cpp:39
SLuint width()
Definition: SLGLTexture.h:218
std::mutex _mutex
Mutex to protect parallel access (used in ray tracing)
Definition: SLGLTexture.h:324
SLCol4f trace(SLRay *ray, SLbool em)
Ray class with ray and intersection properties.
Definition: SLRay.h:40
SLfloat _oneOverGamma
one over gamma correction value
Definition: SLRaytracer.h:157
void renderUIBeforeUpdate()
Must be called before an inbetween frame updateRec.
void setPrimaryRay(SLfloat x, SLfloat y, SLRay *primaryRay)
Set the parameters of a primary ray for a pixel position at x, y.
cbOnWndUpdate onWndUpdate
C-Callback for app for intermediate window repaint.
Definition: SLSceneView.h:141
static SLVec4 BLACK
Definition: SLVec4.h:213
void set(const T X, const T Y, const T Z, const T W=1)
Definition: SLVec4.h:49
void clampMinMax(const T min, const T max)
Definition: SLVec4.h:119

◆ saveImage()

void SLPathtracer::saveImage ( )
virtual

Saves the current PT image as PNG image.

Reimplemented from SLRaytracer.

Definition at line 421 of file SLPathtracer.cpp.

422 {
423  static SLint no = 0;
424  SLchar filename[255];
425  snprintf(filename,
426  sizeof(filename),
427  "Pathtraced_%d_%d.png",
428  _aaSamples,
429  no++);
430  _images[0]->savePNG(filename);
431 }
char SLchar
Definition: SL.h:162

◆ shade()

SLCol4f SLPathtracer::shade ( SLRay ray,
SLCol4f mat 
)

Calculates direct illumination for intersection point of ray

Definition at line 361 of file SLPathtracer.cpp.

362 {
363  SLCol4f color = SLCol4f::BLACK;
364  SLCol4f diffuseColor = SLCol4f::BLACK;
365  SLVec3f L, N;
366  SLfloat lightDist, LdN, df, spotEffect, lighted;
367 
368  // loop over light sources in scene
369  for (auto* light : _sv->s()->lights())
370  {
371  if (light && light->isOn())
372  {
373  N.set(ray->hitNormal);
374  L.sub(light->positionWS().vec3(), ray->hitPoint);
375  lightDist = L.length();
376  L /= lightDist;
377  LdN = L.dot(N);
378 
379  // check shadow ray if hit point is towards the light
380  lighted = (SLfloat)((LdN > 0) ? light->shadowTestMC(ray,
381  L,
382  lightDist,
383  _sv->s()->root3D())
384  : 0);
385 
386  // calculate spot effect if light is a spotlight
387  if (lighted > 0.0f && light->spotCutOffDEG() < 180.0f)
388  {
389  SLfloat LdS = std::max(-L.dot(light->spotDirWS()), 0.0f);
390 
391  // check if point is in spot cone
392  if (LdS > light->spotCosCut())
393  {
394  spotEffect = pow(LdS, (SLfloat)light->spotExponent());
395  }
396  else
397  {
398  lighted = 0.0f;
399  spotEffect = 0.0f;
400  }
401  }
402  else
403  spotEffect = 1.0f;
404 
405  if (lighted > 0.0f)
406  {
407  df = std::max(LdN, 0.0f); // diffuse factor
408 
409  // material color * light emission * LdN * brdf(1/pi) * lighted(for soft shadows)
410  diffuseColor = (*mat & (light->diffuse() * df) * Utils::ONEOVERPI * lighted);
411  }
412 
413  color += light->attenuation(lightDist) * spotEffect * diffuseColor;
414  }
415  }
416 
417  return color;
418 }
SLVec3f hitPoint
Point of intersection.
Definition: SLRay.h:110
SLVec3f hitNormal
Surface normal at intersection point.
Definition: SLRay.h:111
SLVLight & lights()
Definition: SLScene.h:107
void root3D(SLNode *root3D)
Definition: SLScene.h:78
SLScene * s()
Definition: SLSceneView.h:167
T length() const
Definition: SLVec3.h:122
void set(const T X, const T Y, const T Z)
Definition: SLVec3.h:59
T dot(const SLVec3 &v) const
Definition: SLVec3.h:117
void sub(const SLVec3 &a, const SLVec3 &b)
Definition: SLVec3.h:113
static const float ONEOVERPI
Definition: Utils.h:241

◆ trace()

SLCol4f SLPathtracer::trace ( SLRay ray,
SLbool  em 
)

Recursively traces ray in scene.

Definition at line 192 of file SLPathtracer.cpp.

193 {
194  SLCol4f finalColor(ray->backgroundColor);
195 
196  // Participating Media init
197  SLfloat absorption = 1.0f; // used to calculate absorption along the ray
198  SLfloat scaleBy = 1.0f; // used to scale surface reflectance at the end of random walk
199 
200  // Intersect scene
201  SLNode* root = _sv->s()->root3D();
202  if (root) root->hitRec(ray);
203 
204  // end of recursion - no object hit OR max depth reached
205  if (ray->length >= FLT_MAX || ray->depth > maxDepth())
206  return SLCol4f::BLACK;
207 
208  // hit material
209  SLMaterial* mat = ray->hitMesh->mat();
210  ray->hitMesh->preShade(ray);
211 
212  // set object color
213  SLCol4f objectColor = SLCol4f::BLACK;
214  if (ray->hitMatIsDiffuse())
215  objectColor = mat->diffuse();
216  else if (ray->hitMatIsReflective())
217  objectColor = mat->specular();
218  else if (ray->hitMatIsTransparent())
219  objectColor = mat->transmissive();
220 
221  // set object emission
222  SLCol4f objectEmission = mat->emissive();
223  SLfloat maxEmission = objectEmission.maxXYZ();
224 
225  // stop recursion if light source is hit
226  if (maxEmission > 0)
227  {
228  if (ray->depth == 1)
229  return mat->emissive() * absorption;
230  else
231  return mat->emissive() * absorption * em;
232  }
233 
234  // add absorption to base color from Participating Media
235  objectColor = objectColor * absorption;
236 
237  // diffuse reflection
238  if (ray->hitMatIsDiffuse())
239  {
240  // Add component wise the texture color
241  if (mat->numTextures() > 0)
242  {
243  objectColor &= ray->hitTexColor;
244  }
245 
246  if (_calcDirect)
247  finalColor += shade(ray, &objectColor) * scaleBy;
248 
249  if (_calcIndirect)
250  {
251  SLRay scatter;
252  ray->diffuseMC(&scatter);
253 
254  // material emission, material diffuse and recursive indirect illumination
255  finalColor += (trace(&scatter, false) & objectColor) * scaleBy;
256  }
257  }
258  else if (ray->hitMatIsReflective())
259  {
260  // scatter toward perfect specular direction
261  SLRay reflected;
262  ray->reflect(&reflected);
263 
264  // scatter around perfect reflected direction only if material not perfect
265  if (mat->shininess() < SLMaterial::PERFECT)
266  {
267  // rotation matrix for glossy
268  SLMat3f rotMat;
269  SLVec3f rotAxis((SLVec3f(0.0f, 0.0f, 1.0f) ^ reflected.dir).normalize());
270  SLfloat rotAngle = acos(reflected.dir.z);
271  rotMat.rotation(rotAngle * 180.0f * Utils::ONEOVERPI, rotAxis);
272  ray->reflectMC(&reflected, rotMat);
273  }
274 
275  // shininess contribution * recursive indirect illumination and matrial base color
276  finalColor += ((mat->shininess() + 2.0f) / (mat->shininess() + 1.0f) *
277  (trace(&reflected, true) & objectColor)) *
278  scaleBy;
279  }
280  else if (ray->hitMatIsTransparent())
281  {
282  // scatter toward perfect transmissive direction
283  SLRay refracted;
284  ray->refract(&refracted);
285 
286  // init Schlick's approximation
287  SLVec3f rayDir = ray->dir;
288  rayDir.normalize();
289  SLVec3f refrDir = refracted.dir;
290  refrDir.normalize();
291  SLfloat n, nt;
292  SLVec3f hitNormal = ray->hitNormal;
293  hitNormal.normalize();
294 
295  // ray from outside in
296  if (ray->isOutside)
297  {
298  n = 1.0f;
299  nt = mat->kn();
300  }
301  else // ray from inside out
302  {
303  n = mat->kn();
304  nt = 1.0f;
305  }
306 
307  // calculate Schlick's approx.
308  SLfloat nbig, nsmall;
309  nbig = n > nt ? n : nt;
310  nsmall = n < nt ? n : nt;
311  SLfloat R0 = ((nbig - nsmall) / (nbig + nsmall));
312  R0 = R0 * R0;
313  SLbool into = (rayDir * hitNormal) < 0;
314  SLfloat c = 1.0f - (into ? (-rayDir * hitNormal) : (refrDir * hitNormal));
315  SLfloat schlick = R0 + (1 - R0) * c * c * c * c * c;
316 
317  SLfloat P = 0.25f + 0.5f * schlick; // probability of reflectance
318  SLfloat reflectionProbability = schlick / P;
319  SLfloat refractionProbability = (1.0f - schlick) / (1.0f - P);
320 
321  // scatter around perfect transmissive direction only if material not perfect
322  if (mat->translucency() < SLMaterial::PERFECT)
323  {
324  // rotation matrix for translucency
325  SLMat3f rotMat;
326  SLVec3f rotAxis((SLVec3f(0.0f, 0.0f, 1.0f) ^ refracted.dir).normalize());
327  SLfloat rotAngle = acos(refracted.dir.z);
328  rotMat.rotation((SLfloat)(rotAngle * 180.0f * Utils::ONEOVERPI), rotAxis);
329  ray->refractMC(&refracted, rotMat);
330  }
331 
332  // probability of reflection
333  if (rnd01() > (0.25f + 0.5f * schlick))
334  // scatter toward transmissive direction
335  finalColor += ((mat->translucency() + 2.0f) /
336  (mat->translucency() + 1.0f) *
337  (trace(&refracted, true) & objectColor) *
338  refractionProbability) *
339  scaleBy;
340  else
341  {
342  // scatter toward perfect specular direction
343  SLRay scattered;
344  ray->reflect(&scattered);
345 
346  // shininess contribution * recursive indirect illumination and material basecolor
347  finalColor += ((mat->shininess() + 2.0f) /
348  (mat->shininess() + 1.0f) *
349  (trace(&scattered, true) & objectColor) *
350  reflectionProbability) *
351  scaleBy;
352  }
353  }
354 
355  return finalColor;
356 }
bool SLbool
Definition: SL.h:175
SLVec3< SLfloat > SLVec3f
Definition: SLVec3.h:318
void rotation(const T angleDEG, const SLVec3< T > &axis)
Sets the rotation components
Definition: SLMat3.h:392
Defines a standard CG material with textures and a shader program.
Definition: SLMaterial.h:56
void translucency(SLfloat transl)
Definition: SLMaterial.h:176
static SLfloat PERFECT
PM: shininess/translucency limit.
Definition: SLMaterial.h:238
void specular(const SLCol4f &spec)
Definition: SLMaterial.h:173
void diffuse(const SLCol4f &diff)
Definition: SLMaterial.h:171
SLuint numTextures()
Definition: SLMaterial.h:226
void shininess(SLfloat shin)
Definition: SLMaterial.h:177
void transmissive(const SLCol4f &transm)
Definition: SLMaterial.h:175
void emissive(const SLCol4f &emis)
Definition: SLMaterial.h:174
void kn(SLfloat kn)
Definition: SLMaterial.h:199
SLMaterial * mat() const
Definition: SLMesh.h:177
virtual void preShade(SLRay *ray)
Definition: SLMesh.cpp:1470
SLNode represents a node in a hierarchical scene graph.
Definition: SLNode.h:147
virtual bool hitRec(SLRay *ray)
Definition: SLNode.cpp:508
SLCol4f shade(SLRay *ray, SLCol4f *mat)
SLbool hitMatIsTransparent() const
Returns true if the hit material transmission color is not black.
Definition: SLRay.h:205
bool reflectMC(SLRay *reflected, const SLMat3f &rotMat) const
Definition: SLRay.cpp:332
SLCol4f backgroundColor
Background color at pixel x,y.
Definition: SLRay.h:100
SLMesh * hitMesh
Points to the intersected mesh.
Definition: SLRay.h:106
SLbool isOutside
Flag if ray is inside of a material.
Definition: SLRay.h:95
SLint depth
Recursion depth for ray tracing.
Definition: SLRay.h:78
SLVec3f dir
Direction vector of ray in WS.
Definition: SLRay.h:76
void refract(SLRay *refracted)
Definition: SLRay.cpp:197
SLbool hitMatIsReflective() const
Returns true if the hit material specular color is not black.
Definition: SLRay.h:194
SLfloat length
length from origin to an intersection
Definition: SLRay.h:77
void diffuseMC(SLRay *scattered) const
Definition: SLRay.cpp:429
void reflect(SLRay *reflected) const
Definition: SLRay.cpp:156
SLCol4f hitTexColor
Color at intersection for texture or color attributes.
Definition: SLRay.h:112
void refractMC(SLRay *refracted, const SLMat3f &rotMat) const
Definition: SLRay.cpp:384
SLbool hitMatIsDiffuse() const
Returns true if the hit material diffuse color is not black.
Definition: SLRay.h:216
SLint maxDepth() const
Definition: SLRaytracer.h:114
SLVec3 & normalize()
Definition: SLVec3.h:124
T z
Definition: SLVec3.h:43
T maxXYZ()
Definition: SLVec4.h:141

Member Data Documentation

◆ _calcDirect

SLbool SLPathtracer::_calcDirect
private

flag to calculate direct illumination

Definition at line 43 of file SLPathtracer.h.

◆ _calcIndirect

SLbool SLPathtracer::_calcIndirect
private

flag to calculate indirect illumination

Definition at line 44 of file SLPathtracer.h.

◆ renderSlicesPTAsync

function<void(bool, int, SLuint)> SLPathtracer::renderSlicesPTAsync
private

Definition at line 41 of file SLPathtracer.h.


The documentation for this class was generated from the following files: