API reference
User
-
void init(const Json &prop = {})
Initialize the framework.
The framework must be initialized with this function before any use of other APIs. The properties are passed as JSON format and used to initialize the internal subsystems of the framework. This function initializes some subsystems with default types. If you want to configure the subsystem, you want to call each
init()
function afterwards.- See
example/blank.cpp
- Parameters
prop – Properties for configuration.
-
void shutdown()
Shutdown the framework.
This function explicit shutdowns the framework.
Shutdown the framework.
Shutdown progress reporter context.
Shutdown parallel context.
Shutdown logger context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework. You may consider to use
ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.
-
void reset()
Reset the internal state of the framework.
This function resets underlying states including assets and scene to the initial state. The global contexts remains same.
-
void info()
Print information about Lightmetrica.
-
AssetGroup *assets()
Get underlying collection of assets.
- Returns
Instance.
-
void save_state_to_file(const std::string &path)
Save internal state to a file.
- Parameters
path – Output path.
-
void load_state_from_file(const std::string &path)
Load internal state from a file.
- Parameters
path – Input path.
-
template<typename T>
T *load(const std::string &name, const std::string &impl_key, const Json &prop) Load an asset with given type.
- Template Parameters
T – Component interface type.
- Parameters
name – Name of the asset.
impl_key – Key of component implementation in
interface::implementation
format.prop – Properties.
Log
-
enum LogLevel
Log level.
Log messages have their own importance levels. When you want to categorize the log messages according to the importance, you can use convenience macros to generate messages with corresponding importance levels. For instance,
LM_ERROR()
macro generates a message withErr
log level.Values:
-
enumerator Debug
Debug message. You may use this level to specify the error messages are only emitted in a Debug session. You can generate a log message with this type by
LM_DEBUG()
macro.
-
enumerator Info
Information message. You may use this level to notice information to the user. Typical usage is to indicate the execution flow of the application before/after the execution enters/leaves the codes of heavy computation or IO. You can generate a log message with this type by
LM_INFO()
macro.
-
enumerator Warn
Warning message. You may use this level to give warning to the user. Usage might be to convey inconsistent yet continuable state of the execution such as handling of default arguments.
-
enumerator Err
Error message. This error level notifies you an error happens in the execution. The error often comes along with immediate shutdown of the renderer.
-
enumerator Progress
Progress message. The messages of this log level indicates special message type used in the progress update where the message are used specifically for the interactive update of the progress report.
-
enumerator ProgressEnd
End of progress message. The message indicates special message type used in the end of the progress message.
-
enumerator Debug
-
constexpr const char *DefaultType = "default"
Default logger type.
-
void init(const std::string &type = DefaultType, const Json &prop = {})
Initialize logger context.
This function initializes logger subsystem with specified type and properties.
- Parameters
type – Type of log subsystem.
prop – Configuration properties.
-
void shutdown()
Shutdown logger context.
This function shutdowns logger subsystem. You may consider to use
lm::log::ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.Shutdown logger context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework. You may consider to use
ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.
-
void set_severity(int severity)
Set severity of the log.
The log messages with severity value larger or equal to the given value will be rendered.
- Parameters
severity – Severity.
-
void log(LogLevel level, int severity, const char *filename, int line, const char *message)
Write log message.
This function posts a log message of specific log level to the logger subsystem. The behavior of this function depends on the implementation of the logger. You may want to use convenience macros instead of this function because the macros automatically extracts filename and line number for you.
- Parameters
level – Log level.
severity – Severity.
filename – Filename where the log message are generated.
line – Line of the code where the log message are generated.
message – Log message.
-
template<typename ...Args>
void log(LogLevel level, int severity, const char *filename, int line, const std::string &message, Args&&... args) Write log message with formatting.
This version of the log function posts a log message with formatting. The specification follows replacement-based format API by fmt library.
- Parameters
level – Log level.
severity – Severity.
filename – Filename where the log message are generated.
line – Line of the code where the log message are generated.
message – Log message.
args – List of arguments to be replaced according to format in the log message.
-
void update_indentation(int n)
Update indentation.
The log messages can be indented for better visibility. This function controls the indentation level by increment or decrement of the indentation by an integer. For instance,
-1
subtracts one indentation level.- Parameters
n – Increase / decrease of the indentration.
-
LM_LOG(severity, message, ...)
Post a log message with a user-defined severity.
- Parameters
severity – User-defined severity by integer.
message – Log message.
... – Parameters for the format in the log message.
-
LM_ERROR(message, ...)
Post a log message with error level.
- Parameters
message – Log message.
... – Parameters for the format in the log message.
-
LM_WARN(message, ...)
Post a log message with warning level.
- Parameters
message – Log message.
... – Parameters for the format in the log message.
-
LM_INFO(message, ...)
Post a log message with information level.
- Parameters
message – Log message.
... – Parameters for the format in the log message.
-
LM_DEBUG(message, ...)
Post a log message with debug level.
- Parameters
message – Log message.
... – Parameters for the format in the log message.
-
LM_PROGRESS(message, ...)
Log progress outputs.
- Parameters
message – Log message.
... – Parameters for the format in the log message.
-
LM_PROGRESS_END(message, ...)
Log end of progress outputs.
- Parameters
message – Log message.
... – Parameters for the format in the log message.
-
LM_INDENT()
Adds an indentation in the current scope.
Example:
// Indentation = 0. Produces " message 1" LM_INFO("message 1"); { // Indentation = 1. Produces ".. message 2" LM_INDENT(); LM_INFO("message 2"); } // Indentation = 0. Produces " message 3" LM_INFO("message 3");
-
struct LogIndenter
- #include <logger.h>
Log indent contol.
The class controls the indentation level according to the scopes. You want to use convenience macro
LM_INDENT()
instead of this function.
-
class ScopedInit
- #include <logger.h>
Scoped guard of
init
andshutdown
functions.
Exception
-
enum Error
Error code.
Represents the types of errors used in the framework. This error code is associated with
Exception
.Values:
-
enumerator None
Used for other errors.
-
enumerator Unsupported
Feature is unsupported in the platform.
-
enumerator Uninitialized
Feature is uninitialized.
-
enumerator InvalidArgument
Argument is invalid.
-
enumerator Unimplemented
Feature is unimplemented.
-
enumerator IOError
Failed to load or save something.
-
enumerator FailedToRender
Failed to render an image.
-
enumerator None
-
void init(const Json &prop = {})
Initialize exception context.
This function initializes exception subsystem of the framework. The function is implicitly called by the framework so the user do not want to explicitly call this function.
- Parameters
prop – Properties for configuration.
-
void shutdown()
Shutdown exception context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework. You may consider to use
ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.
-
void enable_fpex()
Enable floating point exceptions.
This function enables floating-point exception. You may use
ScopedDisableFPEx
class to automatically enable/disable the floating point exception inside a scope.
-
void disable_fpex()
Disable floating point exceptions.
This function disables floating-point exception. You may use
ScopedDisableFPEx
class to automatically enable/disable the floating point exception inside a scope.
-
void stack_trace()
Print stack trace.
This function prints a stack trace of the current frame. You may find it useful when you want to display additional information as well as an error message.
-
LM_THROW_EXCEPTION(error, message, ...)
Throw exception.
Convenience macro to throw
Exception
. This macro reports the file and line of the code where the exception being raised.- Parameters
error – Error code.
message – Error message.
... – Arguments to format the message.
-
LM_THROW_EXCEPTION_DEFAULT(error)
Throw exception with default message.
Convenience macro to throw
Exception
with default message. This macro reports the file and line of the code where the exception being raised.- Parameters
error – Error code.
-
class ScopedDisableFPEx
- #include <exception.h>
Scoped disable of floating point exception.
A convenience class when you want to temporarily disable floating point exceptions. This class is useful when you want to use some external libraries that does not check strict floating point exceptions.
Example:
// Floating-point exception is enabled enableFPEx(); { // Temporarily disables floating-point exception inside this scope. ScopedDisableFPEx disableFp_; // ... } // Floating-point exception is enabled again // ...
-
class ScopedInit
- #include <exception.h>
Scoped guard of
init
andshutdown
functions.
-
class lm::Exception : public exception
- #include <exception.h>
Represents the exception used in the framework. The user want to use convenience macro
LM_THROW()
instead of throwing this exception directly.Public Functions
-
template<typename ...Args>
inline Exception(Error error, const std::string &file, int line, const std::string &message) Constructor.
Constructs the exception with error type and error message.
- Parameters
error – Error code.
file – File name.
line – Line of code.
message – Error message.
... – Arguments to format the message.
-
template<typename ...Args>
inline Exception(Error error, const std::string &file, int line, const std::string &message, const Args&... args) Constructor with arguments.
Constructs the exception with error type and error message. The constructor also takes additional arguments to format the message.
- Parameters
error – Error code.
file – File name.
line – Line of code.
message – Error message.
args – Arguments to format the message.
-
template<typename ...Args>
Parallel
-
using ParallelProcessFunc = std::function<void(long long index, int threadid)>
Callback function for parallel process.
- Parameters
index – Index of iteration.
threadId – Thread identifier in
0 ... num_threads()-1
.
-
using ProgressUpdateFunc = std::function<void(long long processed)>
Callback function for progress updates.
- Parameters
processed – Processed number of samples.
-
constexpr const char *DefaultType = "openmp"
Default parallel context type.
-
void init(const std::string &type = DefaultType, const Json &prop = {})
Initialize parallel context.
This function initializes the logger subsystem specified by logger type
type
. The function is implicitly called by the framework so the user do not want to explicitly call this function.- Parameters
type – Type of parallel subsystem.
prop – Properties for configuration.
-
void shutdown()
Shutdown parallel context.
This function shutdowns the parallell subsystem. You do not want to call this function because it is called implicitly by the framework.
Shutdown parallel context.
Shutdown logger context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework. You may consider to use
ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.
-
int num_threads()
Get number of threads configured for the subsystem.
- Returns
Number of threads.
-
bool main_thread()
Check if current thread is the main thread.
- Returns
true
if the current thread is the main thread,false
otherwise.
-
void foreach(long long num_samples, const ParallelProcessFunc &process_func, const ProgressUpdateFunc &progress_func)
Parallel for loop.
We provide an abstraction for the parallel loop specifialized for rendering purpose.
- Parameters
num_samples – Total number of samples.
process_func – Callback function called for each iteration.
progress_func – Callback function called for each progress update.
-
void foreach(long long num_samples, const ParallelProcessFunc &process_func)
Parallel for loop.
- Parameters
num_samples – Total number of samples.
process_func – Callback function called for each iteration.
Progress
-
enum ProgressMode
Progress reporting mode.
Values:
-
enumerator Samples
Update sample count.
-
enumerator Time
Update time.
-
enumerator Samples
-
constexpr const char *DefaultType = "default"
Default progress reporter type.
-
void init(const std::string &type = DefaultType, const Json &prop = {})
Initialize progress reporter context.
This function initializes exception subsystem of the framework. The function is implicitly called by the framework so the user do not want to explicitly call this function.
- Parameters
type – Type of progress reporter subsystem.
prop – Properties for configuration.
-
void shutdown()
Shutdown progress reporter context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework.
Shutdown progress reporter context.
Shutdown parallel context.
Shutdown logger context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework. You may consider to use
ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.
-
void start(ProgressMode mode, long long total, double total_time)
Start progress reporting.
This function specifies the start of the progress reporting. The argument
total
is necessary to calculate the ratio of progress over the entire workload. You may useScopedReport
class to automatically enable/disable the floating point exception inside a scope.- Parameters
mode – Progress reporting mode.
total – Total number of iterations (used in Samples mode).
total_time – Total time (used in Time mode).
-
void end()
End progress reporting.
This function specifies the end of the progress reporting. You may use
ScopedReport
class to automatically enable/disable the floating point exception inside a scope.
-
void update(long long processed)
Update progress.
This function notifies the update of the progress to the subsystem.
processed
must be between 0 tototal
specified in thelm::progress::start()
function.- Parameters
processed – Processed iterations.
-
void update_time(Float elapsed)
Update time progress.
- Parameters
elapsed – Elapsed time from the start.
-
class ScopedReport
- #include <progress.h>
Scoped guard of
start
andend
functions.
-
class ScopedTimeReport
- #include <progress.h>
Scoped guard of
startTime
andend
functions.
Debug
-
using OnPollFunc = std::function<void(const Json &val)>
Function being called on polling JSON value.
- Parameters
val – Value.
-
void reg_on_poll(const OnPollFunc &func)
Register polling function for floating-point values.
- Parameters
func – Callback function.
-
void attach_to_debugger()
Attach to debugger.
Attach the process to Visual Studio Debugger. This function is only available in Windows environment.
-
void print_asset_tree(bool visualize_weak_refs)
Prints assets managed by the framework.
This function visualizes a tree of assets managed by the framework. If
visualize_weak_refs
flag enabled, weak references are also visualized.- Parameters
visualize_weak_refs – Visualize weak references if enabled.
Json
-
using Json = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, Float, std::allocator, nlohmann::adl_serializer>
JSON type.
We use nlohmann_json library to represent various properties. This type is mainly used to communicate data between user and framework through API.
-
inline lm::Json operator""_lmJson(const char *s, size_t n)
String literal for JSON types.
-
Json merge(const Json &j1, const Json &j2)
Merge two parameters.
If the same key is used, the value in j1 has priority.
- Parameters
j1 – Parameters.
j2 – Parameters.
-
template<size_t N>
Json parse_positional_args(int argc, char **argv, const std::string &temp) Parse positional command line arguments.
Convenience function to parse positional command line arguments. The format can be specified by Json object with formats. A sequence of
{}
inside the stringtemp
are replaced with positional command line arguments and parsed as a Json object.- See
example/raycast.cpp
- Parameters
argc – Number of arguments.
argv – Vector of arguments.
temp – Json object with templates.
-
template<typename T>
T value(const Json &j, const std::string &name) Get value inside JSON element.
This function will cause an exception if JSON object does not contain the element.
- Parameters
j – Json object.
name – Name of the element.
-
template<typename T>
T value(const Json &j, const std::string &name, T &&def) Get value inside JSON element with default.
- Parameters
j – Json object.
name – Name of the element.
def – Default value.
-
template<typename T>
T *comp_ref(const Json &j, const std::string &name) Get value inside JSON element as component.
This function returns a component pointer referenced by a component locator specified by a JSON element. If failed, this function throws an exception.
- Parameters
j – Json object.
name – Name of the element.
-
template<typename T>
T *comp_ref_or_nullptr(const Json &j, const std::string &name) Get value inside JSON element as component (if failed, nullptr).
This function returns a component pointer referenced by a component locator specified by a JSON element. Unlike
lm::json::comp_ref()
, this function returnsnullptr
if failed.- Parameters
j – Json object.
name – Name of the element.
-
template<typename T>
std::optional<T> value_or_none(const Json &j, const std::string &name) Get value inside JSON element with std::optional.
This variant of value function returns std::nullopt if the json object doesn’t contain the element with given name.
- Parameters
j – Json object.
name – Name of the element.
Math
-
using Vec2 = glm::tvec2<Float>
2d vector
-
using Vec3 = glm::tvec3<Float>
3d vector
-
using Vec4 = glm::tvec4<Float>
4d vector
-
using Mat3 = glm::tmat3x3<Float>
3x3 matrix
-
using Mat4 = glm::tmat4x4<Float>
4x4 matrix
-
using Rng = detail::RngImpl<Float>
Random number generator.
The class provides the feature of uniform random number generator. Various random variables are defined based on the uniform random number generated by this class. Note that the class internally holds the state therefore the member function calls are not thread-safe.
Public Members
-
Rng(int seed)
Construct the random number generator by a given seed value.
-
Float u()
Generate an uniform random number in [0,1).
-
Rng(int seed)
-
constexpr Float Inf = 1e+10_f
Big number.
-
constexpr Float Eps = 1e-3_f
Error tolerance.
-
constexpr Float Pi = 3.14159265358979323846_f
Value of Pi.
-
static unsigned int rng_seed()
Generate random number for seed.
- Returns
Random seed.
-
template<typename VecT>
static bool is_zero(VecT v) Check if components of a vector are all zeros.
- Parameters
v – A vector.
- Returns
true
if components are all zeros,false
otherwise.
-
static Float safe_sqrt(Float v)
Square root handling possible negative input due to the rounding error.
- Parameters
v – Value.
- Returns
Square root of the input value.
-
static Float sq(Float v)
Compute square.
- Parameters
v – Value.
- Returns
Square of the input value.
-
static Vec3 reflection(Vec3 w, Vec3 n)
Reflected direction.
- Parameters
w – Incident direction.
n – Surface normal.
- Returns
Reflected direction.
-
static RefractionResult refraction(Vec3 wi, Vec3 n, Float eta)
Refracted direction.
- Parameters
wi – Incident direction.
n – Surface normal.
eta – Relative ior.
- Returns
Refracted direction.
-
static std::tuple<Vec3, Vec3> orthonormal_basis(Vec3 n)
Compute orthogonal basis.
This implementation is based on the technique by Duff et al. [Duff2017].
- Duff2017
Duff et al., Building an Orthonormal Basis, Revisited., JCGT, 2017.
- Parameters
n – Normal vector.
-
static Vec3 geometry_normal(Vec3 p1, Vec3 p2, Vec3 p3)
Compute geometry normal.
Note that the three points must be given in counter-clockwised order.
- Parameters
p1 – First point.
p2 – Second point.
p3 – Third point.
- Returns
Geometry normal.
-
template<typename VecT>
static VecT mix_barycentric(VecT a, VecT b, VecT c, Vec2 uv) Interpolation with barycentric coordinates.
- Parameters
a – A value associated with the first point on the triangle.
b – A value associated with the second point on the triangle.
c – A value associated with the third point on the triangle.
uv – Ratio of interpolation in [0,1]^2.
- Returns
Interpolated value.
-
static Vec3 spherical_to_cartesian(Float theta, Float phi)
Convert spherical to cartesian coordinates.
-
static Vec2 sample_uniform_disk(Vec2 u)
Uniform sampling on unit disk.
- Parameters
u – Random variable in [0,1]^2.
- Returns
Sampled value.
-
static constexpr Float pdf_uniform_disk()
PDF of uniform distribution on unit disk.
- Returns
Evaluated PDF.
-
static Vec3 sample_cosine_weighted(Vec2 u)
Cosine-weighted direction sampling.
- Parameters
u – Random variable in [0,1]^2.
- Returns
Sampled value.
-
static constexpr Float pdf_cosine_weighted_projSA()
Evauate PDF of cosine-weighted distribution on a sphere in projected solid angle measure.
- Returns
Evaluated PDF.
-
static Vec3 sample_uniform_sphere(Vec2 u)
Uniformly sample a direction from a sphere.
- Parameters
u – Random variable in [0,1]^2.
- Returns
Sampled value.
-
static constexpr Float pdf_uniform_sphere()
PDF of uniform direction on a sphere in solid angle measure.
- Returns
Evaluated density.
-
static Float balance_heuristic(Float p1, Float p2)
Compute balance heuristics.
- Parameters
p1 – Evalauted PDF for the first strategy.
p2 – Evaluated PDF for the second strategy.
- Returns
Evaluated weight.
-
struct lm::Bound
- #include <math.h>
Axis-aligned bounding box.
Public Functions
-
inline Vec3 operator[](int i) const
Index operator.
- Returns
0: minimum coordinates, 1: maximum coordinates.
-
inline Float surface_area() const
Surface area of the bound.
- Returns
Surface area.
-
inline bool isect(Ray r, Float tmin, Float tmax) const
Check intersection to the ray.
Floating point exceptions must be disabled because for performance the function facilitates operations on Inf or NaN (ref).
- Parameters
r – Ray.
tmin – Minimum valid range along with the ray from origin.
tmax – Maximum valid range along with the ray from origin.
-
inline bool isect_range(Ray r, Float &tmin, Float &tmax) const
Check intersection to the ray and update tmin and tmax.
This function checks intersection between ray and bound and assign the intersected range to tmin and tmax if the ray intersects the bound.
- Parameters
r – Ray.
tmin – Minimum valid range along with the ray from origin.
tmax – Maximum valid range along with the ray from origin.
Public Members
-
inline Vec3 operator[](int i) const
-
struct lm::SphereBound
- #include <math.h>
Sphere bound.
-
struct lm::Dist
- #include <math.h>
1d discrete distribution.
Public Functions
-
inline void clear()
Clear internal state.
-
inline bool empty() const
Check if the distribution is empty.
-
inline void add(Float v)
Add a value to the distribution.
- Parameters
v – Value to be added.
-
inline void norm()
Normalize the distribution.
-
inline Float pmf(int i) const
Evaluate pmf.
- Parameters
i – Index.
- Returns
Evaluated pmf.
-
inline int sample(Float u) const
Sample from the distribution.
- Parameters
u – Random number in [0,1].
- Returns
Sampled index.
-
inline void clear()
-
struct lm::Dist2
- #include <math.h>
2d discrete distribution.
Public Functions
-
inline void init(const std::vector<Float> &v, int cols, int rows)
Add values to the distribution.
- Parameters
v – Values to be added.
cols – Number of columns.
rows – Number of rows.
-
inline Float pdf(Float u, Float v) const
Evaluate pmf.
- Parameters
u – Index in column.
v – Index in row.
- Returns
Evaluated pmf.
-
inline void init(const std::vector<Float> &v, int cols, int rows)
-
struct RefractionResult
- #include <math.h>
Result of refraction() function.
OBJ loader
-
using OBJMeshFace = std::vector<OBJMeshFaceIndex>
Face.
-
using ProcessMeshFunc = std::function<bool(const OBJMeshFace &fs, const MTLMatParams &m)>
Callback function to process a mesh.
-
using ProcessMaterialFunc = std::function<bool(const MTLMatParams &m)>
Callback function to process a material.
-
constexpr const char *DefaultType = "simple"
Default parallel context type.
-
void init(const std::string &type = DefaultType, const Json &prop = {})
Initialize objloader context.
-
void shutdown()
Shutdown parallel context.
Shutdown parallel context.
Shutdown logger context.
This function shutdowns the exception subsystem. You do not want to call this function because it is called implicitly by the framework. You may consider to use
ScopedInit
class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.
-
bool load(const std::string &path, OBJSurfaceGeometry &geo, const ProcessMeshFunc &processMesh, const ProcessMaterialFunc &processMaterial)
Load an OBJ file.
-
struct lm::objloader::OBJSurfaceGeometry
- #include <objloader.h>
Surface geometry shared among meshes.
-
struct lm::objloader::OBJMeshFaceIndex
- #include <objloader.h>
Face indices.
-
struct lm::objloader::MTLMatParams
- #include <objloader.h>
MLT material parameters.
Component
-
Component *create_comp(const std::string &key)
Create component instance.
This function creates a component instance from the key. The component implementation with the key must be registered beforehand with
LM_COMP_REG_IMPL()
macro and loaded withload_plugin()
function if the component is defined inside a plugin. Otherwise the function returns nullptr with error message.- Parameters
key – Implementation key.
-
void reg(const std::string &key, const std::string &alias, const Component::CreateFunction &create_func, const Component::ReleaseFunction &release_func)
Register a component.
This function registers a component implementation into the framework. The function is internally and indirectly called by
LM_COMP_REG_IMPL()
macro. The users do not want to use it directly.- Parameters
key – Implementation key.
alias – Alias name.
create_func – Create function.
release_func – Release function.
-
void unreg(const std::string &key, const std::string &alias)
Unregister a component.
This function unregisters a component implementation specified by the key. The users do not want to use it directly.
- Parameters
key – Implementation key.
alias – Alias name.
-
void load_plugin(const std::string &path)
Load a plugin.
This function loads a plugin from a specified path. The components inside the plugin are automatically registered to the framework and ready to use with
lm::comp::create()
function. If the loading fails, the function throws an exception.- Parameters
path – Path to a plugin.
-
void load_plugin_directory(const std::string &directory)
Load plugins inside a given directory.
This functions loads all plugins inside the specified directory. If the loading fails, it generates an error message but ignored.
- Parameters
directory – Path to a directory containing plugins.
-
void unload_all_plugins()
Unload loaded plugins.
This functions unloads all the plugins loaded so far.
-
void foreach_registered(const std::function<void(const std::string &name)> &func)
Iterate registered component names.
This function enumerates registered component names. The specified callback function is called for each registered component.
- Parameters
func – Function called for each registered component.
-
void register_root_comp(Component *p)
Register root component.
This function registers the given component as a root component. The registered component is used as a starting point of the component hierarchy. The given component must have a locator
$
. The function is called internaly so the user do not want to use it directly.- Parameters
p – Component to be registered as a root.
-
template<typename T>
T *get(const std::string &locator) Get component by locator.
This function queries an underlying component instance inside the component hierarchy by a component locator. For detail of component locator, see Component hierarchy and locator. If a component instance is not found, or the locator is ill-formed, the function returns nullptr with error messages.
-
template<typename T>
std::enable_if_t<std::is_base_of_v<lm::Component, T>, void> update_weak_ref(T *&p) Update weak reference.
Helper function to update weak reference of component instance.
- Parameters
p – Reference to the component pointer.
-
template<typename T>
std::enable_if_t<std::is_base_of_v<lm::Component, T>, void> visit(const Component::ComponentVisitor &visitor, T *&p) Visit underlying asset overloaded for weak references.
- Parameters
visitor – Visitor function.
p – Reference to component pointer.
-
template<typename T>
std::enable_if_t<std::is_base_of_v<lm::Component, T>, void> visit(const Component::ComponentVisitor &visitor, Component::Ptr<T> &p) Visit underlying asset overloaded for unique pointers.
- Parameters
visitor – Visitor function.
p – Reference to component pointer.
-
template<typename InterfaceT>
Component::Ptr<InterfaceT> create_without_construct(const std::string &key, const std::string &loc) Create component with specific interface type without calling construct function.
-
template<typename InterfaceT>
Component::Ptr<InterfaceT> create(const std::string &key, const std::string &loc, const Json &prop = {}) Create component with given properties.
-
LM_COMP_REG_IMPL_ALIAS(ImplT, key, alias)
Register implementation with alias.
This macro registers an implementation of a component object into the framework with its alias. Note that lm::Component::key() refers to the original name of the implementation, not the name of the alias.
- Parameters
ImplT – Component implemenation type.
key – Name of implementation being referenced by the alias.
alias – Name of alias.
-
LM_COMP_REG_IMPL(ImplT, key)
Register implementation.
This macro registers an implementation of a component object into the framework. This macro can be placed under any translation unit irrespective to the kind of binaries it belongs, like a shared libraries or an user’s application code. See Implementing interface for detail.
Note
According to the C++ specification [basic.start.dynamic]/5, dependening on the implementation, the dynamic initalization of an object inside a namespace scope can be defered until it is used in the context that its definition must be presented (odr-used). This macro workarounded this issue by expliciting instantiating an singleton
RegEntry<>
defined for each implementation type.- Parameters
ImplT – Component implemenation type.
key – Name of the implementation.
-
class lm::Component
- #include <component.h>
Base component.
Base class of all components in Lightmetrica. All components interfaces and implementations must inherit this class. For detail, see Component.
Subclassed by lm::Accel, lm::AssetGroup, lm::Camera, lm::Film, lm::Light, lm::log::LoggerContext, lm::Material, lm::Medium, lm::Mesh, lm::Model, lm::objloader::OBJLoaderContext, lm::parallel::ParallelContext, lm::Phase, lm::progress::ProgressContext, lm::Renderer, lm::Scene, lm::scheduler::Scheduler, lm::Texture, lm::timer::ScopedTimer, lm::Volume, PyBinder
Public Types
-
using CreateFunction = std::function<Component*()>
Factory function type.
A type of the function to create an component instance. The function of this type is registered automatically to the framework with
LM_COMP_REG_IMPL()
macro.- Returns
Component instance.
-
using ReleaseFunction = std::function<void(Component *p)>
Release function type.
A type of the function to release an component instance. The function of this type is registered automatically to the framework with
LM_COMP_REG_IMPL()
macro.- Parameters
p – Component instance to be deleted.
-
using Ptr = std::unique_ptr<InterfaceT, ComponentDeleter>
Unique pointer for component instances.
unique_ptr for component types. All component instances must be managed by unique_ptr, because we constrained an instance inside our component hierarchy must be managed by a single component.
- Template Parameters
InterfaceT – Component interface type.
-
using ComponentVisitor = std::function<void(Component *&p, bool weak)>
Visitor function type.
The function of this type is used to be a callback function of
lm::Component::foreach_underlying()
function.- Parameters
p – Visiting component instance.
weak – True if the visiting instance is referred as a weak reference.
Public Functions
-
inline const std::string &key() const
Get name of component instance.
This function returns an unique identifier of the component implementation of the instance.
-
inline const std::string &loc() const
Get locator of the component.
If the instance is integrated into the component hierarchy, this function returns the unique component locator of the instance. If the instance is not in the component hierarchy, the function returns an empty string.
-
inline const std::string parent_loc() const
Get parent locator.
This function returns parent locator of the component. If this or parent component is root, the function returns empty string. For instance, if the current locator is
aaa.bbb.ccc
, this function returnsaaa.bbb
. If the current locator isaaa
, this function returns empty string.
-
inline const std::string name() const
Get name of the component instance.
This fuction returns name of the component instance used as an identifier in parent component.
-
inline const std::string make_loc(const std::string &base, const std::string &child) const
Make locator by appending string.
This function appends the specified
child
locator into the back ofbase
locator.- Parameters
base – Base locator.
child – Child locator.
-
inline const std::string make_loc(const std::string &child) const
Make locator by appending string to current locator.
This function appends the specified locator into the back of the locator of the current instance.
- Parameters
child – Child locator.
-
inline virtual void construct(const Json &prop)
Construct a component.
The function is called just after the component instance is created. Mostly, the function is called internally by
lm::comp::create()
function. The configuration properties are passed by JSON type.- Parameters
prop – Configuration property.
-
inline virtual void load(InputArchive &ar)
Deserialize a component.
The function deserialize the component using the archive
ar
. The function is called internally. The users do not want to use this directly.- Parameters
ar – Input archive.
-
inline virtual void save(OutputArchive &ar)
Serialize a component.
The function serialize the component using the archive
ar
. The function is called internally. The users do not want to use this directly.- Parameters
ar – Output archive.
-
inline virtual Component *underlying(const std::string &name) const
Get underlying component instance.
This function queries a component instance by the identifier
name
. If the component instance is found, the function returns a pointer to the instance. If not component instance is found, the function returns nullptr.The name of the component instance found by this function must match
name
, that is,comp->name() == name
.- Parameters
name – Name of the component instance being queried.
-
inline virtual void foreach_underlying(const ComponentVisitor &visitor)
Process given function for each underlying component call.
This function enumerates underlying component of the instance. Every time a component instance (unique or weak) is found, the callback function specified by an argument is called. The callback function takes a flag to show the instance is weak reference or unique. Use
lm::comp::visit()
function to automatically determine either of them.- Parameters
visitor – Component visitor.
-
inline virtual Json underlying_value(const std::string &query = "") const
Get underlying value.
This function gets underlying values of the component. The specification of the query string is implementation-dependent. The return type must be serialized to Json type.
- Parameters
query – Query string.
-
inline virtual void *underlying_raw_pointer(const std::string &query = "") const
Get underlying raw pointer.
This function gets underlying content as a void pointer. We want to use this function for debugging purposes.
- Parameters
query – Query string.
-
using CreateFunction = std::function<Component*()>
-
struct ComponentDeleter
- #include <component.h>
Deleter for component instances.
This must be default constructable because pybind11 library requires to construct unique_ptr from a single pointer.
-
template<typename ContextComponentT>
class lm::comp::detail::ContextInstance - #include <component.h>
Singleton for a context component.
This singleton holds the ownership the context component where we manages the component hierarchy under the context. Example:
using Instance = lm::comp::detail::ContextInstance<YourComponentInterface>; Instance::init("interface::yourcomponent", { ... }); Instance::get()->...
- tparam ContextComponentT
Component type.
Public Static Functions
-
static inline ContextComponentT &get()
Get a reference to the underlying component.
- Returns
Reference to the underlying component.
-
static inline void init(const std::string &type, const Json &prop)
Initialize the underlying component.
This function initializes the underlying component with the specified component type and properties.
- Parameters
type – Component type.
prop – Configuration property.
-
static inline void shutdown()
Delete the underlying component.
-
static inline bool initialized()
Check if the context instance is initialized.
This function returns true if the underlying component is initialized.
-
class ScopedLoadPlugin
- #include <component.h>
Scope guard of
loadPlugins
andloadPlugins
.
-
template<typename ImplType>
class RegEntry - #include <component.h>
Registration entry for component implementation.
This class is used internally by
LM_COMP_REG_IMPL()
macro. The users do not want to use it directly.- tparam ImplType
Type of component implementation.
Acceleration structure
-
class lm::Accel : public lm::Component
- #include <accel.h>
Ray-triangles acceleration structure.
Interfaces acceleration structure for ray-triangles intersection. We provided several tests to check validity or performance of the implementations. See
functest
directory for detail.Public Functions
-
virtual void build(const Scene &scene) = 0
Build acceleration structure.
Builds the acceleration structure from the primitives inside the given scene. When a primitive inside the scene is updated by addition or modification, you need to call the function again to update the structure.
- Parameters
scene – Input scene.
-
virtual std::optional<Hit> intersect(Ray ray, Float tmin, Float tmax) const = 0
Compute closest intersection point.
Finds the closest intersecion point in the direction specified by
ray
. The validity of the ray segment is speicified by the range[tmin, tmax]
measured from the origin of the ray. If no intersection is found, the function returns nullopt.- Parameters
ray – Ray.
tmin – Lower valid range of the ray.
tmax – Higher valid range of the ray.
-
virtual void build(const Scene &scene) = 0
Scene
-
enum TransDir
Light transport direction.
Values:
-
enumerator LE
Transport direction is L (light) to E (sensor).
-
enumerator EL
Transport direction is E (sensor) to L (light).
-
enumerator LE
-
static Float geometry_term(const PointGeometry &s1, const PointGeometry &s2)
Compute geometry term.
This function computes the extended geometry term \(G(\mathbf{x}, \mathbf{y})\). This function can accepts extended points represented by
lm::PointGeometry
.- Parameters
s1 – First point.
s2 – Second point.
-
static Float distance(const PointGeometry &s1, const PointGeometry &s2)
Copmute distance between two points.
This function computes the distance between two points. This function can accepts extended points represented by
lm::PointGeometry
. If one of the points is a point at infinity, returnsInf
.- Parameters
s1 – First point.
s2 – Second point.
-
static Float convert_pdf_SA_to_projSA(Float pdf_SA, const PointGeometry &geom, Vec3 d)
Convert PDF in solid angle measure to projected solid angle measure.
If the point geometry is not degenerated, this function converts the given PDF to the projected solid angle measure. If the point geometry is degenerated, this function keeps the solid angle measure.
- Parameters
pdf_SA – Input evaluated PDF.
geom – Point geometry.
d – Outgoing direction from the surface point.
-
static Float convert_pdf_to_area(Float pdf_in, const PointGeometry &geom1, const PointGeometry &geom2)
Convert PDF in aggregated measure.
This function support conversion of the PDF having either of two measures: (1) convertion from aggregated solid angle to area measure, (2) conversion from aggregated throughput to aggregated area measure. For detail including definitions, please refer to Aggregated solid angle to area and Conversion of aggregated throughput.
- Parameters
pdf_in – Input evaluated PDF.
geom1 – First point geometry.
geom2 – Second point geometry.
-
static Float shading_normal_correction(const PointGeometry &geom, Vec3 wi, Vec3 wo, TransDir trans_dir)
Energy compensation factor for shading normal.
The energy correction term for shading normal [Veach 1998, Sec. 5.3.4]. Note that this implementation doesn’t prevent “black patch” issue when the incoming direction lies in the region \((\omega_i\cdot N_g)(\omega_i\cdot N_s) < 0\) [Veach 1998, Fig. 5.7(b)].
- Parameters
geom – Point geometry.
wi – Incident direction.
wo – Outgoing direction.
trans_dir – Transform direction.
-
class lm::Scene : public lm::Component
- #include <scene.h>
This class represent a component interface for a scene. A scene is responsible for sampling of a ray emitted from a point inside a scene, evaluation of directional terms given a point in the scene, ray-scene intersection, visibility query, etc. The class is a basic building block to construct your own renderer.
A scene is also responsible for managing the collection of assets (e.g., meshes, materials, etc.). Underlying assets are accessed via standard query functions like
lm::Component::underlying()
. The class provides the feature for internal usage and the user may not want to use this interface directly. The feature of the class is exposed byuser
namespace.Public Types
Public Functions
-
virtual void reset() = 0
Reset the scene.
-
virtual int root_node() = 0
Get index of the root node.
- Returns
Node index.
-
virtual int create_primitive_node(const Json &prop) = 0
Create primitive node.
This function create a primitive scene node and add it to the scene. The references to the assets are specified in
prop
. The accepted assets types aremesh
,material
,light
,camera
, andmedium
. This function returns node index if succedded.- Parameters
prop – Property containing references to the scene components.
- Returns
Index of the created node.
-
virtual int create_group_node(Mat4 transform) = 0
Create group node.
This function creates a group scen node and add it to the scene. ‘’transform’’ specifies the transformation of the node to be applied to the child nodes. This function returns node index if succedded.
- Parameters
transform – Local transoform of the node.
-
virtual int create_instance_group_node() = 0
Create instance group node.
This function creates a special group node for instance group. The child nodes of this node are considered as an instance group. This function returns node index if succedded.
-
virtual void add_child(int parent, int child) = 0
Add primitive group.
This function adds a primitive group to the scene and returns index of the group. If the group with the same name is already created, this function returns the index of the registered group.
- Parameters
parent – Parent node index.
child – Child node index being added.
-
virtual void add_child_from_model(int parent, const std::string &model_loc) = 0
Add child node from model asset.
- Parameters
parent – Index of the parent node.
model_loc – Locator of the model asset.
-
virtual int create_group_from_model(const std::string &model_loc) = 0
Create group node from model asset.
- Parameters
model_loc – Locator of the model asset.
- Returns
Index of the created node.
-
inline void add_primitive(const Json &prop)
Create primitive(s) and add to the scene.
This function creates primitive(s) and registers to the framework. A primitive is a scene object associating the assets such as meshes or materials. The coordinates of the object is speficied by a 4x4 transformation matrix. We can use the same assets to define different primitives with different transformations.
If
model
parameter is specified, the function will register primitives generated from the model. In this case, the transformation is applied to all primitives to be generated.- See
example/quad.cpp
- See
example/raycast.cpp
- Parameters
prop – Properties for configuration.
-
inline void add_transformed_primitive(Mat4 transform, const Json &prop)
Create primitive(s) and add to the scene with transform.
- Parameters
transform – Transformation matrix.
prop – Properties for configuration.
-
virtual void traverse_primitive_nodes(const NodeTraverseFunc &traverse_func) const = 0
Iterate primitive nodes in the scene.
This function traverses the primitive nodes in the scene graph. For each primitive node, global transformation is computed and passed as an argument of the callback function. Note that this function does not traverse intermediate group nodes. If you want to traverse also the group node, consider to use
Scene::visit_node()
.- Parameters
traverse_func – Function being called for each traversed primitive node.
-
virtual void visit_node(int node_index, const VisitNodeFunc &visit) const = 0
Traverse a node in the scene.
This function traverse a node in the scene graph. Unlike
Scene::traverse_primitive_nodes()
, this function can be used to traverse all kinds of scene nodes in the scene graph. Be careful the user is responsible to call this function to traverse the node recursively.- Parameters
node_index – Note index where the traverse starts.
visit – Callback function being called for each traversed node.
-
virtual int num_nodes() const = 0
Get number of nodes.
Note that the scene contains at least one node (root node).
-
virtual int num_lights() const = 0
Get number of lights in the scene.
-
virtual int camera_node() const = 0
Get camera node index.
- Returns
Camera node index. -1 if no camera is found in the scene.
-
virtual int medium_node() const = 0
Get medium node index.
- Returns
Medium node index. -1 if no medium is found in the scene.
-
virtual int env_light_node() const = 0
Get environment map node index.
- Returns
Environment light node index. -1 if no environment light is found in the scene.
-
inline void require_primitive() const
Throws an exception if there is no primitive in the scene.
-
inline void require_camera() const
Throws an exception if there is no camera in the scene.
-
inline void require_light() const
Throws an exception if there is no light in the scene.
-
inline void require_accel() const
Throws an exception if there is no accel created for the scene.
-
inline void require_renderable() const
Throws an exception if there the scene is not renderable.
This function is equivalent to calling the following functions:
-
virtual void set_accel(const std::string &accel_loc) = 0
Set underlying acceleration structure.
- Parameters
accel_loc – Locator to the accel asset.
-
virtual void build() = 0
Build acceleration structure.
-
virtual std::optional<SceneInteraction> intersect(Ray ray, Float tmin = Eps, Float tmax = Inf) const = 0
Compute closest intersection point.
This function computes closest intersection point between the given ray and the scene utilizing underlying acceleration structure of the scene. If no intersection happens, this function returns
nullopt
. Note that if the scene contains environment light, this function returns scene intersection structure indicating the intersection with infinite point. This can be examined by checkingPointGeometry::infinite
beingtrue
.- Parameters
ray – Ray.
tmin – Lower bound of the valid range of the ray.
tmax – Upper bound of the valid range of the ray.
-
inline bool visible(const SceneInteraction &sp1, const SceneInteraction &sp2) const
Check if two surface points are mutually visible.
-
virtual bool is_light(const SceneInteraction &sp) const = 0
Check if the surface point is a light.
-
virtual bool is_camera(const SceneInteraction &sp) const = 0
Check if the surface point is a camera.
-
virtual LightSelectionSample sample_light_selection(Float u) const = 0
Light sampling.
- Parameters
u – Random number input in [0,1]. return Sample light index.
-
virtual Float pdf_light_selection(int light_index) const = 0
Evaluate the PDF for light sampling.
- Parameters
light_index – Sampled light index.
- Returns
Evaluated PDF.
-
virtual LightPrimitiveIndex light_primitive_index_at(int light_index) const = 0
Get primitive node index from light index.
-
virtual int light_index_at(int node_index) const = 0
Get light index from node index.
-
struct LightPrimitiveIndex
- #include <scene.h>
Primitive index of the light and its transform.
-
struct LightSelectionSample
- #include <scene.h>
Result of light sampling.
-
virtual void reset() = 0
-
struct lm::SceneNode
- #include <scenenode.h>
Scene node.
This structure represents a scene node. The scene is described by a set of nodes. The scene node is categorized by two types (a) primitive and (b) group.
(a) A primitive describes a concrete object in the scene which associates various scene components like mesh or material. A primitive can represent four types of scene objects.
Scene geometry. If
mesh != nullptr
andmaterial != nullptr
, the structure describes a geometry in the scene, represented by an association of a mesh and a material. A transformation is applied to the mesh.Light. If
light != nullptr
, the structure describes a light in the scene. Note that a light can also be a scene geometry, such as area lights.Camera. If
camera != nullptr
, the structure describes a camera in the scene. Note that a camera and a light cannot be the same primitive, that is,light
andcamera
cannot be non-nullptr
in the same time.Medium. If
medium != nullptr
, the structure describes a medium in the scene.
A set of primitives is managed internally by the functions in
lm::path
namespace. Thus the users usually do not need to explicitly access the underlying interfaces of a primitive.(b) A group is a collection of the multiple nodes which can represent an agrgegated scene object. A group node can have a transformation being locally applied to the primitives in the child nodes. A typical usage of the group node is to specify the instance group. An instance group is a collection of scene object that the acceleration structure is shared between different part of the scene (up to transformation).
Public Static Functions
-
static inline SceneNode make_primitive(int index, Mesh *mesh, Material *material, Light *light, Camera *camera, Medium *medium)
Make primitive node.
- Parameters
index – Primitive index.
mesh – Reference to mesh.
material – Reference to material.
light – Reference to light.
camera – Reference to camera.
medium – Reference to medium.
-
struct lm::PointGeometry
- #include <surface.h>
Point geometry information.
This structure represents a point inside the scene, which includes a surface point, point in the air, or point at infinity, etc. This structure is a basic quantity to be used in various renderer-related functions, like sampling or evaluation of terms. The structure represents three types of points.
A point on a scene surface. The structure describes a point on the scene surface if
degenerated=false
. You can access the following associated information.Position
p
Shading normal
n
Texture coordinates
t
Tangent vectors
u
andv
Degenerated point. The structure describes a degenerated point if
degenerated=true
. The surface around the degenearted point is collapsed to a point or a line. For instance it is used to represent a position of point light or pinhole camera. The associated information is the positionp
.Infinitely distant point. The structure describes a point at infinity if
infinite=true
, used to represent a point generated by directional light or environment light. This point does not represent an actual point associated with certain position in the 3d space, but it is instead used to simplify the renderer interfaces. The associated information is the direction from the point at infinitywo
.
You can find additional information in Point geometry.
Public Functions
-
inline bool opposite(Vec3 w1, Vec3 w2) const
Checks if two directions lies in the same half-space.
This function checks if two directions
w1
andw2
lies in the same half-space divided by the tangent plane.w1
andw2
are interchangeable.- Parameters
w1 – First direction.
w2 – Second direction.
-
inline std::tuple<Vec3, Vec3, Vec3> orthonormal_basis_twosided(Vec3 wi) const
Compute orthonormal basis according to the incident direction.
The function returns an orthornormal basis according to the incident direction
wi
. Ifwi
is coming below the surface, the orthonormal basis are created based on the negated normal vector. This function is useful to support two-sided materials.- Parameters
wi – Incident direction.
Public Members
-
bool degenerated
True if surface is degenerated (e.g., point light).
-
bool infinite
True if the point is a point at infinity.
Public Static Functions
-
static inline PointGeometry make_degenerated(Vec3 p)
Make degenerated point.
A static function to generate a point in the air from the specified position
p
.- Parameters
p – Position.
-
static inline PointGeometry make_infinite(Vec3 wo)
Make a point at infinity.
A static function to generate a point at infinity from the specified direction from the point.
- Parameters
wo – Direction from a point at infinity.
-
static inline PointGeometry make_infinite(Vec3 wo, Vec3 p)
Make a point at infinity.
- Parameters
wo – Direction from a point at infinity.
p – Rrepresentative distant point (e.g., a point outside the scene bound).
-
static inline PointGeometry make_on_surface(Vec3 p, Vec3 n, Vec3 gn, Vec2 t)
Make a point on surface.
A static function to generate a point on the scene surface from the specified surface geometry information.
- Parameters
p – Position.
n – Shading normal.
gn – Geometry normal.
t – Texture coordinates.
-
static inline PointGeometry make_on_surface(Vec3 p, Vec3 n, Vec3 gn)
Make a point on surface.
A static function to generate a point on the scene surface from the specified surface geometry information.
- Parameters
p – Position.
n – Shading normal.
gn – Geometry normal.
-
static inline PointGeometry make_on_surface(Vec3 p, Vec3 gn)
Make a point on surface.
A static function to generate a point on the scene surface from the specified surface geometry information.
- Parameters
p – Position.
gn – Geometry normal.
-
struct lm::SceneInteraction
- #include <surface.h>
Scene interaction.
This structure represents a point of interaction between a light and the scene. The point represents a scattering point of an endpoint of a light transportation path, defined either on a surface or in a media. The point is associated with a geometry information around the point and an index of the primitive. The structure is mainly utilized by the functions in
lm::path
namespace. For detail, please refer to Scene interaction point.Public Functions
-
inline bool is_type(int type_flag) const
Check the scene interaction type.
-
inline SceneInteraction as_type(int new_type) const
Consider the scene interaction as a different type.
Public Members
-
int primitive
Primitive node index.
-
PointGeometry geom
Surface point geometry information.
Public Static Functions
-
static inline SceneInteraction make_surface_interaction(int primitive, const PointGeometry &geom)
Make surface interaction.
- Parameters
primitive – Primitive index.
geom – Point geometry.
- Returns
Created scene interaction.
-
static inline SceneInteraction make_medium_interaction(int primitive, const PointGeometry &geom)
Make medium interaction.
- Parameters
primitive – Primitive index.
geom – Point geometry.
- Returns
Created scene interaction.
-
static inline SceneInteraction make_camera_endpoint(int primitive, const PointGeometry &geom)
Make camera endpoint.
- Parameters
primitive – Primitive index.
geom – Point geometry.
- Returns
Created scene interaction.
-
static inline SceneInteraction make_light_endpoint(int primitive, const PointGeometry &geom)
Make light endpoint.
- Parameters
primitive – Primiive index.
geom – Point geometry.
-
inline bool is_type(int type_flag) const
Renderer
Camera
-
class lm::Camera : public lm::Component
- #include <camera.h>
This component interface represents a camera inside the scene, responsible for sampling and evaluation of the rays emitted from/to the camera. Please refer to Path sampling for detail.
Public Functions
-
virtual void set_aspect_ratio(Float aspect) = 0
Set aspect ratio.
This function sets the aspect ratio of the film to be rendered. Note that this function overrides the aspect ratio given by a parameter of
lm::Component::construct()
function.- Parameters
aspect – Aspect ratio (width / height).
-
virtual Mat4 projection_matrix() const = 0
Get projection matrix if available.
- Returns
Projection matrix.
-
virtual Ray primary_ray(Vec2 rp) const = 0
Generate a primary ray with the corresponding raster position.
This function deterministically generates a ray from the given raster position in \([0,1]^2\) corresponding to width and height of the screen, leaf-to-right and bottom-to-top. This function is useful in the application that the primary ray is fixed (e.g., ray casting). Use
sample_ray()
when the primary ray is generated randomly.- Parameters
rp – Raster position.
-
virtual std::optional<RaySample> sample_ray(const RaySampleU &u) const = 0
Primary ray sampling.
This function samples a primary ray generated from the sensor \((\mathbf{x}, \omega) \sim p_{\mu^* E}(\cdot,\cdot)\).
- Parameters
u – Random number input.
-
virtual Float pdf_ray(const PointGeometry &geom, Vec3 wo) const = 0
Evaluate PDF for primary ray sampling.
This function evaluate the PDF \(p_{\mu^* E}(\mathbf{x}, \omega)\).
- Parameters
geom – Sampled point geometry.
wo – Sampled outgoing direction.
-
virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU &u, const PointGeometry &geom) const = 0
Direction sampling.
This function sample a direction from the point on the sensor: \(\omega \sim p_{\sigma^* E}(\cdot\mid\mathbf{x})\).
- Parameters
u – Random number input.
geom – Point geometry of the point on the sensor.
-
virtual Float pdf_direction(const PointGeometry &geom, Vec3 wo) const = 0
Evaluate PDF for direction sampling.
This function evaluats the PDF \(p_{\sigma^* E}(\omega\mid\mathbf{x})\).
- Parameters
geom – Point geometry of the point on the sensor.
wo – Sampled outgoing direction.
-
virtual std::optional<PositionSample> sample_position(const PositionSampleU &u) const = 0
Endpoint sampling.
This function samples a point on the sensor \(\mathbf{x} \sim p_{AE}(\cdot)\).
- Parameters
u – Random number input.
-
virtual Float pdf_position(const PointGeometry &geom) const = 0
Evaluate PDF for endpoint sampling.
This function evaluates the PDF \(p_{AE}(\mathbf{x})\).
- Parameters
geom – Sampled point geometry.
-
virtual std::optional<RaySample> sample_direct(const RaySampleU &u, const PointGeometry &geom) const = 0
Direct endpoint sampling.
This function sample a direction from the sensor given a point on the surface \(\omega \sim p_{\sigma^* \mathrm{directE}}(\cdot\mid\mathbf{x})\).
- Parameters
u – Random number input.
geom – Point geometry.
-
virtual Float pdf_direct(const PointGeometry &geom, const PointGeometry &geomE, Vec3 wo) const = 0
Evaluate PDF for direct endpoint sampling.
This function evaluates the PDF \(p_{\sigma^* \mathrm{directE}}(\omega\mid\mathbf{x})\).
- Parameters
geom – Point on the surface.
geomE – Sampled point on the sensor.
wo – Sampled direction.
-
virtual std::optional<Vec2> raster_position(Vec3 wo) const = 0
Compute a raster position.
- Parameters
wo – Primary ray direction.
- Returns
Raster position.
-
virtual bool is_connectable(const PointGeometry &geom) const = 0
Check if the sensor is connectable.
This function checks if the sensor is connectable with other scene surface. For detail, please refer to path_sampling_connectable_endpoint.
-
struct DirectionSample
- #include <camera.h>
Result of direction sampling.
-
struct DirectionSampleU
- #include <camera.h>
Random number input for direction sampling.
-
struct PositionSample
- #include <camera.h>
Result of endpint sampling.
-
struct PositionSampleU
- #include <camera.h>
Random number input for endpoint sampling.
-
struct RaySample
- #include <camera.h>
Result of primary ray sampling.
-
struct RaySampleU
- #include <camera.h>
Random number input for primary ray sampling.
-
virtual void set_aspect_ratio(Float aspect) = 0
Film
-
struct lm::FilmSize
- #include <film.h>
Film size.
This structure represents a film size used as a return type of
lm::Film::size()
function.
-
struct lm::FilmBuffer
- #include <film.h>
Film buffer.
The structure represents a film buffer used as a return type of
lm::Film::buffer()
function. The data format of the buffer is implementation-dependent.
-
class lm::Film : public lm::Component
- #include <film.h>
Film.
A component interface representing a film. The component is used as an output from renderers.
Public Types
Public Functions
-
virtual long long num_pixels() const = 0
Get the number of pixels.
-
virtual void set_pixel(int x, int y, Vec3 v) = 0
Set pixel value.
This function sets the pixel color to the specified pixel coordinates
(x,y)
. This function is thread-safe and safe to be accessed from multiple threads in the process of rendering.- Parameters
x – x coordinate of the film.
y – y coordinate of the film.
v – Pixel color.
-
virtual bool save(const std::string &outpath) const = 0
Save rendered film.
This function saves the internal represention of the film to the specified path. The output image format is implementation-dependent. If it fails to save the film, the function returns false.
- Parameters
outpath – Output image path.
-
virtual FilmBuffer buffer() = 0
Get buffer of the film.
The function returns film buffer. The buffer is allocated internally and becomes invalid if the film is deleted. The data format of the buffer is implementation-dependent.
- Returns
Film buffer.
-
virtual void splat_pixel(int x, int y, Vec3 v) = 0
Splat the color to the film by pixel coordinates.
- Parameters
x – x coordinate of the film.
y – y coordinate of the film.
v – Color.
-
virtual void update_pixel(int x, int y, const PixelUpdateFunc &updateFunc) = 0
Atomically update a pixel value based on the current value.
This function is useful to implement user-defined atomic operation to update a pixel value. The given function might be called more than once.
-
virtual void rescale(Float s) = 0
Rescale the film.
- Parameters
s – Scale.
-
virtual void clear() = 0
Clear the film.
-
inline Float aspect() const
Get aspect ratio.
- Returns
Aspect ratio.
-
inline glm::ivec2 raster_to_pixel(Vec2 rp) const
Convert raster position to pixel coordinates.
This function converts the raster position to the pixel coordinates. If the raster position is outside of the range [0,1]^2, the pixel coodinates are clamped to [0,w-1]times [0,h-1].
- Parameters
rp – Raster position in [0,1]^2.
- Returns
Pixel coordinates.
-
inline void inc_ave(int x, int y, long long index, Vec3 v)
Incrementally accumulate average of a pixel value.
- Parameters
x – x coordinate of the film.
y – y coordinate of the film.
index – Current sample index.
v – Color.
-
virtual long long num_pixels() const = 0
Light
-
class lm::Light : public lm::Component
- #include <light.h>
This component interface represents a light source inside the scene. responsible for sampling and evaluation of the rays emitted from/to the light source. Please refer to Path sampling for detail.
Public Functions
-
inline virtual void set_scene_bound(const Bound &bound)
Set scene bound.
- Parameters
bound – Scene bound.
-
virtual std::optional<RaySample> sample_ray(const RaySampleU &u, const Transform &transform) const = 0
Primary ray sampling.
This function samples a primary ray generated from the light \((\mathbf{x}, \omega) \sim p_{\mu^* L}(\cdot,\cdot)\).
- Parameters
u – Random number input.
transform – Transformation of the light source.
-
virtual Float pdf_ray(const PointGeometry &geom, Vec3 wo, const Transform &transform, bool eval_delta) const = 0
Evaluate PDF for primary ray sampling.
The function evaluates the PDF \(p_{\mu^* L}(\mathbf{x}, \omega)\).
- Parameters
geom – Sampled point geometry.
wo – Sampled outgoing direction.
transform – Transformation of the light source.
eval_delta – If true, evaluate delta function.
-
virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU &u, const PointGeometry &geom) const = 0
Direction sampling.
This function sample a direction from the point on the sensor: \(\omega \sim p_{\sigma^* L}(\cdot\mid\mathbf{x})\).
- Parameters
u – Random number input.
geom – Point geometry of the point on the sensor.
-
virtual Float pdf_direction(const PointGeometry &geom, Vec3 wo) const = 0
Evaluate PDF for direction sampling.
This function evaluats the PDF \(p_{\sigma^* L}(\omega\mid\mathbf{x})\).
- Parameters
geom – Point geometry of the point on the sensor.
wo – Sampled outgoing direction.
-
virtual std::optional<PositionSample> sample_position(const PositionSampleU &u, const Transform &transform) const = 0
Endpoint sampling.
This function samples a point on the sensor \(\mathbf{x} \sim p_{AL}(\cdot)\).
- Parameters
u – Random number input.
transform – Transformation of the light source.
-
virtual Float pdf_position(const PointGeometry &geom, const Transform &transform) const = 0
Evaluate PDF for endpoint sampling.
This function evaluates the PDF \(p_{AL}(\mathbf{x})\).
- Parameters
geom – Sampled point geometry.
transform – Transformation of the light source.
-
virtual std::optional<RaySample> sample_direct(const RaySampleU &u, const PointGeometry &geom, const Transform &transform) const = 0
Direct endpoint sampling.
This function samples a direction from the surface point toward the point on the light source: \(\omega \sim p_{\sigma^* \mathrm{directL}}(\cdot\mid\mathbf{x})\). The transformation of the light source is specified by
transform
. For convenience, the function also returns the point on the light source in the direction of the ray \((\mathbf{x}',\omega)\).- Parameters
u – Random number input.
geom – Point geometry on the scene surface.
transform – Transformation of the light source.
-
virtual Float pdf_direct(const PointGeometry &geom, const PointGeometry &geomL, const Transform &transform, Vec3 wo, bool eval_delta) const = 0
Evaluate pdf for direct endpoint sampling.
This function evalutes the PDF \(p_{\sigma^* \mathrm{directL}}(\omega\mid\mathbf{x})\).
- Parameters
geom – Point geometry on the scene surface.
geomL – Point geometry on the light source.
transform – Transformation of the light source.
wo – Outgoing direction from the point of the light source.
eval_delta – If true, evaluate delta function.
-
virtual bool is_specular() const = 0
Check if the light contains delta component.
-
virtual bool is_infinite() const = 0
Check if the light source is inifite distant light.
-
inline virtual bool is_env() const
Check if the light source is environment light.
-
virtual bool is_connectable(const PointGeometry &geom) const = 0
Check if the endpoint is connectable.
-
virtual Vec3 eval(const PointGeometry &geom, Vec3 wo, bool eval_delta) const = 0
Evaluate luminance.
This function evaluates luminance function \(L_e\).
- Parameters
geom – Point geometry on the light source.
wo – Outgoing direction from the point of the light source.
eval_delta – If true, evaluate delta function.
-
struct DirectionSample
- #include <light.h>
Result of direction sampling.
-
struct DirectionSampleU
- #include <light.h>
Random number input for direction sampling.
-
struct PositionSample
- #include <light.h>
Result of endpint sampling.
-
struct PositionSampleU
- #include <light.h>
Random number input for endpoint sampling.
-
struct RaySample
- #include <light.h>
Result of primary ray sampling.
-
struct RaySampleU
- #include <light.h>
Random number input for primary ray sampling.
-
inline virtual void set_scene_bound(const Bound &bound)
Participating medium
-
class lm::Medium : public lm::Component
- #include <medium.h>
Participating medium.
Public Functions
-
virtual std::optional<DistanceSample> sample_distance(Rng &rng, Ray ray, Float tmin, Float tmax) const = 0
Sample a distance in a ray direction.
This function samples a scattering event in the valid range of the ray segmnet. Note that this function assumes there is no scene surfaces in the given range of the ray segment. If it does not sample a scattering event, this function returns
nullopt
.- Parameters
rng – Random number generator.
ray – Ray.
tmin – Lower bound of the valid range of the ray.
tmax – Upper bound of the valid range of the ray.
-
virtual Vec3 eval_transmittance(Rng &rng, Ray ray, Float tmin, Float tmax) const = 0
Evaluate transmittance.
This function estimates transmittance of the given ray segment. Note that this function assumes there is no scene surfaces in the given range of the ray segment. This function might need a random number generator because heterogeneous media needs stochastic estimation.
-
virtual bool is_emitter() const = 0
Check if the medium has emissive component.
- Returns
True if the participating media contains emitter.
-
struct DistanceSample
- #include <medium.h>
Result of distance sampling.
-
virtual std::optional<DistanceSample> sample_distance(Rng &rng, Ray ray, Float tmin, Float tmax) const = 0
Volume data
-
class lm::Volume : public lm::Component
- #include <volume.h>
Volume data.
Public Types
-
using RaymarchFunc = std::function<bool(Float t)>
Callback function called for ray marching.
- Parameters
t – Distance from the ray origin.
- Returns
true – Continue raymarching.
false – Abort raymarching.
Public Functions
-
virtual bool has_scalar() const = 0
Check if the volume has scalar component.
- Returns
True if the volume has scalar component.
-
virtual Float max_scalar() const = 0
Evaluate maximum scalar value.
-
inline virtual Float eval_scalar(Vec3 p) const
Evaluate scalar value.
- Parameters
p – Position in volume coordinates.
- Returns
Evaluated scalar value.
-
virtual bool has_color() const = 0
Check if the volume has color component.
- Returns
True if the volume has color component.
-
inline virtual Vec3 eval_color(Vec3 p) const
Evaluate color.
- Parameters
p – Position in volume coordinates.
- Returns
Evaluated color value.
-
inline virtual void march(Ray ray, Float tmin, Float tmax, Float march_step, const RaymarchFunc &raymarch_func) const
March the volume along with the ray.
This function performs volume-specific raymarching operations.
-
using RaymarchFunc = std::function<bool(Float t)>
Material
-
class lm::Material : public lm::Component
- #include <material.h>
This component insterface represents a material of the scene object, responsible for sampling of reflected/refracted rays from the material, or the evaluation of BSDF.
A material can contain multiple components. A component can be specified by an implementation-dependent component index.
For detail, please refer to Path sampling.
Public Types
Public Functions
-
virtual ComponentSample sample_component(const ComponentSampleU &u, const PointGeometry &geom, Vec3 wi) const = 0
Component sampling.
This function samples a component of the material \(j \sim p_{c,\mathrm{bsdf}}(\cdot\mid\mathbf{x})\).
- Parameters
u – Random number input.
geom – Point geometry.
wi – Incident direction.
-
virtual Float pdf_component(int comp, const PointGeometry &geom, Vec3 wi) const = 0
Evaluate PDF for component sampling.
This function evaluats \(p_{c,\mathrm{bsdf}}(j\mid\mathbf{x})\).
- Parameters
comp – Sampled component index.
geom – Point geometry.
wi – Incident direction.
-
virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU &u, const PointGeometry &geom, Vec3 wi, int comp, TransDir trans_dir) const = 0
Direction sampling.
This function samples a direction given a surface point, an incident direction, and a component index: \(\omega \sim p_{\sigma^* \mathrm{bsdf}}(\cdot\mid\mathbf{x},j)\).
- Parameters
u – Random number input.
geom – Point geometry.
wi – Incident direction.
comp – Component index.
trans_dir – Transport direction.
- Returns
Sampled direction with associated information. nullopt for invalid sample.
-
virtual Float pdf_direction(const PointGeometry &geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const = 0
Evaluate pdf in projected solid angle measure.
This function evaluates the PDF \(p_{\sigma^* \mathrm{bsdf}}(\omega\mid\mathbf{x},j)\).
eval_delta
flag enforces to evaluate delta function when the PDF contains one.- Parameters
geom – Point geometry.
wi – Incident ray direction.
wo – Sampled outgoing ray direction.
comp – Component index.
eval_delta – If true, evaluate delta function.
-
virtual Vec3 eval(const PointGeometry &geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const = 0
Evaluate BSDF.
This function evaluates underlying BSDF \(f_{\mathrm{bsdf}\Omega}(\mathbf{x},j,\omega_i,\omega_o)\) according to the transport direction
trans_dir
. Note thattrans_dir
is necessary to support non-symmetric scattering described in Veach’s thesis [Veach 1998, Chapter 5].- Parameters
geom – Point geometry.
comp – Component index.
wi – Incident ray direction.
wo – Outgoing ray direction.
trans_dir – Transport direction.
eval_delta – If true, evaluate delta function.
-
virtual bool is_specular_component(int comp) const = 0
Check if BSDF contains delta component.
This function evaluats true if the component of the BSDF specified by
comp
contains a delta function.- Parameters
comp – Component index.
-
virtual Vec3 reflectance(const PointGeometry &geom) const = 0
Evaluate reflectance.
This function evaluates the reflectance function of the underlying material if exists.
- Parameters
geom – Point geometry.
-
struct ComponentSample
- #include <material.h>
Result of component sampling.
-
struct ComponentSampleU
- #include <material.h>
Random number input for component sampling.
-
struct DirectionSample
- #include <material.h>
Result of direction sampling.
-
struct DirectionSampleU
- #include <material.h>
Random number input for direction sampling.
-
virtual ComponentSample sample_component(const ComponentSampleU &u, const PointGeometry &geom, Vec3 wi) const = 0
Phase function
-
class lm::Phase : public lm::Component
- #include <phase.h>
Phase function.
Public Functions
-
virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU &u, const PointGeometry &geom, Vec3 wi) const = 0
Sample a direction.
- Parameters
u – Random number input.
geom – Point geometry.
wi – Incident ray direction.
- Returns
Sampled direction and associated information.
-
virtual Float pdf_direction(const PointGeometry &geom, Vec3 wi, Vec3 wo) const = 0
Evaluate pdf in solid angle measure.
- Parameters
geom – Point geometry.
wi – Incident ray direction.
wo – Outgoing ray direction.
- Returns
Evaluated pdf.
-
virtual Vec3 eval(const PointGeometry &geom, Vec3 wi, Vec3 wo) const = 0
Evaluate the phase function.
- Parameters
geom – Point geometry.
wi – Incident ray direction.
wo – Outgoing ray direction.
- Returns
Evaluated value.
-
struct DirectionSample
- #include <phase.h>
Result of direction sampling.
-
struct DirectionSampleU
- #include <phase.h>
Random number input for direction sampling.
-
virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU &u, const PointGeometry &geom, Vec3 wi) const = 0
Texture
-
struct TextureSize
- #include <texture.h>
Texture size.
This structure represents a texture size used as a return type of
lm::Texture::size()
function.
-
struct lm::TextureBuffer
- #include <texture.h>
Texture buffer.
The structure represents a film buffer used as a return type of
lm::Texture::buffer()
function. The data format of the buffer is implementation-dependent. We restrict the underlying data type of the buffer to float vector.
-
class lm::Texture : public lm::Component
- #include <texture.h>
A component interface representing a texture used as an input of the materials.
Public Functions
-
virtual TextureSize size() const = 0
Get size of the texture.
- Returns
Size of the texture.
-
virtual Vec3 eval(Vec2 t) const = 0
Evaluate color component of the texture.
This function evaluate color of the texture of the specified texture coordinates. Handling of the texture coodinates outside of the range \([0,1]^2\) is implementation-dependent.
- Parameters
t – Texture coordinates.
-
virtual Vec3 eval_by_pixel_coords(int x, int y) const = 0
Evaluate color component of the texture by pixel coordinates.
This function evaluates color of the texture of the specified pixel coordinates.
- Parameters
x – x coordinate of the texture.
y – y coordinate of the texture.
-
inline virtual Float eval_alpha(Vec2 t) const
Evaluate alpha component of the texture.
This evalutes alpha component of the texture. If the texture has no alpha component, the behavior is undefined. Use
lm::Texture::has_alpha()
function to check if the texture has an alpha component.- Parameters
t – Texture coordinates.
-
inline virtual bool has_alpha() const
Check if texture has alpha component.
This function returns true if the texture has an alpha component.
-
inline virtual TextureBuffer buffer()
Get buffer of the texture.
- Returns
Texture buffer.
-
virtual TextureSize size() const = 0
Mesh
-
class lm::Mesh : public lm::Component
- #include <mesh.h>
Triangle mesh.
This component interface represents a triangle mesh, respondible for handling or manipulating triangle mesh.
Public Types
-
using ProcessTriangleFunc = std::function<void(int face, const Tri &tri)>
Callback function for processing a triangle.
The function of this type is used as a callback function to process a single triangle, used as an argument of
lm::Mesh::foreach_triangle()
function.- Parameters
face – Face index.
tri – Triangle.
Public Functions
-
virtual void foreach_triangle(const ProcessTriangleFunc &process_triangle) const = 0
Iterate triangles in the mesh.
This function enumerates all triangles inside the mesh. A specified callback function is called for each triangle.
- Parameters
process_triangle – Callback function to process a triangle.
-
virtual InterpolatedPoint surface_point(int face, Vec2 uv) const = 0
Compute surface geometry information at a point.
-
virtual int num_triangles() const = 0
Get number of triangles.
-
struct InterpolatedPoint
- #include <mesh.h>
Interpolated vertex of a triangle.
-
struct Point
- #include <mesh.h>
Vertex of a triangle.
Represents geometry information associated with a vertice of a triangle.
-
struct Tri
- #include <mesh.h>
Triangle.
Represents a triangle composed of three vertices.
-
using ProcessTriangleFunc = std::function<void(int face, const Tri &tri)>
Model
-
class lm::Model : public lm::Component
- #include <model.h>
3D model format.
The componet interface represents a 3D model that aggregates multiple meshes and materials. As well as meshes and materials, a model contains a set associations between meshes and materials, used to generate a set of scene primitives. See Scene setup using primitives for detail.
Public Types
-
using CreatePrimitiveFunc = std::function<void(Component *mesh, Component *material, Component *light)>
Callback function to process a primitive.
The function of this type is used as an argument of
lm::Model::create_primitives()
function.- Parameters
mesh – Underlying mesh.
material – Underlying material.
light – Underlying light.
-
using VisitNodeFuncType = std::function<void(const SceneNode &node)>
Callback function to process a scene node in the model.
This function is called for each visit of the scene node in the model, used as a callback function for
lm::Model::foreach_node()
.- Parameters
node – Scene node.
Public Functions
-
virtual void create_primitives(const CreatePrimitiveFunc &create_primitive) const = 0
Create primitives from underlying components.
This function enumerates a set of primitives generated from the model. A specified callback function is called for each primitive. The function is internally used by the framework, so the users do not want to used it directly.
- Parameters
create_primitive – Callback function to be called for each primitive.
-
virtual void foreach_node(const VisitNodeFuncType &visit) const = 0
Traverses scene nodes in the model.
A model can have its own scene graph to represent a scene. This function can be used to traverse scene nodes in that scene graph. For instance, this function is used by
lm::Scene
to copy the underlying scene graph to the main scene graph.- Parameters
visit – Callback function to be called for each visit of the scene node.
-
using CreatePrimitiveFunc = std::function<void(Component *mesh, Component *material, Component *light)>
Path sampling
-
static void sample_subpath_from_endpoint(Rng &rng, Path &path, const Scene *scene, int max_verts, TransDir trans_dir)
Sample path vertices from the endpoint.
This function samples a subpath from the last vertex of the given
path
. For detail, please refer to Sampling subpath.- Parameters
rng – Random number generator.
path – Subpath to be updated.
scene – Scene.
max_verts – Maximum number of vertices.
trans_dir – Transport direction.
-
static Path sample_subpath(Rng &rng, const Scene *scene, int max_verts, TransDir trans_dir)
Sample a subpath.
This function samples a subpath. For detail, please refer to Sampling subpath.
- Parameters
rng – Random number generator.
scene – Scene.
max_verts – Maximum number of vertices.
trans_dir – Transport direction.
- Returns
Sampled subpath.
-
static std::optional<Path> connect_subpaths(const Scene *scene, const Path &subpathL, const Path &subpathE, int s, int t)
Connect two subapths and generate a full path.
This function takes light and subapth and connect them to compose a fullpath by the specified number of vertices from the endpoints of each subpath. The function returns nullopt if the connection fails. For detail, please refer to Connecting subpaths.
- Parameters
scene – Scene.
subpathL – Light subpath.
subpathE – Eye subpath.
s – Number of light subpath vertices to be used.
t – Number of eye subpath vertices to be used.
- Returns
Connected fullpath. nullopt if failed.
-
static Ray primary_ray(const Scene *scene, Vec2 rp)
Generate a primary ray.
This function deterministically generates a primary ray corresponding to the given raster position.
- Parameters
scene – Scene.
rp – Raster position in [0,1]^2.
- Returns
Generated primary ray.
-
static std::optional<RaySample> sample_primary_ray(const RaySampleU &u, const Scene *scene, TransDir trans_dir)
Primary ray sampling.
This function samples a primary ray according the transport direction. If the transport direction is
LE
, the function generates a primary ray from a light. If the transport direction isEL
, the function generates a primary ray from a camera. In both cases, this function returnsnullopt
if the sampling failed, or the case when the early return is possible for instance when the evaluated contribution of the sampled direction is zero. For detail, please refer to Primary ray sampling.- Parameters
u – Random number input.
scene – Scene.
trans_dir – Transport direction.
-
static std::optional<RaySample> sample_primary_ray(Rng &rng, const Scene *scene, TransDir trans_dir)
Primary ray sampling.
This function samples a primary ray according the transport direction. This version takes random number generator instead of arbitrary random numbers.
- Parameters
rng – Random number generator.
scene – Scene.
trans_dir – Transport direction.
-
static Float pdf_primary_ray(const Scene *scene, const SceneInteraction &sp, Vec3 wo, bool eval_delta)
Evaluate PDF for primary ray sampling.
This function evaluate the PDF correcponding to
sample_primary_ray()
function. For detail, please refer to Primary ray sampling.- Parameters
scene – Scene.
sp – Sampled scene interaction.
wo – Sampled outgoing direction.
eval_delta – If true, evaluate delta function.
-
static ComponentSample sample_component(const ComponentSampleU &u, const Scene *scene, const SceneInteraction &sp, Vec3 wi)
Component sampling.
This function samples a component of the scene interaction accroding to its type. For detail, please refer to Component sampling.
-
static ComponentSample sample_component(Rng &rng, const Scene *scene, const SceneInteraction &sp, Vec3 wi)
Component sampling.
This function samples a component of the scene interaction accroding to its type. This version takes random number generator instead of arbitrary random numbers.
-
static Float pdf_component(const Scene *scene, const SceneInteraction &sp, Vec3 wi, int comp)
Evaluate PDF for component sampling.
This function evaluate the PDF correcponding to
sample_component()
function. For detail, please refer to Component sampling.
-
static std::optional<PositionSample> sample_position(const PositionSampleU &u, const Scene *scene, TransDir trans_dir)
Endpoint sampling.
This function samples an endpoint either on light or camera. If the transport direction is
LE
, an endpoint is sampled from light. If the transport direction isEL
, an endpoint is sampled from camera. For detail, please refer to Endpoint sampling.- Parameters
u – Random number input.
scene – Scene.
trans_dir – Transport direction.
-
static std::optional<PositionSample> sample_position(Rng &rng, const Scene *scene, TransDir trans_dir)
Endpoint sampling.
This function samples an endpoint either on light or camera. This version takes random number generator instead of arbitrary random numbers.
- Parameters
rng – Random number generator.
scene – Scene.
trans_dir – Transport direction.
-
static Float pdf_position(const Scene *scene, const SceneInteraction &sp)
Evaluate PDF for endpoint sampling.
This function evaluate the PDF correcponding to
sample_position()
function. For detail, please refer to Endpoint sampling.- Parameters
scene – Scene.
sp – Sampled scene interaction.
-
static std::optional<DirectionSample> sample_direction(const DirectionSampleU &u, const Scene *scene, const SceneInteraction &sp, Vec3 wi, int comp, TransDir trans_dir)
Direction sampling.
This function samples a direction given a scene interaciton point and incident direction from the point. For detail, please refer to Direction sampling.
-
static std::optional<DirectionSample> sample_direction(Rng &rng, const Scene *scene, const SceneInteraction &sp, Vec3 wi, int comp, TransDir trans_dir)
Direction sampling.
This function samples a direction given a scene interaciton point and incident direction from the point. This version takes random number generator instead of arbitrary random numbers.
-
static Float pdf_direction(const Scene *scene, const SceneInteraction &sp, Vec3 wi, Vec3 wo, int comp, bool eval_delta)
Evaluate pdf for direction sampling.
This function evaluate the PDF correcponding to
sample_direction()
function. For detail, please refer to Direction sampling.
-
static std::optional<RaySample> sample_direct(const RaySampleU &u, const Scene *scene, const SceneInteraction &sp, TransDir trans_dir)
Direct endpoint sampling.
This function samples a ray from the light to the given scene interaction. Be careful not to confuse the sampled ray with the ray sampled via
Scene::sample_ray()
function from a light source. Both rays are sampled from the different distributions and if you want to evaluate densities you want to use different functions. For detail, please refer to Direct endpoint sampling.
-
static std::optional<RaySample> sample_direct(Rng &rng, const Scene *scene, const SceneInteraction &sp, TransDir trans_dir)
Direct endpoint sampling.
This function samples a ray from the light to the given scene interaction. This version takes random number generator instead of arbitrary random numbers.
-
static Float pdf_direct(const Scene *scene, const SceneInteraction &sp, const SceneInteraction &sp_endpoint, Vec3 wo, bool eval_delta)
Evaluate pdf for endpoint sampling given a scene interaction.
This function evaluate pdf for the ray sampled via
Scene::sample_direct_light()
orScene::sample_direct_camera()
. Be carefulwo
is the outgoing direction originated fromsp_endpoint
, notsp
. For detail, please refer to Direct endpoint sampling.
-
static std::optional<DistanceSample> sample_distance(Rng &rng, const Scene *scene, const SceneInteraction &sp, Vec3 wo)
Sample a distance in a ray direction.
This function samples either a point in a medium or a point on the surface. Note that we don’t provide corresponding PDF function because some underlying distance sampling technique might not have the analytical representation.
-
static Vec3 eval_transmittance(Rng &rng, const Scene *scene, const SceneInteraction &sp1, const SceneInteraction &sp2)
Evaluate transmittance.
This function evaluates transmittance between two scene interaction events. This function might need a random number generator because heterogeneous media needs stochastic estimation. If the space between
sp1
andsp2
is vacuum (i.e., no media), this function is conceptually equivalent toScene::visible()
.
-
static bool is_specular_component(const Scene *scene, const SceneInteraction &sp, int comp)
Check if the scene intersection is specular.
This function checks if the directional component \(f_{s\Sigma}(\mathbf{x},j,\omega_i,\omega_o)\) contains a delta function. If contains, this function returns true. For detail, please refer to path_sampling_specular_vertex.
-
static bool is_connectable_endpoint(const Scene *scene, const SceneInteraction &sp)
Check if the endpoint is connectable.
This function checks if the endpoint can be connectable from another point in the scene. For detail, please refer to path_sampling_connectable_endpoint.
-
static std::optional<Vec2> raster_position(const Scene *scene, Vec3 wo)
Compute a raster position.
- Parameters
scene – Scene.
wo – Primary ray direction.
- Returns
Raster position.
-
static Vec3 eval_contrb_direction(const Scene *scene, const SceneInteraction &sp, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta)
Evaluate directional components.
The function evaluates directional component of path integral. This function generalizes several functions according to the type of scene interaction. For detail, please refer to Evaluating directional components.
Note that the scene interaction obtained from
Scene::intersect()
orScene::sample_distance()
is not an endpont even if it might represent either a light or a sensor. In this case, you want to uselm::SceneInteraction::as_type()
to enforce an evaluation as an endpoint.
-
static std::optional<Vec3> reflectance(const Scene *scene, const SceneInteraction &sp)
Evaluate reflectance (if available).
This function evaluate reflectance if
sp
is on a surface and the associated material implementsMaterial::reflectance()
function.- Parameters
scene – Scene.
sp – Surface interaction.
-
struct Path
- #include <bidir.h>
Light transport path.
Represents a light transport path (or just path). This structure can represents two types of paths: subpath or fullpath. For detail, please refer to Light transport path.
Public Functions
-
inline int num_verts() const
Get number of vertices of the path.
-
inline int num_edges() const
Get path length.
-
inline int index(int i, TransDir trans_dir) const
Compute index to access vertex array according to the transport direction.
This function returns the index of the path vertex vector
vs
counted from the endpoint of the path according to the transport direction. If the transport direction isEL
, the function returns the index of i-th vertex counted from the light vertex. If the transport direction isLE
, the function returns the index of i-th vertex counted from the eye vertex. This function is only valid when the path is a full path.- Parameters
i – Index of the subpath.
trans_dir – Transport direction.
-
inline const Vert *vertex_at(int i, TransDir trans_dir) const
Get a pointer to a path vertex (for fullpath).
This function returns a pointer to a path vertex according to an index of the subpath specified by the transport direction. If index is out of range, the function returns nullptr. This function is only valid when the path is a fullpath.
- Parameters
i – Index of the subpath.
trans_dir – Transport direction.
-
inline const Vert *subpath_vertex_at(int i) const
Get a pointer to a path vertex (for subpath).
This function returns a point to a path vertex inside a subpath. If the index is out of range, the function returns nullptr. This is only valid the path is a subpath.
- Parameters
i – Index of the subpath.
-
inline Vert *subpath_vertex_at(int i)
Get a pointer to a path vertex (for subpath).
This function returns a point to a path vertex inside a subpath. If the index is out of range, the function returns nullptr. This is only valid the path is a subpath.
- Parameters
i – Index of the subpath.
-
inline Vec3 direction(const Vert *v_from, const Vert *v_to) const
Compute direction between path vertices.
This function computes the direction from the vertex
v_from
tov_to
. If either of the vertex is nullptr, the function returns invalid vector. The function is useful when the vertex can be empty, as a result of out-of-range access bylm::Path::vertex_at()
orlm::Path::subpath_vertex_at()
functions.- Parameters
v_from – Vertex as an origin.
v_to – Vertex as a target.
-
inline Vec2 raster_position(const Scene *scene) const
Compute raster position.
This function computes the raster position using the primary ray from the eye vertex. This function is only valid when the path is a fullpath.
- Parameters
scene – Scene.
-
inline bool is_samplable_bidir(const Scene *scene, int s) const
Check if the path is samplable.
This function checks if the path is samplable by the bidirectional path sampling strategy indexed by
s
. This function is necessary to compute bidirecitonal path PDF. For detail, please refer to Connecting subpaths.- Parameters
scene – Scene.
s – Strategy index.
- Returns
True if the path is samplable by the strategy.
-
inline Vec3 eval_subpath_sampling_weight(const Scene *scene, int l, TransDir trans_dir) const
Evaluate subpath contribution.
This function computes the subpath contribution. \(\alpha_L(\bar{y})\) when
trans_dir
is LE. \(\alpha_E(\bar{z})\) whentrans_dir
is EL. For detail, please refer to Evaluating sampling weight.- Parameters
scene – Scene.
l – Number of vertices.
trans_dir – Transport direction.
-
inline Vec3 eval_connection_term(const Scene *scene, int s) const
Evaluate connection term.
This function evaluates the connection term \(c_{s,t}\). For detail, please refer to Evaluating measurement contribution.
- Parameters
scene – Scene.
s – Strategy index.
-
inline Vec3 eval_sampling_weight_bidir(const Scene *scene, int s) const
Evaluate sampling weight.
This function evaluates the sampling weight \(C^*_{s,t}(\bar{x})\). For detail, please refer to path::path_sampling_evaluating_sampling_weight.
- Parameters
scene – Scene.
s – Strategy index.
-
inline Vec3 eval_measurement_contrb_bidir(const Scene *scene, int s) const
Evaluate measreument contribution function.
This function evaluates the measurement contribution function f_{s,t}(bar{x}). For detail, please refer to Evaluating measurement contribution.
- Parameters
scene – Scene.
s – Strategy index.
-
inline Float pdf_bidir(const Scene *scene, int s) const
Evaluate bidirectional path PDF.
This function evaluats the bidirectional path PDF \(p_{s,t}(\bar{x})\). For detail, please refer to Evaluating bidirectional path PDF.
- Parameters
scene – Scene.
s – Strategy index.
-
inline Float eval_mis_weight(const Scene *scene, int s) const
Evaluate MIS weight.
This function evaluates the MIS weight via power heuristic. For detail, please refer to Evaluating MIS weight.
- Parameters
scene – Scene.
s – Strategy index.
-
inline int num_verts() const
-
struct lm::path::RaySample
- #include <path.h>
Result of ray sampling.
Public Functions
-
struct RaySampleU
- #include <path.h>
Random number input for ray sampling.
-
struct ComponentSample
- #include <path.h>
Result of component sampling.
-
struct ComponentSampleU
- #include <path.h>
Result of component sampling.
-
struct PositionSample
- #include <path.h>
Result of endpint sampling.
-
struct PositionSampleU
- #include <path.h>
Random number input for endpoint sampling.
-
struct DirectionSample
- #include <path.h>
Result of direction sampling.
-
struct DirectionSampleU
- #include <path.h>
Random number input for direction sampling.
-
struct lm::path::DistanceSample
- #include <path.h>
Result of distance sampling.
Public Members
-
SceneInteraction sp
Sampled interaction point.
-
SceneInteraction sp