Path Tracing
Loading...
Searching...
No Matches
main.cpp File Reference

Main code. More...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <vector>
#include <algorithm>
#include <thread>
#include <atomic>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "stb_image_write.h"
#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
#include "common/shader.hpp"
#include "mesh.hpp"
#include "bvh.hpp"
#include "config.hpp"
#include "loader.hpp"
#include "texture.hpp"
#include "denoiser.hpp"
Include dependency graph for main.cpp:

Classes

struct  Metrics

Macros

#define GLEW_NO_GLU
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define VERSION   "1.8.1"
#define VERSION_NOTE   ""
#define WINDOW_TITLE   "Path Tracer"
#define WINDOW_TITLE_VERSION   WINDOW_TITLE " v" VERSION " " VERSION_NOTE

Functions

void onKeyPress (GLFWwindow *, int key, int, int action, int)
void onMouseMove (GLFWwindow *, double x, double y)
void onMouseButton (GLFWwindow *w, int button, int action, int)
void onMouseScroll (GLFWwindow *w, double, double yoffset)
void onWindowResize (GLFWwindow *, int width, int height)
void toggleFullscreen ()
vec3 cameraForward ()
void zoomToFit ()
 Repositions the camera to frame the model on scene.
void setPreviewResolution ()
 Switches the render resolution to the low-res mode.
void setFullResolution ()
 Switches the render resolution to full render mode.
void setPreviewMode (bool enabled)
 Toggle Preview Mode Pins the renderer at the low preview resolution and stops it from auto-upgrading to full res until disabling and starting a fresh render.
void processMovement ()
 Process WASD movement.
void formatTime (double seconds, char *buf, int buf_size)
 Formats a duration in seconds as "Xs" or "XmYs".
bool initShaders ()
void reloadShaders ()
void initUniforms ()
 Caches every uniform location of the active shader into Renderer.
void loadScene ()
 Loads the scene and imports the model on a secondary thread.
void resetModel ()
void uploadConfig ()
 Updates every RenderConfig parameter, called when any changed.
void applyConfig ()
 Calls uploadConfig and resets the scene.
void uploadCamera ()
void uploadCornellTopLight ()
void uploadPrismDemoLight ()
void uploadSun ()
bool transferDataToGPU (void)
 First time GPU setup.
void cleanDataFromGPU ()
void display (void)
void clearTextures ()
void setDenoiseCheckpoints ()
 Computes at which samples the denoiser should run.
void createDenoisedTex (int w, int h)
 Allocates the denoised output texture at a width w and height h.
void resetAccumulation ()
 Restarts progressive accumulation back to 0.
void draw (void)
 Renders one full frame in the order: path trace, denoise, autoEV, display, grid, UI.
void saveScreenshot ()
 Takes a screenshot of the render.
float computeTargetExposureEV ()
void updateAutoExposure (float speed)
void drawGrid ()
 Renders the world view grid.
void drawCompositionGuides ()
 Draws photography-style framing guides and an aspect-ratio crop preview mask over the viewport Doesn't touch the shader, render or camera, only a viewfinder to position the camera.
void syncResolutionDropdown ()
 Syncs the UI to the current window size.
void drawUI ()
void applyResolution (int w, int h)
bool useMoveKeys ()
 Checks if the user pressed the WASD keys.
int main (void)
void applyLensPreset (int idx)
 Copies a LensPreset into config and applies it.
vector< string > scanModels (const string &models_dir)
 Recursively lists supported model files under the /models directory.
vector< string > scanHDRI (const string &hdri_dir)
 Recursively lists HDRI files under the /hdri directory.
void runDenoiser (int checkpoint_num, int total)
 Reads back the accumulation texture, runs OIDN and sends the result.
glm::vec3 displayPixelCPU (glm::vec3 linear_color, float alpha, glm::vec2 uv, float exposure_ev, int tone_mapping, float vignette_strength)
 Mirror of display.frag's per-pixel pipeline exposure → tone map + gamma → vignette → composite.
void computeAspectCropRect (int frame_w, int frame_h, int aspect_frame, int &out_x0, int &out_y0, int &out_w, int &out_h)
void addContrastLine (ImDrawList *dl, ImVec2 p1, ImVec2 p2, float thickness)
 Draws a line that shows clearly in dark and light backgrounds.

Variables

GLFWwindow * window
Renderer renderer
CameraConfig camera
Denoiser denoiser
double mouse_last_x = 0.0
double mouse_last_y = 0.0
bool mouse_first = true
bool mouse_captured = false
Metrics metrics
RenderConfig config
const char * txt_sep = "---------------------------------------------"
vector< GPULight > analytic_lights
int sun_light_index = -1
int current_res_idx = 0
const int res_w [] = {1280, 1920, 2560, 4096, 0, 0}
const int res_h [] = {720, 1080, 1440, 2160, 0, 0}

Detailed Description

Main code.

Author
Leonel Matos
Date
2026-03-24

Macro Definition Documentation

◆ GLEW_NO_GLU

#define GLEW_NO_GLU

◆ STB_IMAGE_WRITE_IMPLEMENTATION

#define STB_IMAGE_WRITE_IMPLEMENTATION

◆ VERSION

#define VERSION   "1.8.1"

◆ VERSION_NOTE

#define VERSION_NOTE   ""

◆ WINDOW_TITLE

#define WINDOW_TITLE   "Path Tracer"

◆ WINDOW_TITLE_VERSION

#define WINDOW_TITLE_VERSION   WINDOW_TITLE " v" VERSION " " VERSION_NOTE

Function Documentation

◆ addContrastLine()

void addContrastLine ( ImDrawList * dl,
ImVec2 p1,
ImVec2 p2,
float thickness )

Draws a line that shows clearly in dark and light backgrounds.

◆ applyConfig()

void applyConfig ( )

Calls uploadConfig and resets the scene.

◆ applyLensPreset()

void applyLensPreset ( int idx)

Copies a LensPreset into config and applies it.

See also
LENS_PRESETS, applyConfig

◆ applyResolution()

void applyResolution ( int w,
int h )

◆ cameraForward()

vec3 cameraForward ( )
Returns
vec3 camera forward vector from pitch and yaw

◆ cleanDataFromGPU()

void cleanDataFromGPU ( )

◆ clearTextures()

void clearTextures ( )

◆ computeAspectCropRect()

void computeAspectCropRect ( int frame_w,
int frame_h,
int aspect_frame,
int & out_x0,
int & out_y0,
int & out_w,
int & out_h )
inline

◆ computeTargetExposureEV()

float computeTargetExposureEV ( )

subsampling area, defines an estimate average for performance Not a fixed number because different resolutions might not apply well So adaptive stride looks for a constant sample regardless of resolution or Render Mode

pixels below this are excluded

standart photographic middle-gray target, 18%

◆ createDenoisedTex()

void createDenoisedTex ( int w,
int h )

Allocates the denoised output texture at a width w and height h.

◆ display()

void display ( void )

◆ displayPixelCPU()

glm::vec3 displayPixelCPU ( glm::vec3 linear_color,
float alpha,
glm::vec2 uv,
float exposure_ev,
int tone_mapping,
float vignette_strength )
inline

Mirror of display.frag's per-pixel pipeline exposure → tone map + gamma → vignette → composite.

Parameters
linear_colorraw HDR color sampled from render texture
alpharender texture's alpha channel
uvpixel-center position in the frame[0,1]
Returns
vec3 pixel with all pipeline applied
See also
toneMapCPU, computeAspectCropRect, saveScreenshot, display.frag

◆ draw()

void draw ( void )

Renders one full frame in the order: path trace, denoise, autoEV, display, grid, UI.

◆ drawCompositionGuides()

void drawCompositionGuides ( )

Draws photography-style framing guides and an aspect-ratio crop preview mask over the viewport Doesn't touch the shader, render or camera, only a viewfinder to position the camera.

Note
Drawn on ImGui's background draw list, so it stays on top ot the render and beneath the Scene Editor window

◆ drawGrid()

void drawGrid ( )

Renders the world view grid.

◆ drawUI()

void drawUI ( )

Environment Map HDRI

See external window for env map selector, outside of the side windows

◆ formatTime()

void formatTime ( double seconds,
char * buf,
int buf_size )

Formats a duration in seconds as "Xs" or "XmYs".

◆ initShaders()

bool initShaders ( )

Compiles and links all shaders

Returns
true on success

◆ initUniforms()

void initUniforms ( )

Caches every uniform location of the active shader into Renderer.

◆ loadScene()

void loadScene ( )

Loads the scene and imports the model on a secondary thread.

◆ main()

int main ( void )

◆ onKeyPress()

void onKeyPress ( GLFWwindow * ,
int key,
int ,
int action,
int  )

◆ onMouseButton()

void onMouseButton ( GLFWwindow * w,
int button,
int action,
int  )

◆ onMouseMove()

void onMouseMove ( GLFWwindow * ,
double x,
double y )

◆ onMouseScroll()

void onMouseScroll ( GLFWwindow * w,
double ,
double yoffset )

Simulate Unity's camera control speed multiplier Use SHIFT + Mouse Scroll to change camera speed

◆ onWindowResize()

void onWindowResize ( GLFWwindow * ,
int width,
int height )

◆ processMovement()

void processMovement ( )

Process WASD movement.

◆ reloadShaders()

void reloadShaders ( )

◆ resetAccumulation()

void resetAccumulation ( )

Restarts progressive accumulation back to 0.

◆ resetModel()

void resetModel ( )

◆ runDenoiser()

void runDenoiser ( int checkpoint_num,
int total )

Reads back the accumulation texture, runs OIDN and sends the result.

Parameters
checkpoint_numindex of checkpoint
totalTotal number of checkpoints

◆ saveScreenshot()

void saveScreenshot ( )

Takes a screenshot of the render.

◆ scanHDRI()

vector< string > scanHDRI ( const string & hdri_dir)

Recursively lists HDRI files under the /hdri directory.

Parameters
hdri_dirDirectory to scan
Returns
Sorted list of file paths

◆ scanModels()

vector< string > scanModels ( const string & models_dir)

Recursively lists supported model files under the /models directory.

Parameters
models_dirDirectory to scan
Returns
Sorted list of file paths

◆ setDenoiseCheckpoints()

void setDenoiseCheckpoints ( )

Computes at which samples the denoiser should run.

◆ setFullResolution()

void setFullResolution ( )

Switches the render resolution to full render mode.

◆ setPreviewMode()

void setPreviewMode ( bool enabled)

Toggle Preview Mode Pins the renderer at the low preview resolution and stops it from auto-upgrading to full res until disabling and starting a fresh render.

◆ setPreviewResolution()

void setPreviewResolution ( )

Switches the render resolution to the low-res mode.

◆ syncResolutionDropdown()

void syncResolutionDropdown ( )

Syncs the UI to the current window size.

◆ toggleFullscreen()

void toggleFullscreen ( )

◆ transferDataToGPU()

bool transferDataToGPU ( void )

First time GPU setup.

Returns
true on success

◆ updateAutoExposure()

void updateAutoExposure ( float speed)

Handler for computeTargetExposureEV, gradually changes EV value based on speed

Parameters
speedHow quick the EV change applies, 0 = frozen, 1 = instant, 0-1 = gradual

◆ uploadCamera()

void uploadCamera ( )

◆ uploadConfig()

void uploadConfig ( )

Updates every RenderConfig parameter, called when any changed.

◆ uploadCornellTopLight()

void uploadCornellTopLight ( )

Brute-forced way to set the Cornell's top light to follow the light types emissions, since now plain geometry aren't considered LIGHT types

◆ uploadPrismDemoLight()

void uploadPrismDemoLight ( )

◆ uploadSun()

void uploadSun ( )

◆ useMoveKeys()

bool useMoveKeys ( )

Checks if the user pressed the WASD keys.

Returns
true if any WASD key pressed

◆ zoomToFit()

void zoomToFit ( )

Repositions the camera to frame the model on scene.

Note
Uses renderer.current_bounds
See also
current_bounds_min, current_bounds_max

Variable Documentation

◆ analytic_lights

vector<GPULight> analytic_lights

◆ camera

CameraConfig camera

◆ config

RenderConfig config

◆ current_res_idx

int current_res_idx = 0
inline

◆ denoiser

Denoiser denoiser

◆ metrics

Metrics metrics

◆ mouse_captured

bool mouse_captured = false

◆ mouse_first

bool mouse_first = true

◆ mouse_last_x

double mouse_last_x = 0.0

◆ mouse_last_y

double mouse_last_y = 0.0

◆ renderer

Renderer renderer

◆ res_h

const int res_h[] = {720, 1080, 1440, 2160, 0, 0}

◆ res_w

const int res_w[] = {1280, 1920, 2560, 4096, 0, 0}

◆ sun_light_index

int sun_light_index = -1

◆ txt_sep

const char* txt_sep = "---------------------------------------------"

◆ window

GLFWwindow* window