API reference

User

constexpr const char *lm::user::DefaultType = "user::default"

Default user type.

void lm::init(const std::string &type = user::DefaultType, const Json &prop = {})

Initialize the renderer.

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
  • type: Type of user context.

  • prop: Properties for configuration.

void lm::shutdown()

Shutdown the renderer.

Call this function if you want explicit shutdown of the renderer. If you want to use scoped initialization/shutdown, consider to use lm::ScopedInit.

Shutdown the renderer.

Shutdown progress reporter context.

Shutdown parallel context.

Shutdown logger context.

Shutdown exception context.

Shutdown debugio server context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

void lm::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 lm::info()

Print information about Lightmetrica.

std::string lm::asset(const std::string &name, const std::string &implKey, const Json &prop)

Create an asset.

Asset represents a basic component of the scene object such as meshes or materials. We use assets as building blocks to construct the scene of the framework. This function creates an instance of an asset and register it to the framework by a given identifier. name is used as a reference by other APIs. implKey has a format of <asset type>::<implementation>. If name is already registered or implKey is missing, the framework will generate corresponding error messages through logger system as well as runtime error exception.

Return

Locator of the asset.

See

example/blank.cpp

Parameters
  • name: Identifier of the asset.

  • implKey: Name of the asset to create.

  • prop: Properties for configuration.

std::string lm::asset(const std::string &name)

Get the locator of an asset.

Return

Locator of the asset.

Parameters
  • name: Identifier of the asset.

void lm::build(const std::string &accelName, const Json &prop = {})

Build acceleration structure.

Some renderers require acceleration structure for ray-scene intersections. This function internally creates and registers an acceleration structure used by other parts of the framework. You may specify the acceleration structure type by accel::<type> format.

See

example/raycast.cpp

Parameters
  • accelName: Type of acceleration structure.

  • prop: Property for configuration.

void lm::renderer(const std::string &rendererName, const Json &prop = {})

Initialize renderer.

Parameters
  • rendererName: Type of renderer.

  • prop: Property for configuration.

void lm::render(bool verbose = true)

Render image based on current configuration.

Once you have completed all configuration of the scene, you may start rendering using this function. You may specify the renderer type by renderer::<type> format.

See

example/raycast.cpp

Parameters
  • verbose: Supress outputs if false.

static void lm::render(const std::string &rendererName, const Json &prop = {})

Initialize renderer and render.

Parameters
  • rendererName: Type of renderer.

  • prop: Property for configuration.

void lm::save(const std::string &filmName, const std::string &outpath)

Save an image.

This function saves the film to the specified output path. The behavior of the save depends on the asset type specified in filmName.

See

example/blank.cpp

Parameters
  • filmName: Identifier of a film asset.

  • outpath: Output path.

FilmBuffer lm::buffer(const std::string &filmName)

Get buffer of an image.

This function obtains the buffer to the film asset specified by filmName.

Return

Film buffer.

Parameters
  • filmName: Identifier of a film asset.

void lm::serialize(std::ostream &os)

Serialize the internal state of the framework to a stream.

Parameters
  • os: Output stream.

void lm::deserialize(std::istream &is)

Deserialize the internal state of the framework from a stream.

Parameters
  • is: Input stream.

void lm::serialize(const std::string &path)

Serialize the internal state to a file.

Parameters
  • path: Path to a file with serialized state.

void lm::deserialize(const std::string &path)

Deserialize the internal state to a file.

Parameters
  • path: to a file with serialized state.

void lm::validate()

Validate consistency of the component instances.

int lm::rootNode()
int lm::primitiveNode(const Json &prop)
int lm::groupNode()
int lm::instanceGroupNode()
int lm::transformNode(Mat4 transform)
void lm::addChild(int parent, int child)
void lm::addChildFromModel(int parent, const std::string &modelLoc)
void lm::primitive(Mat4 transform, 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
  • group: Group index.

  • transform: Transformation matrix.

  • prop: Properties for configuration.

class ScopedInit
#include <user.h>

Scoped guard of init and shutdown functions.

Example:

{
     ScopedInit init_;
     // Do something using API
     // ...
}
// Now the framework was safely shutdown.
// All API calls after this line generates errors.

class UserContext : public lm::Component
#include <user.h>

User context.

You may implement this interface to replace user APIs. Each virtual function corresponds to API call with functions above.

Log

enum log::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 with Err log level.

Values:

Debug = -10

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.

Info = 10

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.

Warn = 20

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.

Err = 30

Error message. This error level notifies you an error happens in the execution. The error often comes along with immediate shutdown of the renderer.

Progress = 100

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.

ProgressEnd = 100

End of progress message. The message indicates special message type used in the end of the progress message.

constexpr const char *lm::log::DefaultType = "logger::default"

Default logger type.

void lm::log::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 lm::log::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.

Shutdown exception context.

Shutdown debugio server context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

void lm::log::setSeverity(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 lm::log::setSeverity(LogLevel severity)
void lm::log::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 lm::log::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 lm::log::updateIndentation(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 and shutdown functions.

class LoggerContext : public lm::Component
#include <logger.h>

Logger context.

You may implement this interface to implement user-specific log subsystem. Each virtual function corresponds to API call with functions inside log namespace.

Exception

constexpr const char *lm::exception::DefaultType = "exception::default"

Default exception type.

void lm::exception::init(const std::string &type = DefaultType, 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
  • type: Type of exception subsystem.

  • prop: Properties for configuration.

void lm::exception::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.

Shutdown exception context.

Shutdown debugio server context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

void lm::exception::enableFPEx()

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 lm::exception::disableFPEx()

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 lm::exception::stackTrace()

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.

class ScopedInit
#include <exception.h>

Scoped guard of init and shutdown functions.

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 ExceptionContext : public lm::Component
#include <exception.h>

Exception context.

You may implement this interface to implement user-specific exception subsystem. Each virtual function corresponds to API call with a free function inside exception namespace.

Parallel

using lm::parallel::ParallelProcessFunc = std::function<void(long long index, int threadId)>

Callback function called for each iteration of the parallel process.

Parameters
  • index: Index of iteration.

  • threadId: Thread identifier in 0 ... numThreads()-1.

constexpr const char *lm::parallel::DefaultType = "parallel::openmp"

Default parallel context type.

void lm::parallel::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 lm::parallel::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.

Shutdown exception context.

Shutdown debugio server context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

int lm::parallel::numThreads()

Get number of threads configured for the subsystem.

Return

Number of threads.

bool lm::parallel::mainThread()

Check if current thread is the main thread.

Return

true if the current thread is the main thread, false otherwise.

void lm::parallel::foreach(long long numSamples, const ParallelProcessFunc &processFunc)

Parallel for loop.

We provide an abstraction for the parallel loop specifialized for rendering purpose.

Parameters
  • numSamples: Total number of samples.

  • processFunc: Callback function called for each iteration.

class ParallelContext : public lm::Component
#include <parallel.h>

Parallel context.

You may implement this interface to implement user-specific parallel subsystem. Each virtual function corresponds to API call with a free function inside parallel namespace.

Progress

constexpr const char *lm::progress::DefaultType = "progress::default"

Default progress reporter type.

void lm::progress::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 lm::progress::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.

Shutdown exception context.

Shutdown debugio server context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

void lm::progress::start(long long total)

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 use ScopedReport class to automatically enable/disable the floating point exception inside a scope.

Parameters
  • total: Total number of iterations.

void lm::progress::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 lm::progress::update(long long processed)

Update progress.

This function notifies the update of the progress to the subsystem. processed must be between 0 to total specified in the lm::progress::start() function.

Parameters
  • processed: Processed iterations.

class ScopedReport
#include <progress.h>

Scoped guard of start and end functions.

class ProgressContext : public lm::Component
#include <progress.h>

Progress context.

You may implement this interface to implement user-specific progress reporting subsystem. Each virtual function corresponds to API call with a free function inside progress namespace.

Debug IO

enum debugio::[anonymous]

Debugio mesh type.

This structure represents mesh type for debug visualization, used as an argument of lm::debugio::draw() function.

Values:

Triangles = 1 << 0

Triangle mesh.

LineStrip = 1 << 1

Line strip.

Lines = 1 << 2

Lines.

Points = 1 << 3

Points.

using lm::debugio::server::HandleMessageFunc = std::function<void(const std::string &message)>

Callback function for handleMessage.

Parameters
  • message: Received message.

using lm::debugio::server::SyncUserContextFunc = std::function<void()>

Callback function for syncUserContext.

using lm::debugio::server::DrawFunc = std::function<void(int type, Vec3 color, const std::vector<Vec3> &vs)>

Callback function for draw.

Parameters

void lm::debugio::init(const std::string &type, const Json &prop)

Initialize debugio context.

This function initializes debugio subsystem with specified type and properties.

Parameters
  • type: Type of debugio subsystem.

  • prop: Configuration properties.

void lm::debugio::shutdown()

Shutdown debugio context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

void lm::debugio::handleMessage(const std::string &message)

Handle a message.

Parameters
  • message: Send a message to the server.

void lm::debugio::syncUserContext()

Synchronize the state of user context.

This function synchronizes the internal state of the user context of the client process to the server process.

void lm::debugio::draw(int type, Vec3 color, const std::vector<Vec3> &vs)

Query drawing to visual debugger.

Parameters

void lm::debugio::server::init(const std::string &type, const Json &prop)

Initialize debugio server context.

This function initializes debugio server subsystem with specified type and properties.

Parameters
  • type: Type of debugio server subsystem.

  • prop: Configuration properties.

void lm::debugio::server::shutdown()

Shutdown debugio server context.

This function shutdowns debugio server subsystem. You may consider to use lm::debugio::server::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

Shutdown debugio server context.

This function shutdowns debugio subsystem. You may consider to use lm::debugio::ScopedInit class if you want to explicitly shutdown the subsystem at the end of the scope, instead of call this function directly.

void lm::debugio::server::poll()

Poll events.

void lm::debugio::server::run()

Start to run the server.

void lm::debugio::server::on_handleMessage(const HandleMessageFunc &process)

Register callback function for handleMessage.

Parameters
  • process: Callback function.

void lm::debugio::server::on_syncUserContext(const SyncUserContextFunc &process)

Register callback function for syncUserContext.

Parameters
  • process: Callback function.

void lm::debugio::server::on_draw(const DrawFunc &process)

Register callback function for draw.

Parameters
  • process: Callback function.

class ScopedInit
#include <debugio.h>

Scoped guard of init and shutdown functions.

class DebugioContext : public lm::Component
#include <debugio.h>

Debugio context.

class ScopedInit
#include <debugio.h>

Scoped guard of init and shutdown functions.

class DebugioServerContext : public lm::Component
#include <debugio.h>

Debugio server context.

Json

lm::Json operator""_lmJson(const char *s, size_t n)

String literal for JSON types.

Json lm::json::merge(const Json &j1, const Json &j2)

Merge two parameters.

If the same key is used, the value in j1 has priority.

template<size_t N>
Json lm::json::parsePositionalArgs(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 string temp 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 lm::json::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 lm::json::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>
std::optional<T> lm::json::valueOrNone(const Json &j, const std::string &name)

Math

using lm::Vec2 = glm::tvec2<Float>

2d vector

using lm::Vec3 = glm::tvec3<Float>

3d vector

using lm::Vec4 = glm::tvec4<Float>

4d vector

using lm::Mat3 = glm::tmat3x3<Float>

3x3 matrix

using lm::Mat4 = glm::tmat4x4<Float>

4x4 matrix

using lm::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).

constexpr Float lm::Inf = 1e+10_f

Big number.

constexpr Float lm::Eps = 1e-4_f

Error tolerance.

constexpr Float lm::Pi = 3.14159265358979323846_f

Value of Pi.

static std::tuple<Vec3, Vec3> lm::math::orthonormalBasis(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.

template<typename VecT>
static VecT lm::math::mixBarycentric(VecT a, VecT b, VecT c, Vec2 uv)

Interpolation with barycentric coordinates.

Return

Interpolated value.

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.

template<typename VecT>
static bool lm::math::isZero(VecT v)

Check if components of a vector are all zeros.

Return

true if components are all zeros, false otherwise.

Parameters
  • v: A vector.

static Float lm::math::safeSqrt(Float v)

Square root handling possible negative input due to the rounding error.

Return

Square root of the input value.

Parameters
  • v: Value.

static Float lm::math::sq(Float v)

Compute square.

Return

Square of the input value.

Parameters
  • v: Value.

static Vec3 lm::math::reflection(Vec3 w, Vec3 n)

Reflected direction.

Return

Reflected direction.

Parameters
  • w: Incident direction.

  • n: Surface normal.

static RefractionResult lm::math::refraction(Vec3 wi, Vec3 n, Float eta)

Refracted direction.

Return

Refracted direction.

Parameters
  • wi: Incident direction.

  • n: Surface normal.

  • eta: Relative ior.

static Vec3 lm::math::sampleCosineWeighted(Rng &rng)

Cosine-weighted direction sampling.

Return

Sampled value.

Parameters
  • rng: Random number generator.

static Float lm::math::balanceHeuristic(Float p1, Float p2)

Balance heuristics.

struct Ray
#include <math.h>

Ray.

Public Members

Vec3 o

Origin.

Vec3 d

Direction.

struct Bound
#include <math.h>

Axis-aligned bounding box.

Public Functions

Vec3 operator[](int i) const

Index operator.

Return

0: minimum coordinates, 1: maximum coordinates.

Vec3 center() const

Return centroid of the bound.

Return

Centroid.

Float surfaceArea() const

Surface area of the bound.

Return

Surface area.

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.

Public Members

Vec3 mi = Vec3(Inf)

Minimum coordinates.

Vec3 ma = Vec3(-Inf)

Maximum coordinates.

Friends

Bound merge(Bound b, Vec3 p)

Merge a bound and a point.

Return

Merged bound.

Parameters

Bound merge(Bound a, Bound b)

Merge two bounds.

Return

Merged bound.

Parameters

struct Dist
#include <math.h>

1d discrete distribution.

Public Functions

void add(Float v)

Add a value to the distribution.

Parameters
  • v: Value to be added.

void norm()

Normalize the distribution.

Float p(int i) const

Evaluate pmf.

Return

Evaluated pmf.

Parameters
  • i: Index.

int samp(Rng &rn) const

Sample from the distribution.

Return

Sampled index.

Parameters
  • rn: Random number generator.

struct Dist2
#include <math.h>

2d discrete distribution.

Public Functions

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.

Float p(Float u, Float v) const

Evaluate pmf.

Return

Evaluated pmf.

Parameters
  • u: Index in column.

  • v: Index in row.

Vec2 samp(Rng &rn) const

Sample from the distribution.

Return

Sampled position.

Parameters
  • rn: Random number generator.

struct RefractionResult
#include <math.h>

Result of refraction() function.

struct Transform
#include <math.h>

Transform.

Public Functions

Transform(const Mat4 &M)

Construct the transform with 4x4 transformation matrix.

Parameters
  • M: Transformation matrix.

Public Members

Mat4 M

Transform associated to the primitive.

Mat3 normalM

Transform for normals.

Float J

J := |det(M_lin)| where M_lin is linear component of M.

Component

Component *lm::comp::detail::createComp(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 with loadPlugin() function if the component is defined inside a plugin. Otherwise the function returns nullptr with error message.

Parameters
  • key: Implementation key.

void lm::comp::detail::reg(const std::string &key, const Component::CreateFunction &createFunc, const Component::ReleaseFunction &releaseFunc)

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.

  • createFunc: Create function.

  • releaseFunc: Release function.

void lm::comp::detail::unreg(const std::string &key)

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.

bool lm::comp::detail::loadPlugin(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 returns false.

Parameters
  • path: Path to a plugin.

void lm::comp::detail::loadPluginDirectory(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 lm::comp::detail::unloadPlugins()

Unload loaded plugins.

This functions unloads all the plugins loaded so far.

void lm::comp::detail::foreachRegistered(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 lm::comp::detail::registerRootComp(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

Component *lm::comp::detail::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.

Parameters

Template Parameters
Parameters

template<typename T>
T *lm::comp::get(const std::string &locator)

Get component by locator.

Template Parameters
Parameters

template<typename T>
std::enable_if_t<std::is_base_of_v<lm::Component, T>, void> lm::comp::updateWeakRef(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> lm::comp::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> lm::comp::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> lm::comp::create(const std::string &key, const std::string &loc)

Create component with specific interface type.

Template Parameters
Parameters
  • key: Name of the implementation.

  • loc: Component locator of the instance.

template<typename InterfaceT>
Component::Ptr<InterfaceT> lm::comp::create(const std::string &key, const std::string &loc, const Json &prop)

Create component with construction with given properties.

Template Parameters
Parameters
  • key: Name of the implementation.

  • loc: Component locator of the instance.

  • prop: Properties.

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 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::Assets, lm::Camera, lm::debugio::DebugioContext, lm::debugio::server::DebugioServerContext, lm::dist::DistMasterContext, lm::dist::worker::DistWorkerContext, lm::exception::detail::ExceptionContext, lm::Film, lm::Light, lm::log::detail::LoggerContext, lm::Material, lm::Mesh, lm::Model, lm::objloader::OBJLoaderContext, lm::parallel::ParallelContext, lm::progress::detail::ProgressContext, lm::Renderer, lm::Scene, lm::Texture, lm::user::detail::UserContext

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.

Return

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

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

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::foreachUnderlying() function.

Parameters
  • p: Visiting component instance.

  • weak: True if the visiting instance is referred as a weak reference.

Public Functions

const std::string &key() const

Get name of component instance.

This function returns an unique identifier of the component implementation of the instance.

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.

const std::string parentLoc() 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 returns aaa.bbb. If the current locator is aaa, this function returns empty string.

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.

const std::string makeLoc(const std::string &base, const std::string &child) const

Make locator by appending string.

This function appends the specified child locator into the back of base locator.

Parameters
  • base: Base locator.

  • child: Child locator.

const std::string makeLoc(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.

virtual bool 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. The return values indicates if the construction suceeded or not.

Parameters
  • prop: Configuration property.

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.

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.

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.

virtual void foreachUnderlying(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

virtual Json underlyingValue(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.

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 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()->...
Template Parameters

Public Static Functions

static ContextComponentT &get()

Get a reference to the underlying component.

Return

Reference to the underlying component.

static 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 void shutdown()

Delete the underlying component.

static 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 and loadPlugins.

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.

Template Parameters
  • ImplType: Type of component implementation.

Acceleration structure

class 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.

struct Hit
#include <accel.h>

Hit result.

Shows information associated to the hit point of the ray. More additional information like surface positions can be obtained from querying appropriate data types from these information.

Public Members

Float t

Distance to the hit point.

Vec2 uv

Barycentric coordinates.

Transform globalTransform

Global transformation.

int primitive

Primitive node index.

int face

Face index.

Scene

enum scene::SceneNodeType

Values:

Primitive
Group
static Float lm::surface::geometryTerm(const PointGeometry &s1, const PointGeometry &s2)

Compute geometry term.

This function computes the geometry term \(G(\mathbf{x}\leftrightarrow\mathbf{y})\) from the two surface points \(\mathbf{x}\) and \(\mathbf{y}\). This function can accepts extended points represented by lm::PointGeometry.

Parameters
  • s1: First point.

  • s2: Second point.

struct RaySample
#include <scene.h>

Result of ray sampling.

This structure represents the result of ray sampling used by the functions of lm::Scene class.

Public Functions

Ray ray() const

Get a ray from the sample.

This function constructs a lm::Ray structure from the ray sample.

Public Members

SurfacePoint sp

Surface point information.

Vec3 wo

Sampled direction.

Vec3 weight

Contribution divided by probability.

struct SceneNode
#include <scene.h>

Scene primitive.

This structure represents a scene primitive. The scene is described by a set of primitives and a primitive describes an object in the scene, which associates various scene components like mesh or material. A primitive can represent three types of scene objects.

  1. Scene geometry. If mesh != nullptr and material != 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.

  2. 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.

  3. 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 and camera cannot be non-nullptr in the same time.

A set of primitives is managed internally by the implementation of lm::Scene and the class exposes a facade for the sampling and evaluation functions for the underlying component interfaces. Thus the users usually do not need to explicitly access the underlying component interfaces of a primitive.

Public Members

SceneNodeType type

Scene node type.

int index

Node index.

Mesh *mesh = nullptr

Underlying mesh.

Material *material = nullptr

Underlying material.

Light *light = nullptr

Underlying light.

Camera *camera = nullptr

Underlying camera.

std::vector<int> children

Child primitives.

bool instanced

True if the group is an instance group.

std::optional<Mat4> localTransform

Transformation applied to children.

Public Static Functions

static SceneNode makePrimitive(int index, Mesh *mesh, Material *material, Light *light, Camera *camera)

Make primitive node.

static SceneNode makeGroup(int index, bool instanced, std::optional<Mat4> localTransform)

Make group node.

class Scene : public lm::Component
#include <scene.h>

Scene.

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. For detail, see TODO.

Public Types

using NodeTraverseFunc = std::function<void(const SceneNode &node, Mat4 globalTransform)>

Iterate primitives in the scene.

Public Functions

virtual bool renderable() const = 0

Check if the scene is renderable.

This function returns true if the scene is renderable. If not, the function returns false with error messages.

virtual int createNode(SceneNodeType type, const Json &prop) = 0

Load scene node(s).

This function construct a primitive and add it to the scene given the transformation and the references specified in prop. The type of the primitive created by this function changes according to the properties in prop. The function returns true if the loading is a success.

Parameters
  • groupPrimitiveIndex: Group index.

  • transform: Transformation associated to the primitive.

  • prop: Property containing references to the scene components.

virtual void addChild(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
  • groupName: Name of the group.

virtual void build(const std::string &name, const Json &prop) = 0

Build acceleration structure.

Parameters
  • name: Name of the acceleration structure.

  • prop: Property for configuration.

virtual std::optional<SurfacePoint> intersect(Ray ray, Float tmin = Eps, Float tmax = Inf) const = 0

Compute closest intersection point.

bool visible(const SurfacePoint &sp1, const SurfacePoint &sp2) const

Check if two surface points are mutually visible.

virtual bool isLight(const SurfacePoint &sp) const = 0

Check if given surface point is light.

virtual bool isSpecular(const SurfacePoint &sp) const = 0

Check if given surface point is specular.

virtual Ray primaryRay(Vec2 rp, Float aspectRatio) const = 0

Generate a primary ray.

virtual std::optional<RaySample> sampleRay(Rng &rng, const SurfacePoint &sp, Vec3 wi) const = 0

Sample a ray given surface point and incident direction.

(x,wo) ~ p(x,wo|sp,wi)

virtual std::optional<RaySample> samplePrimaryRay(Rng &rng, Vec4 window, Float aspectRatio) const = 0

Sample a ray given pixel position.

(x,wo) ~ p(x,wo|raster window)

virtual std::optional<RaySample> sampleLight(Rng &rng, const SurfacePoint &sp) const = 0

Sample a position on a light.

virtual Float pdf(const SurfacePoint &sp, Vec3 wi, Vec3 wo) const = 0

Evaluate pdf for direction sampling.

virtual Float pdfLight(const SurfacePoint &sp, const SurfacePoint &spL, Vec3 wo) const = 0

Evaluate pdf for light sampling.

virtual Vec3 evalBsdf(const SurfacePoint &sp, Vec3 wi, Vec3 wo) const = 0

Evaluate extended BSDF.

virtual Vec3 evalContrbEndpoint(const SurfacePoint &sp, Vec3 wo) const = 0

Evaluate endpoint contribution.

f(x,wo) where x is endpoint

virtual std::optional<Vec3> reflectance(const SurfacePoint &sp) const = 0

Evaluate reflectance (if available).

rho(x)

struct PointGeometry
#include <surface.h>

Geometry information of a point inside the scene.

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.

  1. A point on the 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 and v

  2. A point in the air. The sturcture describes a point in the air if degenerated=true, for instance used to represent a position of point light or pinhole camera. The associated information is the position p.

  3. A point at infinity. 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 infinity wo.

Public Functions

bool opposite(Vec3 w1, Vec3 w2) const

Checks if two directions lies in the same half-space.

This function checks if two directions w1 and w2 lies in the same half-space divided by the tangent plane. w1 and w2 are interchangeable.

Parameters
  • w1: First direction.

  • w2: Second direction.

std::tuple<Vec3, Vec3, Vec3> orthonormalBasis(Vec3 wi) const

Return orthonormal basis according to the incident direction.

The function returns an orthornormal basis according to the incident direction wi. If wi 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.

Vec3 p

Position.

Vec3 n

Shading normal.

Vec3 wo

Direction from a point at infinity.

Vec2 t

Texture coordinates.

Vec3 v

Orthogonal tangent vectors.

Public Static Functions

static PointGeometry makeDegenerated(Vec3 p)

Make degenerated point.

A static function to generate a point in the air from the specified position p.

Parameters
  • p: Position.

static PointGeometry makeInfinite(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 PointGeometry makeOnSurface(Vec3 p, Vec3 n, 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: Normal.

  • t: Texture coordinates.

static PointGeometry makeOnSurface(Vec3 p, Vec3 n)

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: Normal.

struct SurfacePoint
#include <surface.h>

Scene surface point.

Represents single point on the scene surface, which contains geometry information around a point and an index of the primitive associated with the point. The structure is used by the functions of lm::Scene class.

Public Members

int primitive

Primitive node index.

int comp

Component index.

PointGeometry geom

Surface point geometry information.

bool endpoint

True if endpoint of light path.

Renderer

class Renderer : public lm::Component
#include <renderer.h>

Renderer component interface.

Subclassed by Renderer_AO

Public Functions

virtual bool requiresScene() const

True if the scene is required.

virtual void render(const Scene *scene) const = 0

Process rendering.

Asset management

class Assets : public lm::Component
#include <assets.h>

Collection of assets.

Interfaces collection of assets. All instances of the assets (e.g., meshes, materials, etc.) of the framework are managed by this class. 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 by user namespace. See Preparing asset for detail.

Public Functions

virtual std::optional<std::string> loadAsset(const std::string &name, const std::string &implKey, const Json &prop) = 0

Loads an asset.

Loads an asset from the given information and registers to the class. implKey is used to create an instance and prop is used to construct it. prop is passed to lm::Component::construct() function of the implementation of the asset.

If the asset with same name is already loaded, the function tries to deregister the previously-loaded asset and reload an asset again. If the global component hierarchy contains a reference to the original asset, the function automatically resolves the reference to the new asset. For usage, see functest/func_update_asset.py.

Return

Locator of the asset. nullopt if failed.

Parameters
  • name: Name of the asset.

  • implKey: Key of component implementation in interface::implementation format.

  • prop: Properties.

Camera

struct CameraRaySample
#include <camera.h>

Result of primary ray sampling.

This structure represents the result of lm::Camera::samplePrimaryRay() function.

Public Members

PointGeometry geom

Sampled geometry information.

Vec3 wo

Sampled direction.

Vec3 weight

Contribution divided by probability.

class Camera : public lm::Component
#include <camera.h>

Camera.

This component interface represents a camera inside the scene, responsible for sampling and evaluation of the rays emitted from/to the camera.

Public Functions

virtual bool isSpecular(const PointGeometry &geom) const

Check if the camera contains delta component.

This function returns true if the sensitivity function \(W_e\) of the camera contains a component of delta function.

Parameters
  • geom: Surface geometry information.

virtual Ray primaryRay(Vec2 rp, Float aspectRatio) const

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 samplePrimaryRay() when the primary ray is generated randomly.

Parameters
  • rp: Raster position.

  • aspectRatio: Aspect ratio of the film.

virtual std::optional<CameraRaySample> samplePrimaryRay(Rng &rng, Vec4 window, Float aspectRatio) const

Sample a primary ray within the given raster window.

This function generates a uniformly random ray from the raster window inside the screen. The raster windows is specified by subregion of \([0,1]^2\) using 4d vector containing (x,y,w,h) where (x,y) is the bottom-left point of the region, and (w,h) is width and height of the region.

The sampled results are returned by CameraRaySample() structure. When sampling has failed, the function returns nullopt.

Mathematically the function defines a sampling from the distribution having a joint probability density \(p(\mathbf{x}, \omega)\) defined by the surface point \(\mathbf{x}\) and the direction \(\omega\) according to the produce measure of area measure and projected solid angle measure.

Note that the generated rays are uniform in a sense that each ray is generated from the uniform sampling of the raster window. Looking by the solid angle measure, for instance, the set of rays are not uniform.

Parameters
  • rng: Random number generator.

  • window: Raster window.

  • aspectRatio: Aspect ratio of the film.

virtual Vec3 eval(const PointGeometry &geom, Vec3 wo) const

Evaluate sensitivity.

Evaluates sensitivity function \(W_e(\mathbf{x}, \omega)\) of the camera.

Parameters
  • geom: Surface geometry information.

  • wo: Outgoing direction.

virtual Mat4 viewMatrix() const

Get view matrix if available.

Return

View matrix.

virtual Mat4 projectionMatrix(Float aspectRatio) const

Get projection matrix if available.

Return

Projection matrix.

Parameters
  • aspectRatio: Aspect ratio of the film.

Film

struct FilmSize
#include <film.h>

Film size.

This structure represents a film size used as a return type of lm::Film::size() function.

Public Members

int w

Width of the film.

int h

Height of the film.

struct 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.

Public Members

int w

Width of the buffer.

int h

Height of the buffer.

Float *data

Data.

class Film : public lm::Component
#include <film.h>

Film.

A component interface representing a film. The component is used as an output from renderers.

Public Functions

virtual FilmSize size() const = 0

Get size of the film.

Return

Size of the film.

virtual void setPixel(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.

Float aspectRatio() const

Get aspect ratio.

Return

Aspect ratio.

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.

Return

Film buffer.

virtual void accum(const Film *film) = 0

Accumulate another film.

Parameters
  • film: Another film.

virtual void splat(Vec2 rp, Vec3 v) = 0

Splat the color to the film.

Parameters
  • rp: Raster position.

  • v: Color.

virtual void clear() = 0

Clear the film.

Light

struct LightRaySample
#include <light.h>

Result of light sampling.

This structure represents the result of lm::Light::sample() function.

Public Members

PointGeometry geom

Sampled geometry information.

Vec3 wo

Sampled direction.

Vec3 weight

Contribution divided by probability.

class Light : public lm::Component
#include <light.h>

Light.

This component interface represents a light source inside the scene. responsible for sampling and evaluation of the rays emitted from/to the light source.

Public Functions

virtual bool isSpecular(const PointGeometry &geom) const = 0

Check if the light contains delta component.

This function returns true if the luminance function \(L_e\) of the light source contains a component of delta function.

Parameters
  • geom: Surface geometry information.

virtual std::optional<LightRaySample> sample(Rng &rng, const PointGeometry &geom, const Transform &transform) const = 0

Sample a position on the light.

This function samples a direction from the surface point geom toward the point on the light source. The transformation of the light source is specified by transform.

Mathmatically, the function samples a direction \(\omega\) from the conditional probability density \(p(\omega\mid \mathbf{x}')\) in projected solid angle measure given the surface point \(\mathbf{x}'\).

For convenience, the function also returns the point on the light source in the direction of the ray \((\mathbf{x}',\omega)\). If there is no corresponding surface geometry in the case of distant light source, geom.infinite becomes true.

Parameters
  • rng: Random number generator.

  • geom: Point geometry on the scene surface.

  • transform: Transformation of the light source.

virtual Float pdf(const PointGeometry &geom, const PointGeometry &geomL, const Transform &transform, Vec3 wo) const = 0

Evaluate pdf for light sampling in projected solid angle measure.

This function evalutes a pdf corresponding to lm::Light::sample() function. geomL is either the point on the light source or inifite point. If the given direction cannot be sampled, the function returns zero.

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.

virtual bool isInfinite() const = 0

Check if the light source is inifite distant light.

This function checks if the light source is inifite distant light such as environment light or directional light.

virtual Vec3 eval(const PointGeometry &geom, Vec3 wo) const = 0

Evaluate luminance.

This function evaluates luminance function \(L_e\) of the light source.

Parameters
  • geom: Point geometry on the light source.

  • wo: Outgoing direction from the point of the light source.

Material

struct MaterialDirectionSample
#include <material.h>

Result of direction sampling.

This structure represents the result of lm::Material::sample() function.

Public Members

Vec3 wo

Sampled direction.

int comp

Sampled component index.

Vec3 weight

Contribution divided by probability.

class Material : public lm::Component
#include <material.h>

Material.

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.

Subclassed by Material_VisualizeNormal

Public Functions

virtual bool isSpecular(const PointGeometry &geom, int comp) const

Check if the material is specular.

This function checks if the BSDF of the material contains delta component.

Parameters
  • geom: Point geometry.

  • comp: Component index.

virtual std::optional<MaterialDirectionSample> sample(Rng &rng, const PointGeometry &geom, Vec3 wi) const

Sample a ray given surface point and incident direction.

This function samples direction based on the probability distribution associated to the material. Mathematically, this function samples a direction \(\omega\) according to the pdf \(p(\omega\mid \mathbf{x}, \omega_i)\) in projected solid angle measure, where \(\mathbf{x}\) is a surface point and \(\omega_i\) is an incident ray direction.

If the material contains multiple component, this function also samples the component type. The selected component type is stored into lm::MaterialDirectionSample::comp.

Parameters
  • rng: Random number generator.

  • geom: Point geometry.

  • wi: Incident ray direction.

virtual std::optional<Vec3> reflectance(const PointGeometry &geom, int comp) const

Evaluate reflectance.

This function evaluates the reflectance function of the underlying material if exists.

Parameters
  • geom: Point geometry.

  • comp: Component index.

virtual Float pdf(const PointGeometry &geom, int comp, Vec3 wi, Vec3 wo) const

Evaluate pdf in projected solid angle measure.

This function evaluates a pdf corresponding to lm::Material::sample() function.

Parameters
  • geom: Point geometry.

  • comp: Component index.

  • wi: Incident ray direction.

  • wo: Outgoing ray direction.

virtual Vec3 eval(const PointGeometry &geom, int comp, Vec3 wi, Vec3 wo) const

Evaluate BSDF.

This function evaluates underlying BSDF of the material.

Parameters
  • geom: Point geometry.

  • comp: Component index.

  • wi: Incident ray direction.

  • wo: Outgoing ray direction.

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 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.

Public Members

int w

Width.

int h

Height.

int c

Components.

float *data

Underlying data type.

class Texture : public lm::Component
#include <texture.h>

Texture.

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.

Return

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

virtual Vec3 evalByPixelCoords(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.

virtual Float evalAlpha(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::hasAlpha() function to check if the texture has an alpha component.

Parameters

virtual bool hasAlpha() const

Check if texture has alpha component.

This function returns true if the texture has an alpha component.

virtual TextureBuffer buffer()

Get buffer of the texture.

Return

Texture buffer.

Mesh

class 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::foreachTriangle() function.

Parameters
  • face: Face index.

  • tri: Triangle.

Public Functions

virtual void foreachTriangle(const ProcessTriangleFunc &processTriangle) 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
  • processTriangle: Callback function to process a triangle.

virtual Tri triangleAt(int face) const = 0

Get triangle by face index.

virtual Point surfacePoint(int face, Vec2 uv) const = 0

Compute surface geometry information at a point.

struct Point
#include <mesh.h>

Vertex of a triangle.

Represents geometry information associated with a vertice of a triangle.

Public Members

Vec3 p

Position.

Vec3 n

Normal.

Vec2 t

Texture coordinates.

struct Tri
#include <mesh.h>

Triangle.

Represents a triangle composed of three vertices.

Public Members

Point p1

First vertex.

Point p2

Second vertex.

Point p3

Third vertex.

Model

class 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 Making scene 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::createPrimitives() function.

Parameters
  • mesh: Underlying mesh.

  • material: Underlying material.

  • light: Underlying light.

Public Functions

virtual void createPrimitives(const CreatePrimitiveFunc &createPrimitive) 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
  • createPrimitive: Callback function to be called for each primitive.