<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tutorial &#8211; Jacco&#039;s Blog</title>
	<atom:link href="https://jacco.ompf2.com/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>https://jacco.ompf2.com</link>
	<description>Links, Code &#38; Articles</description>
	<lastBuildDate>Fri, 25 Sep 2026 09:12:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://jacco.ompf2.com/wp-content/uploads/2019/03/cropped-robotlab-32x32.jpg</url>
	<title>Tutorial &#8211; Jacco&#039;s Blog</title>
	<link>https://jacco.ompf2.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>TinyBVH &#8211; Manual &#8211; Advanced</title>
		<link>https://jacco.ompf2.com/2025/01/25/tinybvh-manual-advanced/</link>
					<comments>https://jacco.ompf2.com/2025/01/25/tinybvh-manual-advanced/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Sat, 25 Jan 2025 18:32:11 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=2251</guid>

					<description><![CDATA[This document describes the TinyBVH header-only library for Bounding Volume Hierarchy construction and traversal, with a focus...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This document describes the TinyBVH header-only library for Bounding Volume Hierarchy construction and traversal, with a focus on ray tracing on CPU and GPU &#8211; to be used for graphics, audio or physics.</p>



<p class="wp-block-paragraph"><em>This document is currently in sync with TinyBVH version 1.9.0.</em></p>



<p class="wp-block-paragraph">TinyBVH is open source (MIT license) and <a href="https://github.com/jbikker/tinybvh">available on Github</a>.</p>



<p class="wp-block-paragraph">The manual is split up in multiple compact documents:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2025/01/24/tinybvh-manual-basic-use/">Basic Use. Building a BVH, tracing a ray, alternative layouts, TLAS/BLAS</a>.</li>



<li><strong>Advanced Topics (this document).</strong> GPU ray tracing, custom math libraries, TinyBVH settings.</li>
</ol>



<h3 class="wp-block-heading">Introduction</h3>



<p class="wp-block-paragraph">The first part of the TinyBVH manual discussed basic use of the header-only library. In this second part presents several more advanced topics. An overview:</p>



<ul class="wp-block-list">
<li>Using indexed triangles and vertex buffers</li>



<li>Building BVHs for the GPU: Layouts, considerations and best practices</li>



<li>Replacing the TinyBVH math library</li>



<li>Double-precision BVHs</li>



<li>Memory management: Design, callbacks</li>



<li>Using custom geometry</li>



<li>Collision queries</li>



<li>Low-level settings</li>
</ul>



<h3 class="wp-block-heading">Data Ownership, Indexed Input, Slices</h3>



<p class="wp-block-paragraph">The standard input for all builders is a raw list of four-component vectors. These are used in two places:</p>



<ul class="wp-block-list">
<li>During BVH construction: Each triangle is turned into a <em>fragment</em>, which stores AABB of the triangle and the index of the original.</li>



<li>During traversal: To intersect a triangle in a BVH leaf node, the original triangle data is needed.</li>
</ul>



<p class="wp-block-paragraph">The triangle data that is passed to <code>BVH::Build</code> is thus kept and should not be destroyed or changed between BVH construction and BVH traversal. Ownership of the data does however stay with the calling application.</p>



<p class="wp-block-paragraph">In some cases it is inconvenient to pass data in this exact format. For example when TinyBVH should operate on data that is also used by a rasterizer, where the vertex stream may contain x, y, z but also u, v and perhaps normal data. For this purpose a <code>bvhvec4slice</code> can be used (<code>tiny_bvh_base.h</code>, line 166):</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct bvhvec4slice
{
	bvhvec4slice() = default;
	bvhvec4slice( const bvhvec4* data, uint32_t count, uint32_t stride = sizeof( bvhvec4 ) );
	...
};</pre></div>



<p class="wp-block-paragraph">This struct encapsulates the vertex data pointer, along with a <em>stride</em> (in bytes). For four-component vector input, the stride defaults to 16.</p>



<p class="wp-block-paragraph">Using a <code>bvhvec4slice</code> as input for the builders has no impact on performance &#8211; In fact, passing a raw <code>bvhvec4</code> pointer results in the creation of a slice with stride 16. Do note however that the SIMD builders require each vertex to start at a <span style="text-decoration: underline;">16-byte boundary</span> in memory. If this can not be enforced, please disable <code>useSIMDifavailable</code> in <code>BVHBase::settings</code>.</p>



<p class="wp-block-paragraph">Apart from vertex buffers, rasterizers also typically use vertex indices to define each triangle. To support this input, each <code>Build</code> function accepts (next to the vertex list) an index list. An example:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bvh.Build( (bvhvec4*)verts, (uint32_t*)indices, TRIANGLE_COUNT );</pre></div>



<p class="wp-block-paragraph">If indices are provided, they will be kept along with the vertex data for use in the traversal functions. Please be aware that this adds a level of indirection when accessing vertex positions in the triangle intersection code; indexed data is therefore slightly slower (~5%) than a raw list of <code>bvhvec4</code>&#8216;s.</p>



<h3 class="wp-block-heading">GPU BVHs</h3>



<p class="wp-block-paragraph">Tracing rays on the GPU is these days typically done with dedicated hardware. This hardware reduces the computational cost of BVH traversal and triangle intersection &#8211; it does however not magically increase the memory bandwidth of the GPU. It is therefore most effective when bandwidth is not the bottleneck. </p>



<p class="wp-block-paragraph">In a typical ray tracer this is the case for coherent primary rays (those leaving the camera). Rays after a bounce are more divergent and tend to be more expensive. These rays also require more bandwidth, which somewhat limits the possible gains of the dedicated ray tracing hardware. Especially for these scattered rays the quality of the BVH is important. All vendors thus provide their own BVH builders, which generate BVHs that are hardware-specific and finely tuned.</p>



<p class="wp-block-paragraph">TinyBVH will currently not create BVHs in vendor-specific formats &#8211; although this may be different in a later version of the library, at least for vendors that disclose their BVH formats (currently: AMD and Intel).</p>



<p class="wp-block-paragraph">Instead, TinyBVH will produce several layouts that work well for GPUs in general. As on CPU, there is a balance to be found between BVH construction time and ray traversal time. Currently three GPU BVH layouts are available:</p>



<ul class="wp-block-list">
<li><code>BVH_GPU</code>: This layout follows the recommendations in a 2009 paper by Aila &amp; Laine. This BVH layout is easily obtained from the default BVH layout and offers good ray tracing performance. Traversal kernels for this format are short and simple and can easily be implemented in any shader or compute kernel.</li>



<li><code>BVH4_GPU</code>: This layout uses a wide (and thus shallow) BVH to speedup traversal of divergent rays. The reduced number of traversal steps improves memory coherency at the expense of more calculations per step, which is a good trade-off in most cases. Conversion is a bit more expensive than for the <code>BVH_GPU</code> layout, and traversal code is more complex.</li>



<li><code>CWBVH</code>: This is the final layout proposed by NVIDIA before introducing their RTX hardware. CWBVH uses an 8-wide BVH with heavily compressed nodes. Additionally, triangle data is stored without any indirection interleaved with the nodes for optimal access. This is a fast layout, but obtaining it is relatively costly. This is mostly useful for static geometry. Also note that the traversal kernel is complex.</li>
</ul>



<p class="wp-block-paragraph">Note that all vendors construct their BVHs on the GPU, rather than on the CPU. TinyBVH on the other hand assumes that BVHs are constructed and maintained on the CPU. This is because CPU builders tend to build better BVHs, and, more importantly: Because CPUs are typically under-utilized in modern games. Even if the CPU requires more time to prepare the BVH, frame time improves if we move the task from the GPU to the CPU so that building and tracing are done in parallel rather than sequentially on the faster processor. <em>NB: Several of these claims require experimental validation.</em></p>



<h3 class="wp-block-heading">Bring Your Own Math Library</h3>



<p class="wp-block-paragraph">Vector math inside TinyBVH is handled by a small set of structs, and a minimal set of operators. These can be found in <code>tiny_bvh_base.h</code>, starting on line 63:</p>



<ul class="wp-block-list">
<li>bvhvevc2/3/4</li>



<li>bvhint2/3</li>



<li>bvhuint2</li>



<li>bvhaabb</li>



<li>bvhdbl3</li>
</ul>



<p class="wp-block-paragraph">These structs only exist to avoid dependency on an external math library. However, applications using TinyBVH probably already use their own math classes, e.g. <a href="https://github.com/PX4/eigen">Eigen</a> or <a href="https://github.com/g-truc/glm">glm</a>. The included structs (with uncommon names) aim to avoid collisions.</p>



<p class="wp-block-paragraph">Additionally, it is possible to use your preferred math library. For this, simply define <code>TINYBVH_USE_CUSTOM_VECTOR_TYPES</code> before including <code>tiny_bvh.h</code>, and inform TinyBVH about your types, e.g.:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">namespace tinybvh
{
   using bvhint2 = math::int2;
   using bvhint3 = math::int3;
   using bvhuint2 = math::uint2;
   using bvhvec2 = math::float2;
   using bvhvec3 = math::float3;
   using bvhvec4 = math::float4;
   using bvhdbl3 = math::double3;
}</pre></div>



<p class="wp-block-paragraph">From here on, TinyBVH will now use your math library. Two notes:</p>



<ol class="wp-block-list">
<li>The float3 / bvhvec3 type <span style="text-decoration: underline;">must</span> be 12 bytes in size (do not pad to 16 bytes).</li>



<li>The unconventional double vector type is not needed if double precision functionality is disabled (see the section on double precision and/or settings).</li>
</ol>



<h3 class="wp-block-heading">Double Precision</h3>



<p class="wp-block-paragraph">In some exceptional situations a scene may require double precision numbers. For this, TinyBVH offers a double precision BVH layout, in which every floating point number is stored (and processed) as a 64-bit value, greatly extending the range and precision.</p>



<p class="wp-block-paragraph">A double precision BVH is constructed like a regular one:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVH_Double bvh;
bvh.Build( (bvhdbl3)triangles, TRIANGLE_COUNT );</pre></div>



<p class="wp-block-paragraph">Note that the input triangles are specified here with three doubles &#8211; not four; the BVH will not be constructed with SIMD code and does not have the data alignment restriction of the regular BVH.</p>



<p class="wp-block-paragraph">A double-precision BVH is intersected with a double-precision ray. The struct for this is <code>tinybvh::RayEx</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">RayEx ray( O, D );
bvh.Intersect( ray );</pre></div>



<p class="wp-block-paragraph">The ray origin and direction in <code>RayEx</code> are specified as double precision values.</p>



<p class="wp-block-paragraph">To build a TLAS over double-precision BVHs, use the <code>InstanceEx</code> struct. Other than this, TLAS construction is the same as with regular BVHs. And, like regular BVHs, a double-precision BVH can be constructed over custom primitives. </p>



<p class="wp-block-paragraph">The double-precision functionality is demonstrated in the <code>tiny_bvh_instancing_double.cpp</code> example.</p>



<h3 class="wp-block-heading">Memory Management</h3>



<p class="wp-block-paragraph">The construction of a BVH requires several buffers:</p>



<ul class="wp-block-list">
<li>A fragment buffer, which contains the AABBs for the primitives</li>



<li>A list of BVH nodes</li>



<li>A list of primitive indices, used to efficiently sort primitives during conversion</li>
</ul>



<p class="wp-block-paragraph">Depending on the BVH layout, additional buffers may be needed.</p>



<p class="wp-block-paragraph">Some applications may require that allocation and de-allocation is handled by a custom memory manager. This is supported by TinyBVH via the <code>BVHContext</code>, which can be passed to the default constructors of all BVH layouts. By default, this struct contains two function pointers:</p>



<ul class="wp-block-list">
<li>One to <code>malloc64</code>, which allocates memory aligned to a cache line boundary, </li>



<li>And <code>free64</code>, which frees memory allocated by <code>malloc64</code>.</li>
</ul>



<p class="wp-block-paragraph">TinyBVH exclusively uses these two function pointers to allocate and de-allocate memory. Override these function pointers to use your own functions.</p>



<h3 class="wp-block-heading">Custom Geometry</h3>



<p class="wp-block-paragraph">The standard primitive type in TinyBVH is the triangle. In cases where other primitives are required, these can be added as <em>custom geometry</em>. In this case, the application must implement three callback functions:</p>



<ol class="wp-block-list">
<li>A function that calculates the AABB for a given primitive</li>



<li>A function that intersects a ray with a primitive</li>



<li>A function that detects a hit between a ray and a primitive. </li>
</ol>



<p class="wp-block-paragraph">A pointer to the first function must be supplied to <code>BVH::Build()</code> when the BVH is constructed. The other two must be set by overwriting the <code>customIntersect</code> and <code>customIsOccluded</code> fields of the BVH instance.</p>



<p class="wp-block-paragraph">Note that a BVH can only support a single primitive type. To construct a scene of spheres and triangles for instance, one BVH should be constructed for the spheres, and one for the triangles. These can then be combined under a TLAS.</p>



<p class="wp-block-paragraph">The custom geometry functionality is available both in regular BVHs and double-precision BVHs and is demonstrated in detail in <code>tiny_bvh_custom.cpp</code> and <code>tiny_bvh_custom_double.cpp</code>.</p>



<h3 class="wp-block-heading">BVH versus Sphere</h3>



<p class="wp-block-paragraph">Although the BVH functionality of TinyBVH focuses on ray tracing, a single physics-oriented operation is provided, which determines whether a BVH collides with a sphere:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bool hit = bvh.IntersectSphere( position, radius );</pre></div>



<p class="wp-block-paragraph">Here <code>position</code> is a three-component vector, and <code>radius</code> is a float. A double-precision version is currently not available, and the operation is currently only implemented for the default BVH layout.</p>



<p class="wp-block-paragraph">It is worth noting that if you constructed a different layout, e.g. <code>BVH4_CPU</code>, the underlying default <code>BVH</code> layout remains accessible, via the <code>.bvh</code> field of the derived layout:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVH4_CPU bvh4;
bvh4.Build( triangles, TRIANGLE_COUNT );
bool hit = bvh4.bvh.IntersectSphere( position, radius );</pre></div>



<p class="wp-block-paragraph">Here, the efficient <code>BVH4_CPU</code> is used for ray tracing, while the original <code>BVH</code> that the <code>BVH4_CPU</code> was converted from is used for the sphere intersection.</p>



<h3 class="wp-block-heading">Settings</h3>



<p class="wp-block-paragraph">Various defines are used in TinyBVH to fine-tune desired functionality and performance. You can set these before including <code>tiny_bvh.h</code> in your application to override defaults.</p>



<ul class="wp-block-list">
<li><code>C_INT</code>, <code>C_TRAV</code> : These values affect BVH construction. During construction the cost of intersecting a ray with a node is minimized using the SAH heuristic. This requires knowledge about the cost of traversing a node (<code>C_TRAV</code>) or intersecting a primitive (<code>C_INT</code>). Tweaking these values may improve ray tracing performance on a specific CPU or GPU or for primitives with custom intersection code.</li>



<li><code>HQBVHBINS</code> : Like the regular BVH builder, the SBVH builder uses a fixed set of discrete intervals to evaluate the &#8216;Surface Area Heuristic&#8217; (SAH). A good tree is produced even with a modest number of intervals, but quality may improve somewhat with more intervals. The default is 8; values of 16 or even 32 may yield a (small) improvement of BVH quality, although this will increase build time.</li>



<li><code>INST_IDX_BITS</code> : This value defaults to 32, which forces TinyBVH to use a full 32-bit value to store the instance index of an intersection of a ray with a TLAS. Reducing this value to e.g. 10 allows TinyBVH to combine the instance index with the primitive index, reducing the intersection data to 16 bytes. This is faster, but 10 bits means that only 1024 instances can be used, while the remaining 22 bits can index only 4 million triangles.</li>



<li><code>NO_DOUBLE_PRECISION_SUPPORT</code> : If defined, the double-precision BVH layout <code>BVH_Double</code> becomes unavaible, along with the double-precision vector type <code>bvhdbl3</code>. The main benefit of this is that a custom math library does not need to override <code>bvhdbl3</code>.</li>



<li><code>NO_INDEXED_GEOMETRY</code> : If defined, indexed vertices will not be available for BVH construction. This potentially slightly improves ray tracing performance, as the ray/triangle code otherwise must use an if-statement to determine the presence of indices. This effect should be limited for scenes that exclusively use either indexed or non-indexed geometry. </li>



<li><code>NO_CUSTOM_GEOMETRY</code> : If defined, custom primitive intersection via callbacks is disabled. Like <code>NO_INDEXED_GEOMETRY</code> this reduces or eliminates conditional code during intersection.</li>



<li><code>TINYBVH_USE_CUSTOM_VECTOR_TYPES</code> : If this is defined, TinyBVH will not use its own vector types; instead it will assume you define these. See the relevant section earlier in this document.</li>



<li><code>TINYBVH_NO_SIMD</code> : TinyBVH will use SIMD via AVX or NEON on CPUs that support this. If you prefer the library without SIMD support, you can use this define.</li>
</ul>



<h2 class="wp-block-heading">And Finally&#8230;</h2>



<p class="wp-block-paragraph">This concludes the &#8216;Advanced&#8217; section of the TinyBVH manual.</p>



<p class="wp-block-paragraph">Please take some time to explore the examples that come with the TinyBVH distribution. These may demonstrate topics omitted in these articles. Also feel free to reach out in case of questions. If your project is using TinyBVH I would especially like to hear from you! </p>



<p class="wp-block-paragraph">Questions? Comments? Mail me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a> or follow me on Bluesky: @jbikker.bsky.social.</p>



<p class="wp-block-paragraph">Manual index:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2025/01/24/tinybvh-manual-basic-use/">Basic Use. Building a BVH, tracing a ray, alternative layouts, TLAS/BLAS</a>.</li>



<li><strong>Advanced Topics (this document).</strong> GPU ray tracing, custom math libraries, TinyBVH settings.</li>
</ol>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2025/01/25/tinybvh-manual-advanced/feed/</wfw:commentRss>
			<slash:comments>13</slash:comments>
		
		
			</item>
		<item>
		<title>TinyBVH &#8211; Manual &#8211; Basic Use</title>
		<link>https://jacco.ompf2.com/2025/01/24/tinybvh-manual-basic-use/</link>
					<comments>https://jacco.ompf2.com/2025/01/24/tinybvh-manual-basic-use/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Fri, 24 Jan 2025 12:57:40 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=2241</guid>

					<description><![CDATA[This document describes the TinyBVH header-only library for Bounding Volume Hierarchy construction and traversal, with a focus...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This document describes the TinyBVH header-only library for Bounding Volume Hierarchy construction and traversal, with a focus on ray tracing on CPU and GPU &#8211; to be used for graphics, audio or physics.</p>



<p class="wp-block-paragraph"><em>This document is currently in sync with TinyBVH version 1.9.0.</em></p>



<p class="wp-block-paragraph">TinyBVH is open source (MIT license) and <a href="https://github.com/jbikker/tinybvh">available on GitHub</a>.</p>



<p class="wp-block-paragraph">The manual is split into multiple compact documents:</p>



<ol class="wp-block-list">
<li><strong>Basic Use (this document).</strong> Building a BVH, tracing a ray, alternative layouts, TLAS/BLAS.</li>



<li><a href="https://jacco.ompf2.com/2025/01/25/tinybvh-manual-advanced/">Advanced Topics. GPU ray tracing, custom math libraries, TinyBVH settings</a>.</li>
</ol>



<h3 class="wp-block-heading">Introduction</h3>



<p class="wp-block-paragraph">High-quality acceleration structure construction is <a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">non-trivial</a>. A good BVH lets you trace hundreds of millions of rays per second on a modest CPU and billions of rays per second on a high-end GPU. It does this by hierarchically subdividing the scene; a ray can then efficiently cull large groups of primitives if it does not hit the bounding volume of those primitives.</p>



<p class="wp-block-paragraph">This is also the core functionality of NVIDIA&#8217;s <a href="https://en.wikipedia.org/wiki/Nvidia_RTX">RTX</a>, Microsoft&#8217;s <a href="https://en.wikipedia.org/wiki/DirectX_Raytracing">DXR</a> and Intel and AMD&#8217;s ray tracing hardware. On the CPU, similar functionality is available in the form of Intel&#8217;s <a href="https://www.embree.org/">Embree</a> and Madmann91&#8217;s <a href="https://github.com/madmann91/bvh">BVH library</a>.</p>



<p class="wp-block-paragraph">So, TinyBVH arrives in a crowded space, but it does bring some specific characteristics and ambitions.</p>



<ul class="wp-block-list">
<li>For GPU, it aims to offer competitive ray tracing performance outside Vulkan, DirectX and CUDA. TinyBVH comes with example code for OpenCL, OpenGL compute, Vulkan and DirectX12. TinyBVH is already enabling fast ray tracing in <a href="https://threejsresources.com/tool/webgpu-raytracer">WebGPU</a>.</li>



<li>For CPU, it aims to offer a more accessible and compact framework than the awesome but complex Embree library.</li>



<li>TinyBVH is a header-only library written in &#8216;sane C++&#8217; and it comes with <em>no dependencies</em>. That means that adding tinybvh is simple: just include <code>tiny_bvh.h</code>.</li>



<li>TinyBVH is fast. In fact: TinyBVH offers state-of-the-art performance for CPU ray tracing, both for construction and traversal &#8211; outperforming Embree.</li>



<li>TinyBVH is cross-platform. This goes well beyond &#8216;it works&#8217;: Most SIMD builders and ray tracing kernels have specialized Intel AVX as well as ARM NEON implementations for peak performance on both architectures.</li>



<li>TinyBVH is simple to use. Despite the technical details listed above, anyone can trace a ray using TinyBVH, with just a few lines of code. Either in C/C++, <a href="https://github.com/FlorentLM/pytinybvh">Python</a>, <a href="https://github.com/andersforsgren/TinyBVHNet">.NET</a>, or <a href="https://docs.rs/tinybvh-rs/latest/tinybvh_rs/">Rust</a>, should you so desire.</li>
</ul>



<p class="wp-block-paragraph">This manual describes basic use of TinyBVH. It frequently references example code included with TinyBVH, which can be compiled on Windows, Linux and macOS.</p>



<h3 class="wp-block-heading">Basic Use</h3>



<p class="wp-block-paragraph">A basic example using the library can be found in <code>tiny_bvh_minimal.cpp</code>. The library is added to the file  with an include:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#define TINYBVH_IMPLEMENTATION
#include "tiny_bvh.h"</pre></div>



<p class="wp-block-paragraph">The define before the include tells TinyBVH that this file needs the interface as well as the implementation. Other files can also include <code>tiny_bvh.h</code>, but only one C/C++ file should use the <code>TINYBVH_IMPLEMENTATION</code> define.</p>



<p class="wp-block-paragraph">Now we can simply instantiate an empty bvh:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tinybvh::BVH bvh;</pre></div>



<p class="wp-block-paragraph">Next, we feed it some triangles:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bvh.Build( triangles, TRIANGLE_COUNT );</pre></div>



<p class="wp-block-paragraph">Here, &#8216;triangles&#8217; is a list of vertices: three for each triangle. Each vertex is specified as a 16-byte &#8216;float4&#8217; value, of which only 12 bytes are used for x, y and z. The reason for this &#8216;waste&#8217; is performance: For most CPUs, 16-byte vertices are faster to operate on.</p>



<p class="wp-block-paragraph">With the BVH constructed, we can use it to fire rays:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tinybvh::Ray ray( O, D );
bvh.Intersect( ray );</pre></div>



<p class="wp-block-paragraph">The result of this operation can be found in <code>ray.hit</code>. This has a couple of fields:</p>



<ul class="wp-block-list">
<li><code>ray.hit.t</code>: This is the intersection distance. If the ray hit nothing, this will be 1e30f (<code>BVH_FAR</code>). You can turn the intersection distance into an intersection location with the formula <code>P = ray.O + ray.hit.t * ray.D</code>.</li>



<li><code>ray.hit.prim</code>: This is the index of the triangle that was hit. You can find the vertices of this triangle in the array that was passed to <code>bvh.Build</code>. Note that ownership of this array remains yours; TinyBVH just borrowed it for the construction and traversal of the BVH.</li>



<li><code>ray.hit.u</code> and <code>ray.hit.v</code>: These are the barycentric coordinates of the hit point on the triangle. These can be used to interpolate normals and textures.</li>
</ul>



<p class="wp-block-paragraph">Sometimes you don&#8217;t need all this information; perhaps you simply want to know if a ray can go from A to B unobstructed. This could be implemented with <code>bvh.Intersect</code>, but there is a better way:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tinybvh::Ray ray( O, D, 100 );
bool hit = bvh.IsOccluded( ray );</pre></div>



<p class="wp-block-paragraph">Note that the ray this time has a <em>length</em>: &#8216;hit&#8217; will only be true if an obstacle is found between point <code>O</code> and a point along the ray, at a distance that is smaller than 100 <em>(assuming D is a normalized vector)</em>.</p>



<p class="wp-block-paragraph">The distinction between the two <em>ray queries</em> is important, because a <em>shadow ray</em> is generally faster (about 30%) than the more generic ray query.</p>



<p class="wp-block-paragraph">These are the basics. From here:</p>



<ul class="wp-block-list">
<li>Trace millions of rays. This is what TinyBVH is made for. You can also trace rays from multiple threads.</li>



<li>Change the vertex positions and rebuild the BVH. Just call <code>bvh.Build</code> each time you change something.  </li>
</ul>



<p class="wp-block-paragraph">That is probably all you need. The remainder of this manual discusses alternative BVH layouts with a different balance between construction speed and ray tracing speed, alternative geometry representations, using the BVH on the GPU and more.</p>



<h3 class="wp-block-heading">Steering Construction</h3>



<p class="wp-block-paragraph">The BVH builder that is invoked with a call to <code>bvh.Build</code> is the default builder. This is a multi-threaded <em>binning SAH BVH</em> builder, using AVX2 or ARM NEON if available, capable of processing ~200k triangles in less than 10ms.</p>



<p class="wp-block-paragraph">When the default builder is not what you are looking for, you can override it through <code>BVHBase::settings</code>. In <code>tiny_bvh_base.h</code> you can find the available options and their defaults:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">struct BVHBuildSettings
{
	bool usePresplitting = false;	// pre-split triangles before building the BVH.
	bool useSpatialSplits = false;	// consider spatial splits during construction (SBVH).
	bool presplitPostPass = true;	// attempt to un-split primitives in leaves after a presplit build.
	float presplitFactor = 0.3f;	// presplit budget relative to input data size.
	bool useFullSweep = false;	// for experiments only; full-sweep SAH builder.
	bool postOptimize = false;	// optimize generated BVH using tree rotations.
	int optimizeIterations = 25;	// default optimization iterations.
	bool useSIMDifavailable = true;	// set to false to use the scalar reference builder.
};</pre></div>



<p class="wp-block-paragraph">A higher-quality BVH (at the expense of build time) can be obtained by enabling <code>useSpatialSplits</code>, and/or <code>postOptimize</code>. Together, these options may yield up to 30% better traversal speed. However, be aware of some drawbacks:</p>



<ul class="wp-block-list">
<li>An SBVH will use slightly more memory (about 15%).</li>



<li>Because of the unpredictable memory use, an SBVH currently cannot be <em>rebuilt</em>.</li>



<li>Because of triangle cutting in the algorithm, an SBVH also cannot be <em>refitted</em>.</li>
</ul>



<p class="wp-block-paragraph">Generally speaking, a high-quality BVH is suitable for static geometry.</p>



<h3 class="wp-block-heading">Alternative Layouts</h3>



<p class="wp-block-paragraph">In <code>tiny_bvh.h</code> you will find several alternative BVH layouts. One of them is <code>BVH4_CPU</code>. To construct a BVH in this layout, simply instantiate and build it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVH4_CPU bvh;
bvh.Build( triangles, TRIANGLE_COUNT );</pre></div>



<p class="wp-block-paragraph">Internally, this builds a regular BVH, and converts it to a format that is easier for a modern CPU to digest. This results in faster ray tracing performance: You can expect about 3.5× more rays per second when using <code>BVH4_CPU</code>, so the impact is substantial. And, it can be combined with the spatial splits discussed earlier for even better speed.</p>



<p class="wp-block-paragraph">Some drawbacks to consider:</p>



<ul class="wp-block-list">
<li>Conversion is not an expensive step, but it does take time. Do not use <code>BVH4_CPU</code> if you have just a few rays to trace, or when you need to rebuild the BVH per frame.</li>



<li>The conversion does not destroy the original BVH. Effectively, you are now using twice the memory. It would not be impossible to change this (especially not for <code>BVH4_CPU</code>s that you do not intend to rebuild) but for the moment, this is something to keep in mind.</li>



<li><code>BVH4_CPU</code> traversal requires an AVX2-capable processor (x86-64), or an ARM NEON compatible processor (macOS, Raspberry Pi). It is thus broadly supported, but not fully cross-platform. A scalar fallback path is available, but it may be slower than the default BVH format.</li>
</ul>



<p class="wp-block-paragraph">Several other BVH formats exist, each with specific characteristics:</p>



<ul class="wp-block-list">
<li><code>BVH8_CPU</code>: an 8-wide BVH, which used to be the fastest option but was recently defeated by <code>BVH4_CPU</code>. Left in for reference and experiments.</li>



<li><code>BVH_GPU</code>: a BVH format suitable for traversal on a GPU.</li>



<li><code>BVH4_GPU</code>, <code>BVH8_CWBVH</code>: Specialized GPU BVH formats.</li>



<li><code>BVH_Verbose</code>: An internal format, used for operations like BVH optimization.</li>



<li><code>MBVH</code>: Also an internal format, used during construction of 4-wide and 8-wide formats.</li>
</ul>



<p class="wp-block-paragraph">A final &#8216;BVH format&#8217; (derived from <code>BVHBase</code>) is <code>VoxelSet</code>. This one is a bit out of place in TinyBVH, but for some projects it may be useful to have.</p>



<h3 class="wp-block-heading">Animation: Refitting</h3>



<p class="wp-block-paragraph">To trace rays in dynamic scenes, the most obvious option is to rebuild the BVH each frame. However, even for moderately complex scenes this does not allow for smooth frame rates.</p>



<p class="wp-block-paragraph">Luckily, a full rebuild is rarely needed. We have two alternatives:</p>



<ul class="wp-block-list">
<li>Often a BVH can be <em>refitted</em> rather than rebuilt.</li>



<li>Often large parts of a scene do not require an update.</li>
</ul>



<p class="wp-block-paragraph">Refitting is based on the observation that if the frames of an animated mesh are very similar, the BVH that we would rebuild each frame will also be similar. This is the case for example for trees that sway in the wind, or a water surface with gentle waves. In that case we can simply re-use a BVH and <em>refit</em> it around the changed geometry. This is a matter of updating bounding volumes, which is a lot more efficient than a full rebuild.</p>



<p class="wp-block-paragraph">To refit a BVH, simply call the <code>Refit</code> method:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bvh.Refit();</pre></div>



<p class="wp-block-paragraph">This will use the triangle array pointer that you passed during construction. That means that the <em>size </em>of the list of triangles cannot change. Triangles should also not have changed position in the array; refitting really is only for changes to vertex positions. When these conditions apply, refitting is very fast: A BVH for 200k triangles is refitted in less than a millisecond.</p>



<p class="wp-block-paragraph">Refitting does not help all scenes. To exploit the fact that most geometry in a scene is static, we build not one BVH, but several. This is discussed in the next section.</p>



<h3 class="wp-block-heading">Animation: TLAS</h3>



<p class="wp-block-paragraph">Example program <code>tiny_bvh_instancing.cpp</code> demonstrates the concept of the <em>top level acceleration structure</em>. In this example several BVHs are constructed:</p>



<ul class="wp-block-list">
<li>One for the static geometry of the Crytek Sponza scene (~262k triangles)</li>



<li>One for a Stanford Bunny object.</li>
</ul>



<p class="wp-block-paragraph">The example demonstrates <em>instancing</em>: The bunny object is replicated in a 2×2×2 grid. For this an array of 9 <em>instances</em> is used, eight for the bunnies and one for Sponza:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">BVH sponza;
BVH obj;
BVH tlas;
BVHBase* bvhList[] = { &amp;sponza, &amp;obj };
BLASInstance inst[INSTCOUNT + 1 /* one extra for sponza */];</pre></div>



<p class="wp-block-paragraph">For each instance a 4×4 matrix transform is set. After that on line 118 the TLAS is constructed:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">tlas.Build( inst, 1 + INSTCOUNT, bvhList, 2 );</pre></div>



<p class="wp-block-paragraph">We can now intersect the TLAS as if it were a regular BVH (line 156, 157):</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray ray( eye, D );
tlas.Intersect( ray );</pre></div>



<p class="wp-block-paragraph">The result is almost the same as intersecting a regular BVH. There is one difference: <code>ray.hit.prim</code> this time also holds the <em>instance index</em> of the object that was hit. This is important, because triangle 1000 in Sponza is not the same as triangle 1000 in the bunny, and: Each individual bunny now has a model transform&#8230; This lets us intersect the <em>same </em>BVH multiple times, to paste the mesh in multiple locations (and if you wish, in multiple orientations).</p>



<p class="wp-block-paragraph">The TLAS is a powerful tool. Take for example a racing game with 10M static triangles for the race track, plus 10 cars, each with a body mesh and 4 tire meshes:</p>



<ul class="wp-block-list">
<li>We calculate the BVH for the track once, at the highest possible quality.</li>



<li>We calculate a BVH for the race car body and duplicate it 10 times, so we can change individual copies later.</li>



<li>We calculate a BVH for a tire and replicate it 40 times, 4 times per car.</li>



<li>To animate the cars, we change their transforms and rebuild the TLAS each frame.</li>



<li>If a car gets damaged, we refit the changed model.</li>
</ul>



<p class="wp-block-paragraph">None of these operations involve a BVH rebuild, except for the TLAS. Constructing the TLAS for 51 objects will take far less than a millisecond. We now have a fully dynamic scene ready to be ray traced.</p>



<p class="wp-block-paragraph">Note that the BVHs (referred to as <em>BLASes</em>) referenced by the TLAS can be of any type. One BLAS may be best described using a <code>BVH4_CPU</code> constructed with spatial splits (e.g. large static geometry), while another is actually a regular BVH because it needs frequent rebuilds. And, a <code>VoxelSet</code> object can also be placed under a TLAS, for a different kind of scene.</p>



<h2 class="wp-block-heading">And Finally&#8230;</h2>



<p class="wp-block-paragraph">This concludes the &#8216;Basic Use&#8217; section of the TinyBVH manual. See the index below for easy access to the <strong>Advanced Topics</strong> manual.</p>



<p class="wp-block-paragraph">Questions? Comments? Mail me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a> or follow me on Bluesky: @jbikker.bsky.social.</p>



<p class="wp-block-paragraph">Manual index:</p>



<ol class="wp-block-list">
<li><strong>Basic Use (this document).</strong> Building a BVH, tracing a ray, alternative layouts, TLAS/BLAS.</li>



<li><a href="https://jacco.ompf2.com/2025/01/25/tinybvh-manual-advanced/">Advanced Topics. GPU ray tracing, custom math libraries, TinyBVH settings</a>.</li>
</ol>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2025/01/24/tinybvh-manual-basic-use/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 6</title>
		<link>https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/</link>
					<comments>https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 29 May 2024 09:08:23 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=2046</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1887">Converging under movement: Reprojection</a>.</li>



<li><strong>Path tracing: Basics first; then: Importance Sampling (this article).</strong></li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">After all the noise and noise suppression techniques it is time to move forward and improve the visual fidelity of the renderer. We will do so using probably the most beautiful algorithm in computer graphics: <em>Path Tracing</em>. The core &#8216;ground truth&#8217; algorithm turns out to be surprisingly simple &#8211; and stunningly close to the &#8220;God Algorithm&#8221;: Light transport (via photons) in the Real World. </p>



<p class="wp-block-paragraph">At the end of this episode an extension to the basic path tracing implementation is introduced that improves its efficiency, while still producing an image identical to &#8216;ground truth&#8217;.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">We start with a new scene: The &#8220;Floating Island of the Potion Brewer&#8221;, converted from a Sketchfab model by author <a href="https://sketchfab.com/vilmariina">Vilmariina</a>. The scene is 256x256x256 voxels, so, in <code>scene.h</code>, set <code>WORLDSIZE</code> to 256. Then, load the scene using the following code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    grid = (uint*)MALLOC64( GRIDSIZE3 * sizeof( uint ) );
    gzFile f = gzopen( "assets/floating256.bin", "rb" );
    gzread( f, grid, sizeof( int3 ) );
    gzread( f, grid, GRIDSIZE3 * sizeof( uint ) );
    gzclose( f );
}</pre></div>



<p class="wp-block-paragraph">Next, replace <code>Renderer::Trace</code> (in <code>renderer.cpp</code>) by something simple:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int, int, int depth )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 1.2f, 1.2f, 1.0f );
    return ray.albedo;
}</pre></div>



<p class="wp-block-paragraph">That&#8217;s it, we&#8217;re all set. </p>



<h2 class="wp-block-heading">Cheese</h2>



<p class="wp-block-paragraph">This time, we&#8217;re going to dive right in and start with the &#8216;finished product&#8217;. Run the code and find a camera view similar to the shot shown below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="661" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-1024x661.jpg" alt="" class="wp-image-2112" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-1024x661.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-300x194.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-768x496.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-897x579.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1-360x232.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viewfind-1.jpg 1214w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 1: A good viewpoint to enjoy the scene.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Next, add the accumulator from Episode 3. Either <a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">go there</a> for detailed instructions, or copy/paste the shortified code below, replacing <code>Renderer::Init</code> and <code>Renderer::Tick</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Init()
{
    accumulator = new float3[SCRWIDTH * SCRHEIGHT];
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Tick( float deltaTime )
{
    static int spp = 1;
    const float scale = 1.0f / spp++;
#pragma omp parallel for schedule(dynamic)
    for (int y = 0; y &lt; SCRHEIGHT; y++) for (int x = 0; x &lt; SCRWIDTH; x++)
    {
        Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
        accumulator[x + y * SCRWIDTH] += Trace( r );
        float3 average = accumulator[x + y * SCRWIDTH] * scale;
        screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( average );
    }
    if (!camera.HandleInput( deltaTime )) return; else spp = 1;
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<p class="wp-block-paragraph">And finally, replace <code>Renderer::Trace</code> by the following magical code snippet.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int, int, int depth )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 1.2f, 1.2f, 1.0f );
    if (depth == 4) return float3( 0 );
    float3 N = ray.GetNormal(), I = ray.IntersectionPoint();
    float3 R = diffuseReflection( N );
    float3 brdf = ray.GetAlbedo() / PI;
    float pdf = 1.0f / TWOPI;
    float3 indirect = Trace( Ray( I, R ), 0, 0, depth + 1 ); 
    return brdf * indirect * (dot( N, R ) / pdf);
}</pre></div>



<p class="wp-block-paragraph">Now run <em>this.</em> The output is breath-taking:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" width="1024" height="662" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-1024x662.jpg" alt="" class="wp-image-2121" style="width:600px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-1024x662.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-300x194.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-768x496.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-897x580.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2-360x233.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/magic-2.jpg 1216w" sizes="(max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 2: Path-traced render of the scene.</figcaption></figure>
</div>


<p class="wp-block-paragraph">In fact, your output may be darker than that but this is easily resolved by modifying variable <code>average</code> before plotting it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">average.x = sqrtf( average.x );
average.y = sqrtf( average.y );
average.z = sqrtf( average.z );</pre></div>



<p class="wp-block-paragraph">The purpose of these three lines is <em><a href="https://www.cambridgeincolour.com/tutorials/gamma-correction.htm">gamma correction</a></em>. The renderer is producing correct values in &#8216;linear color space&#8217;, i.e.: Doubling a value makes it exactly twice as bright. The average monitor or laptop screen however uses a different curve, which isn&#8217;t linear at all: a relative large change is needed to make a dark pixel somewhat brighter. The square root counters this, so that the color gradients on the screen look natural. </p>



<p class="has-drop-cap has-white-color has-pale-cyan-blue-background-color has-text-color has-background has-link-color wp-elements-2 wp-block-paragraph" style="font-style:italic;font-weight:400">Gamma is useful by the way, because our eyes have a similar curve in sensitivity: We can detect smaller differences between dark colors than between bright colors. Having more values in the low regions thus accommodates the human visual system. Just like the red/green/blue color blending: The <a href="https://askabiologist.asu.edu/rods-and-cones">rods and cones</a> in our eyes that detect light happen to be sensitive to exactly those colors.  </p>



<p class="wp-block-paragraph">Looking at the path traced image in Figure 2, we see subtle soft shadows, subtle darkening near voxels, light inside the buildings, and an overall <em>natural</em> appearance of the illumination. But, there are no lights&#8230; So, how does this work?</p>



<h2 class="wp-block-heading">God&#8217;s Algorithm</h2>



<p class="wp-block-paragraph">Light energy in nature travels from light sources to sensors (eyes, cameras) in the form of photons. Photon behavior is really simple: A photon travels in a straight line (unless close to a black hole, but lets ignore that here), and when it hits something, it gets absorbed, or it changes direction.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img decoding="async" width="446" height="342" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/room.jpg" alt="" class="wp-image-2131" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/room.jpg 446w, https://jacco.ompf2.com/wp-content/uploads/2024/05/room-300x230.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/room-360x276.jpg 360w" sizes="(max-width: 446px) 100vw, 446px" /><figcaption class="wp-element-caption">Figure 3: God&#8217;s algorithm in a student room. The lightbulb emits <span class="wp-katex-eq" data-display="false">10^{20}</span> photons per second, but the behavior of each photon is simple.</figcaption></figure>
</div>


<p class="wp-block-paragraph">We can simulate that behavior for physically-based, photo-realistic images. And that is precisely the basis of the path tracing algorithm. Look at this line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 indirect = Trace( Ray( I, R ), 0, 0, depth + 1 );</pre></div>



<p class="wp-block-paragraph">That&#8217;s a recursive call to the <code>Renderer::Trace</code> function. So, at the end of the Trace function, a new ray is generated, and whatever indirect light it brings back is what the primary ray returns to the <code>Tick</code> function. The bouncing rays together form a path, which ends at a specific length (four, in this case) or when a light is found.</p>



<p class="wp-block-paragraph">So this does replicate photon behavior, and quite successfully, judging from the outcome. One thing is strange though: The path is formed in the <em>reversed</em> direction; i.e. from the camera to the lights. It turns out that this is fine: A physics rule named the <a href="https://en.wikipedia.org/wiki/Helmholtz_reciprocity">Helmholtz reciprocity principle</a> states that source and observation point can be swapped without affecting the outcome. The great benefit of the reversed path is that we now effectively ignore all the photon paths that do not connect to the camera.</p>



<h2 class="wp-block-heading">Pi, pdf etc.</h2>



<p class="wp-block-paragraph">Let&#8217;s reformulate the base algorithm a bit to understand it better:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int, int, int )
{
    float3 throughput( 1, 1, 1 );
    for( int bounce = 0; bounce &lt; 4; bounce++ )
    {
        // find nearest surface
        scene.FindNearest( ray );
        if (ray.voxel == 0) 
        {
            // path found the sky
            return throughput * float3( 1.2f, 1.2f, 1.0f );
        }
        // get surface interaction data
        float3 N = ray.GetNormal(), I = ray.IntersectionPoint();
        float3 brdf = ray.GetAlbedo() / PI;
        // generate new path segment
        float3 R = diffuseReflection( N );
        float pdf = 1.0f / TWOPI;
        throughput *= brdf * (dot( N, R ) / pdf);
        ray = Ray( I, R );
    }
    return { 0 }; // path too long
}</pre></div>



<p class="wp-block-paragraph">Functionally nothing changed here. That being said: The function now no longer uses recursion; instead, a simple loop keeps track of the bounces. The amount of light the path transports from the sky to the camera is kept track of using variable <code>throughput</code>.</p>



<p class="wp-block-paragraph">At each surface that the path visits, the throughput is changed using three values, which we will discuss in more detail.</p>



<ol class="wp-block-list">
<li>The material color, or more precisely: the BRDF;</li>



<li>A &#8216;probability density function&#8217; PDF;</li>



<li>A dot product between the surface normal <span class="wp-katex-eq" data-display="false">N</span> and the new ray direction <span class="wp-katex-eq" data-display="false">R</span>.</li>
</ol>



<p class="wp-block-paragraph">All of these are vital for the correctness of the simulation.</p>



<h2 class="wp-block-heading">BRDF</h2>



<p class="wp-block-paragraph">All materials (even the super-dark <a href="https://www.surreynanosystems.com/about/vantablack">Vantablack</a>) reflect light. The amount of reflected light and the direction of the reflection depends on the specific material. If you look into a bathroom mirror for example, the reflected light is (almost) the same as the incoming light, and the direction of the reflection is very specific. A sheet of red paper on the other hand does reflect, but mostly the red part of the visible spectrum; other colors are absorbed. And, the direction of the outgoing light is pretty much random for such a material.</p>



<p class="wp-block-paragraph">The reflection properties of a material can be described using a BRDF, the <em>Bidirectional Reflection Distribution Function</em>. For a given incoming and outgoing direction, the BRDF describes how much light is reflected. For a mirror, the BRDF describes that all light for a specific incoming direction leaves into a single outgoing direction. But for a diffuse material, like paper, it states that any incoming direction can be coupled to any outgoing direction.</p>



<p class="wp-block-paragraph">The BRDF in the above code snippet is formulated as <code>ray.GetAlbedo() / PI</code>. With that formula, there is no dependency on incoming and outgoing directions; the only thing that matters is absorption. The division by <span class="wp-katex-eq" data-display="false">\pi</span> is needed <a href="https://sakibsaikia.github.io/graphics/2019/09/10/Deriving-Lambertian-BRDF-From-First-Principles.html">for reasons</a> beyond the scope of this article.</p>



<p class="wp-block-paragraph">The random scattering itself is implemented in function <code>diffuseReflection</code>, which you can find in <code>tmpl8math.h</code>. It reads:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">inline float3 diffuseReflection( const float3&amp; N )
{
    float3 R;
    do
    {
        R = make_float3( RandomFloat(), RandomFloat(), RandomFloat() ) * 2 - 1;
    } while (dot( R, R ) &gt; 1);
    return normalize( dot( R, N ) &lt; 0 ? -R : R );
}</pre></div>



<p class="wp-block-paragraph">The purpose of this function is to generate a random new direction that does not travel into the surface with normal <span class="wp-katex-eq" data-display="false">N</span>. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="790" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-1024x790.jpg" alt="" class="wp-image-2140" style="width:400px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-1024x790.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-300x231.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-768x592.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-897x692.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl-360x278.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/diffrefl.jpg 1058w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 4: Generating a random bounce in the surface defined by normal <span class="wp-katex-eq" data-display="false">N</span>.</figcaption></figure>
</div>


<p class="wp-block-paragraph">In 2D, to generate a &#8216;random bounce&#8217; we first generate a random vector with <span class="wp-katex-eq" data-display="false">x</span>, <span class="wp-katex-eq" data-display="false">y</span> and <span class="wp-katex-eq" data-display="false">z</span> in the range of <span class="wp-katex-eq" data-display="false">-1 .. 1</span>. We recalculate this vector if it is outside the circle of radius 1: This is to prevent a higher density of rays towards the corners of the rectangle. Next, if the chosen point is behind the surface (detected using <code>dot(R, N) &lt; 0</code> ), we negate it. This will always take it to the correct side. And finally, we normalize the calculated point to place it exactly on the half-circle of radius 1.</p>



<p class="wp-block-paragraph">In 3D the process is the same. The half-sphere of radius 1 is now called the <em>hemisphere</em> over the surface point that we hit.  </p>



<h2 class="wp-block-heading">(Ir)radiance</h2>



<p class="wp-block-paragraph">The random direction <span class="wp-katex-eq" data-display="false">R</span> away from the surface is thus used to collect light, maybe directly from the sky, or maybe via another surface, maybe via several. In any case, the light arrives in the form of <em>radiance</em>, while the BRDF must be applied to <em>irradiance.</em> To understand the difference, look at the following diagram:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="688" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-1024x688.jpg" alt="" class="wp-image-2147" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-1024x688.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-300x201.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-768x516.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-1222x821.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-897x602.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1-360x242.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/project-1.jpg 1251w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 5: Projected radiance becomes irradiance.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, two identical beams of light strike a surface. The left beam affects a small area, but the right one affects a much bigger area. This has a consequence: The <em>energy</em> in the right beam is distributed over a larger area, and therefore, for a single point on the surface, the projected energy is a lot lower.</p>



<p class="wp-block-paragraph">We call light energy that travels freely through space <em>radiance</em>, while energy that got projected onto a surface is called <em>irradiance.</em> We calculate irradiance from radiance by multiplying the radiance by the cosine of the angle between the normal and a vector towards the light. Or, much more conveniently, we can replace that by <code>dot( N, R )</code>, which is precisely what the path tracing code does.</p>



<h2 class="wp-block-heading">PDF</h2>



<p class="wp-block-paragraph">That leaves one final term: The &#8216;pdf&#8217;, which is stated to be <span class="wp-katex-eq" data-display="false">1/{2\pi}</span>. The concept is a bit complex, but what it boils down to is this: The single random ray we send to the hemisphere accounts for light arriving over a hemisphere with an area of <span class="wp-katex-eq" data-display="false">2\pi</span>. If each point on that hemisphere has the same chance of being picked, the probability density is a constant <span class="wp-katex-eq" data-display="false">1/{2\pi}</span>. More details in a separate article: <a href="https://jacco.ompf2.com/2019/12/11/probability-theory-for-physically-based-rendering/">Probability Theory for Physically Based Rendering</a>.   </p>



<h2 class="wp-block-heading">Interlude</h2>



<p class="wp-block-paragraph">Summarizing, a path tracer is a reverse photon simulator, where a path starts at the camera and bounces around the scene randomly until it encounters a light source. At each surface it encounters it loses some energy: Because of the color (a.k.a. albedo) of the material, and because of projection onto the surface, a.k.a. radiance to irradiance conversion.</p>



<p class="wp-block-paragraph">Some thoughts before we advance:</p>



<ul class="wp-block-list">
<li>It&#8217;s good that we are rendering an outdoor scene here: The sky counts as a light in this scene and even short paths are able to find it. On the other hand, that means that the current path tracer will struggle with an indoor scene illuminated by a small light.</li>



<li>All materials so far are diffuse, but paths will happily bounce off of a mirror as well. In that case, the bounce is deterministic instead of random, and the new path direction is calculated using the reflection formula we saw in <a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Episode 2</a>.</li>



<li>A path will bring back less energy the longer it gets. At the same time, these paths are costly; each ray takes time to trace after all. To use compute resources effectively, we need a way to focus on short paths which are expected to bring back more energy. </li>
</ul>



<p class="wp-block-paragraph">That last thought is an important one. Focusing on the <em>important paths</em> is the main way to make a path tracer more efficient.</p>



<h2 class="wp-block-heading">Importance</h2>



<p class="wp-block-paragraph">Let&#8217;s make some changes to the path tracer. Change the lines that calculate the reflected direction and the pdf to the following new code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R = cosweightedDiffuseReflection( N );
float pdf = dot( N, R ) / PI;</pre></div>



<p class="wp-block-paragraph">Running the path tracer with this change yields a substantially better image. In the following image, the left half was rendered with the old approach; the right half uses the new technique.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/is.jpg" alt="" style="width:512px"/><figcaption class="wp-element-caption">Figure 6: The impact of importance sampling.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That looks a lot nicer, especially when the camera is moving. But, is it still the same image? We can easily check. Add the following code at the end of the <code>Tick</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float sum = 0;
for( int i = 0; i &lt; SCRWIDTH * SCRHEIGHT; i++ )
{
    float3 pixel = accumulator[i] * scale;
    sum += pixel.x + pixel.y + pixel.z;
}
printf( "%.2f\n", sum );</pre></div>



<p class="wp-block-paragraph">This code loops over all the pixels in the accumulator and sums their (averaged) red, green and blue color values. The result is a large number which represents the total energy in the rendered image.</p>



<p class="wp-block-paragraph">Now we can compare numbers between the old method and the new one. On my system, I get about 3834000 for the old method, and for the new method, nothing changes: Also about 3834000. Because of the randomness no two frames are identical, but quite obviously, the two methods <em>on average</em> produce the same answer. The difference is in the noise: Statistically speaking, the new method has less variance.</p>



<h2 class="wp-block-heading">Cosine-Weighted</h2>



<p class="wp-block-paragraph">Importance sampling for diffuse materials uses a new function to calculate a random direction to the hemisphere, named <code>cosweightedDiffuseReflection</code>. It&#8217;s implementation is similar to <code>diffuseReflection</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R;
do
{
    R = make_float3( RandomFloat(), RandomFloat(), RandomFloat() ) * 2 - 1;
} while (dot( R, R ) &gt; 1);
return normalize( N + normalize( R ) );</pre></div>



<p class="wp-block-paragraph">Just like <code>diffuseReflection</code>, this function can produce any direction on the hemisphere. However, there is a difference: Directions straight up (along the normal) occur with a greater probability. This is because these directions are <em>more important</em>. Recall the original path tracer code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return brdf * indirect * (dot( N, R ) / pdf);</pre></div>



<p class="wp-block-paragraph">Because of the radiance-to-irradiance conversion, every sample is scaled by <code>dot( N, R )</code>. The outcome of this dot product is close to 1 if <span class="wp-katex-eq" data-display="false">R</span> is close to <span class="wp-katex-eq" data-display="false">N</span>; however, it is close to 0 if <span class="wp-katex-eq" data-display="false">R</span> is almost parallel to the surface. So, if we pick a direction that grazes the surface, the <em>whole path</em> will have a low throughput and our effort will be mostly wasted. We cannot exclude these paths, because we never know what we will find there; perhaps the only light source is in that direction. But, generally speaking, we should make it <em>unlikely</em> that such a direction is picked.</p>



<p class="wp-block-paragraph">The <em>optimal</em> distribution is in this case very specific. Contributions are scaled by <code>dot( N, R )</code>, i.e. a cosine curve. And that&#8217;s precisely what <code>cosweightedDiffuseReflection</code> does.</p>



<p class="wp-block-paragraph">If we would just change the distribution of random rays we would obviously change the rendered image. So, we need to compensate somewhere for this. And that is where the pdf comes into play. If we scale unlikely samples by a high value, and likely samples by a lower value, the end result comes statistically sound again. This is why the pdf is now no longer a constant <span class="wp-katex-eq" data-display="false">1/{2\pi}</span>: Instead, it becomes <code>dot( N, R ) / pi</code>. For more details please read <a href="https://jacco.ompf2.com/2019/12/13/probability-theory-for-physically-based-rendering-part-2/">Probability Theory for Physically Based Rendering Part 2</a>. </p>



<h2 class="wp-block-heading">Beyond</h2>



<p class="wp-block-paragraph">With the basic path tracing algorithm in place it is time to stop. Beyond this point is treasure, but also dragons. There is Russian roulette, which weeds out the long paths. There is <em>direct light sampling</em> a.k.a. <em>next event estimation</em> which makes scenes with small light sources efficient. If there are multiple lights, these can be importance sampled as well. Read some recent research on <a href="https://benedikt-bitterli.me/restir/">ReSTIR</a> to see how to take this to extremes for scenes with millions of lights. There is photon mapping for difficult paths through water and glass. And much more.</p>



<p class="wp-block-paragraph">For this series we&#8217;ll instead move on to denoising. </p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph"><em>The next article may arrive a bit later due to real-world obligations&#8230; Sorry about that.</em></p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> If you have not done so already, replace the solid background color by an HDR skydome and illuminate the scene with that. Implementation details can be found in <a href="https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/">this article</a>. You may want to differentiate between a &#8216;direct hit&#8217; on the skydome and subsequent encounters to make it perfect for <em>Image Based Lighting.</em> </p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> Besides light from the sky, you could add lighting from voxels. Find a way to assign bright colors to certain voxels; the rest should work &#8216;out-of-the-box&#8217;.</p>



<p class="wp-block-paragraph"><strong>Challenge 3.</strong> Path tracers greatly benefit from reprojection. Combine the concepts of the <a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">previous episode</a> with the path tracer code.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1887">Converging under movement: Reprojection</a>.</li>



<li><strong>Path tracing: Basics first; then: Importance Sampling (this article).</strong></li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 5</title>
		<link>https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/</link>
					<comments>https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 22 May 2024 08:34:03 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1887</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><strong>Converging under movement: Reprojection (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">Rendering complex effects in a ray tracer requires random sampling &#8211; which produces noise. A <a href="https://jacco.ompf2.com/?p=1803">previous episode</a> introduced the concept of the <em>accumulator</em>, which combines fast moving &#8211; but noisy &#8211; images with converged images for a stationary camera, by averaging samples over time. In this article we will explore how we can accumulate samples over time, even when the camera is moving.</p>



<p class="wp-block-paragraph">Reprojection is an important, but complex topic. That means that there will be open problems at the end of the article. See the list of challenges at the end of the text for some of these.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">As usual we will first prepare the unmodified template code for the purpose of this episode. For <code>Renderer::Trace()</code> we will use a short version with basic soft shadows from a hard-coded area light. See <a href="https://jacco.ompf2.com/?p=1803">Episode 3</a> for an explanation of this technique.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int x, int y )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    float3 I = ray.IntersectionPoint();
    float3 P( (RandomFloat() + 1) / 2, (RandomFloat() + 6) / 5, 3 );
    float3 L = normalize( P - I );
    if (scene.IsOccluded( Ray( I, L, 10 ) )) return 0.2f;
    return ray.GetAlbedo() * 2 * max( 0.2f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">In <code>scene.cpp</code>, swap out the default scene for the scene introduced at the end of Episode 3:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    grid = (uint*)MALLOC64( GRIDSIZE3 * 4 );
    gzFile f = gzopen( "assets/viking.bin", "rb" );
    gzread( f, grid, 16 ); // skip size data
    gzread( f, grid, 1 &lt;&lt; 23 );
}</pre></div>



<p class="wp-block-paragraph">And finally, since we will be working on reprojection, let&#8217;s automate scene movement. In <code>camera.cpp</code>, replace <code>HandleInput</code> by the following turntable code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">bool Camera::HandleInput( const float t )
{
    static float r = 0, a;
    r += t * 0.001f, a = 0.7f * sinf( r ) + 1.6f;
    camPos = 0.7f * float3( cosf( a ) + 0.7, 0.7f, sinf( a ) + 0.7f );
    mat4 M = mat4::LookAt( camPos, float3( 5, 3, 5 ) / 10 );
    float3 x( M[0], M[4], M[8] ), y( M[1], M[5], M[9] ), z( M[2], M[6], M[10] );
    topLeft = camPos + 2 * z - aspect * x + y;
    topRight = camPos + 2 * z + aspect * x + y;
    bottomLeft = camPos + 2 * z - aspect * x - y;
    return true;
}</pre></div>



<p class="wp-block-paragraph">I admit that all the above code was optimized for brevity, not clarity. Feel free to rectify that before proceeding. Or, accept this random challenge and shorten it further. Here&#8217;s a <a href="https://pastebin.com/c7n66AVm">tiny ray tracer</a> in C in case you need some inspiration.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/spin.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 1: The starting point for this episode: A rotating voxel scene. </figcaption></figure>
</div>


<p class="wp-block-paragraph">To do something about the noise in those soft shadows we have several options:</p>



<ol class="wp-block-list">
<li>We could take more samples. This would of course affect framerate.</li>



<li>We could take better samples, using blue noise.</li>



<li>We can accumulate samples over time. But this requires a stationary camera.</li>
</ol>



<p class="wp-block-paragraph">If we ignore the fact that the camera is not stationary, and use the accumulator anyway, we get a horrible blur&#8230;</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/blur.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 2: Accumulating while ignoring the moving camera.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The problem is: After 100 frames, all frames contribute equally to the average. The longer this runs, the less impact new samples have. The opposite should be the case: Newer samples should have a greater weight than older ones, with ancient samples slowly diminishing. This is what we get if we replace the accumulator by a <em>running average.</em></p>



<h2 class="wp-block-heading">Running Average</h2>



<p class="wp-block-paragraph">The running average is defined mathematically as:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">A_{new}=w A_{old}+(1-w)S</span></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here, <span class="wp-katex-eq" data-display="false">A_{old}</span> is the value in the accumulator, which will be replaced for the next frame by <span class="wp-katex-eq" data-display="false">A_{new}</span>. Value <span class="wp-katex-eq" data-display="false">S</span> is a new sample which we obtain by calling <code>Renderer::Trace</code>. And finally, <span class="wp-katex-eq" data-display="false">w</span> is a blending factor. A typical value for <span class="wp-katex-eq" data-display="false">w</span> is <span class="wp-katex-eq" data-display="false">0.9</span>, which would replace the accumulator by 90% of whatever was in it, plus 10% of a new sample. This sounds like the new sample is still pretty unimportant, but in reality, <em>all</em> previous samples have to share the 90% weight, and older samples become obsolete as we move on, while the new sample always gets the 10% share.</p>



<p class="wp-block-paragraph">To implement the running average, we need room for the accumulator:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Init()
{
    accumulator = new float3[SCRWIDTH * SCRHEIGHT];
}</pre></div>



<p class="wp-block-paragraph">We can now use the accumulator to keep track of the running average.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( (float)x, (float)y );
    float3&amp; pixel = accumulator[x + y * SCRWIDTH];
    pixel = 0.8f * pixel + 0.2f * Trace( r );
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel );
}</pre></div>



<p class="wp-block-paragraph">Note that in this code pixel is a bit different than in previous snippets. It is a float3 <em>reference</em>, so it maps directly to a value in the accumulator array.</p>



<p class="wp-block-paragraph">Compared to the original accumulator, calculating the running average is a bit simpler. For starters, we don&#8217;t need to keep track of the number of frames that contribute to the average. We also don&#8217;t need to scale the accumulated value: Since <span class="wp-katex-eq" data-display="false">w+(1-w)=1</span>, the pixels in the accumulator do not get brighter over time, and we can use them as-is.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/runavg.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 3: Accumulating using a running average fades out older samples.</figcaption></figure>
</div>


<p class="wp-block-paragraph">We can now play with the weight factor <span class="wp-katex-eq" data-display="false">w</span>. Using <span class="wp-katex-eq" data-display="false">0.8</span> we get considerable ghosting. A larger weight (e.g. <span class="wp-katex-eq" data-display="false">0.99</span>) will make this worse. A lower value reduces ghosting, but now the average discards more of the old value, which makes the shadows noisier. </p>



<p class="wp-block-paragraph">The real power of the running average is in different weights per pixel however. Think of <span class="wp-katex-eq" data-display="false">w</span> as a <em>trust value:</em> If we believe that the value in the accumulator should contribute to a pixel, we make <span class="wp-katex-eq" data-display="false">w</span> a value close to 1. If on the other hand we suspect the history contains useless data, e.g. because we moved the camera really fast, then we reduce <span class="wp-katex-eq" data-display="false">w</span>, maybe all the way to zero &#8211; which fully discards the old data and overwrites it with the new sample.</p>



<h2 class="wp-block-heading">Hindsight</h2>



<p class="wp-block-paragraph">So far, when we read &#8216;historic&#8217; data from the accumulator, we read a pixel at the same location as the pixel we&#8217;re working on. That doesn&#8217;t always make sense. Imagine we have a camera that slowly moves to the right. In that case, the perfect pixel to blend with is always a bit to the <em>left</em>. In fact, if we could calculate <em> by how much</em>, we should in theory get perfect blending, without any ghosting.</p>



<p class="wp-block-paragraph">So, the million dollar question is: For a pixel location <span class="wp-katex-eq" data-display="false">(x,y)</span> in the current frame, <em>where was this pixel in the previous frame?</em></p>



<p class="wp-block-paragraph">At first sight, this looks like a very hard thing to calculate. But, when we take a moment to think over the math, it turns out to be&#8230; not impossible.</p>



<p class="wp-block-paragraph">Consider the following situation:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/primhit.png" alt="" style="width:440px"/><figcaption class="wp-element-caption">Figure 4: Primary hit for a pixel, in world space.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, a ray is sent through a pixel. It then hits the red ball. </p>



<p class="wp-block-paragraph">There is something about the coordinates used for <em>everything</em> in this setup: <em>It&#8217;s all happening in world space.</em> The camera, the primary hit, even the pixel position; it&#8217;s all defined in one coordinate system. And, if we move on to the next frame, this is <em>still </em>true:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/moving.png" alt="" style="width:440px"/><figcaption class="wp-element-caption">Figure 5: Camera moving downwards in world space.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That point <span class="wp-katex-eq" data-display="false">P</span> in the new frame <span class="wp-katex-eq" data-display="false">t</span> <em>was </em>in fact in view in the previous frame <span class="wp-katex-eq" data-display="false">t-1</span>. So, if we can construct a ray from the <em>previous </em>camera to <span class="wp-katex-eq" data-display="false">P</span>, and we figure out through which pixel this ray travels, then we know exactly where our pixel was in the previous frame.</p>



<p class="wp-block-paragraph">The original question, <em>&#8220;where was this pixel in the previous frame?&#8221;</em> has now been refined to: <em>&#8220;through which pixel of the previous frame is <span class="wp-katex-eq" data-display="false">P</span> visible?&#8221;</em></p>



<p class="wp-block-paragraph">An intuitive way to answer this question is illustrated in the next image.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/frustum.png" alt="" style="width:450px"/><figcaption class="wp-element-caption">Figure 6: Pixel position relative to frustum planes.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Point <span class="wp-katex-eq" data-display="false">P</span> is visible through the red pixel. It turns out that the position of the pixel corresponds to the distance of <span class="wp-katex-eq" data-display="false">P</span> to the top and bottom plane. More formally: On a scale of 0..1, the position of the red point is <span class="wp-katex-eq" data-display="false">d_1/(d_1+d_2)</span>. This works in a 2D situation, but also in 3D: In that case, we need <em>four</em> planes, which together make up a pyramid shape, known as the view frustum.</p>



<h2 class="wp-block-heading">Mathematics</h2>



<p class="wp-block-paragraph">Let&#8217;s summarize. We have a point <span class="wp-katex-eq" data-display="false">P</span>, which is a point in the world on a surface visible through a pixel in the current frame. We <em>need</em> the four distances of this point to the four planes for the view frustum of the previous frame. Using these distances, we can calculate through which pixel point <span class="wp-katex-eq" data-display="false">P</span> was visible.</p>



<p class="wp-block-paragraph">The first mathematical construct is thus the set of four planes. A plane can be defined in several ways, but for our purposes the <em>implicit</em> <em>definition</em> is useful. It&#8217;s form is <span class="wp-katex-eq" data-display="false">Ax+By+Cz-d=0</span>. Here, <span class="wp-katex-eq" data-display="false">ABC</span> form the normal of the plane; scalar <span class="wp-katex-eq" data-display="false">d</span> is the distance of the plane to the origin. The normal vector is calculated as the cross-product between two vectors in the plane. For each of the four planes, we thus must find two vectors. We can produce these from the four screen corners and the camera position.</p>



<p class="wp-block-paragraph">The camera is defined in file <code>camera.h</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">class Camera
{
public:
    Camera();
    ~Camera();
    Ray GetPrimaryRay( const float x, const float y );
    bool HandleInput( const float t );
    float aspect = (float)SCRWIDTH / (float)SCRHEIGHT;
    float3 camPos, camTarget;
    float3 topLeft, topRight, bottomLeft;
};</pre></div>



<p class="wp-block-paragraph">It contains all the data we need. To calculate the normal of the top plane for example, we use the vector from <code>topLeft</code> to <code>topRight</code> and the vector from <code>camPos</code> to <code>topLeft</code>. And, for the left plane we use the vector from <code>camPos</code> to <code>topLeft</code> and the vector from <code>topLeft</code> to <code>bottomLeft</code>. Note that a <code>bottomRight</code> point is missing, but a vector from <code>topRight</code> to <code>bottomRight</code> is identical to the vector from <code>topLeft</code> to <code>bottomLeft</code>, so we don&#8217;t need it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="933" height="628" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1.jpg" alt="" class="wp-image-2093" style="width:500px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1.jpg 933w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-300x202.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-768x517.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-897x604.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/fr3d-1-360x242.jpg 360w" sizes="auto, (max-width: 933px) 100vw, 933px" /><figcaption class="wp-element-caption">Figure 7: The view frustum. The bounding planes can be constructed using vectors in the planes.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The template does not have a &#8216;Plane&#8217; class, but we can easily make one. Add the following lines to <code>camera.h</code>, above the <code>Camera</code> class definition:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">typedef float4 Plane;
struct Frustum { Plane plane[4]; };
inline float distance( Plane&amp; plane, float3&amp; pos )
{
    return dot( float3( plane ), pos ) - plane.w;
}</pre></div>



<p class="wp-block-paragraph">The first line defines the <code>Plane</code> type as a <code>float4</code>. That looks rather minimalistic, but it is just what we need: <code>xyz</code> in the <code>float4</code> will hold the plane normal, while the <code>w</code> component will store the distance of the plane to the origin. The second line defines a frustum as a collection of four planes. And finally, the one-line function will simplify working with the new <code>Plane</code> type: It calculates the distance between a point and a plane.</p>



<p class="wp-block-paragraph">We now have everything we need to calculate four planes for a camera. The functionality is implemented as a new method of the <code>Camera</code> class.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Frustum BuildFrustum()
{
    Frustum f;
    f.plane[0] = cross( topLeft - bottomLeft, topLeft - camPos );
    f.plane[1] = cross( topRight - camPos, topLeft - bottomLeft );
    f.plane[2] = cross( topRight - topLeft, topLeft - camPos );
    f.plane[3] = cross( bottomLeft - camPos, topRight - topLeft );
    for (int i = 0; i &lt; 4; i++) f.plane[i].w = distance( f.plane[i], camPos );
    return f;
}</pre></div>



<p class="wp-block-paragraph">Plane 0 and 1 are the planes on the left and the right side of the view frustum. Plane 2 and 3 are the planes at the top and the bottom. The vectors used in the cross product are carefully chosen so the normals points inwards. This way, we get positive distances for points inside the view frustum. We can optionally normalize the result of the cross product, but in this specific case, this is not needed, so we can spare the effort.</p>



<p class="wp-block-paragraph">Method <code>Camera::BuildFrustum</code> ends with the calculation of the distance of each plane to the origin. For this, we take one point on the plane (conveniently, <code>camPos</code> will do in all cases), and calculate the dot product of this point and the normal. </p>



<h2 class="wp-block-heading">Applying Mathematics</h2>



<p class="wp-block-paragraph">Remember that the view frustum of the camera of the previous frame is needed for reprojection. So, we return to <code>renderer.cpp</code>, and add a global variable at the top of the file:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Frustum previous;</pre></div>



<p class="wp-block-paragraph">Then, <em>after</em> rendering a frame but just <em>before</em> we change the camera for the next frame (using a call to <code>camera.HandleInput(..))</code> we fill variable <code>previous</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// handle user input
previous = camera.BuildFrustum();
camera.HandleInput( deltaTime );</pre></div>



<p class="wp-block-paragraph">The final step is to actually use the set of four planes for reprojection. We need an intersection point for this: The point <span class="wp-katex-eq" data-display="false">P</span> used in the math. This point P is obtained from the ray:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r = camera.GetPrimaryRay( (float)x, (float)y );
float3 sample = Trace( r );
if (r.voxel &gt; 0)
{
    float3 P = r.O + r.t * r.D;
    ...</pre></div>



<p class="wp-block-paragraph">Note the condition: <code>r.voxel &gt; 0</code>. We cannot reproject if the ray hit nothing: In that case, we just plot the sky color, without using reprojection. If we <em>did</em> hit a voxel, the hit location <span class="wp-katex-eq" data-display="false">P</span> is along the ray: Starting at the ray origin <code>r.O</code>, we travel <code>r.t</code> units in the ray direction <code>r.D</code>. The distance <code>r.t</code> is what <code>scene.FindNearest</code> (called from <code>Trace</code>) calculated. </p>



<p class="wp-block-paragraph">We now calculate the distance of <span class="wp-katex-eq" data-display="false">P</span> to the left and right planes, and to the top and bottom planes:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float dLeft = distance( previous.plane[0], P );
float dRight = distance( previous.plane[1], P );
float dUp = distance( previous.plane[2], P );
float dDown = distance( previous.plane[3], P );</pre></div>



<p class="wp-block-paragraph">Using these distances we then calculate the pixel location for <span class="wp-katex-eq" data-display="false">P</span> in the previous frame.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float prev_x = (SCRWIDTH * dLeft) / (dLeft + dRight);
float prev_y = (SCRHEIGHT * dUp) / (dUp + dDown);</pre></div>



<p class="wp-block-paragraph">Remember that <span class="wp-katex-eq" data-display="false">d_{left}/(d_{left}+d_{right})</span> yields a number between 0 and 1; we thus scale by the resolution of the screen to get the actual pixel position. The reprojection was successful if the calculated screen coordinates are actually on the screen:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
{
    ...
}</pre></div>



<h2 class="wp-block-heading">History</h2>



<p class="wp-block-paragraph">For reprojection we need to read pixels from the previous frame, while writing pixels for the current frame. Since we do not read from the same pixels we&#8217;re writing to, we need a copy of the &#8216;history&#8217;. Add the following line to <code>Renderer::Init()</code> to add a second pixel buffer:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">history = new float3[SCRWIDTH * SCRHEIGHT];</pre></div>



<p class="wp-block-paragraph">Then, at the end of each frame, we copy the <code>accumulator</code> to <code>history</code>. Or, we simply swap the two buffers, which is a bit more efficient. All it takes is the following line at the end of <code>Renderer::Tick</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">swap( history, accumulator );</pre></div>



<p class="wp-block-paragraph">We can now complete the <code>if</code> statement:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
{
    historySample = history[(int)prev_x + (int)prev_y * SCRWIDTH];
}</pre></div>



<p class="wp-block-paragraph">And there it is: This <code>historySample</code> is what we will assign a large weight in the running average from the start of this article. The full pixel loop, in all its glory: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( (float)x, (float)y );
    float3 historySample, sample = Trace( r );
    float historyWeight = 0;
    if (r.voxel &gt; 0)
    {
        // reproject
        float3 P = r.O + r.t * r.D;
        float dLeft = distance( previous.plane[0], P );
        float dRight = distance( previous.plane[1], P );
        float dUp = distance( previous.plane[2], P );
        float dDown = distance( previous.plane[3], P );
        float prev_x = (SCRWIDTH * dLeft) / (dLeft + dRight);
        float prev_y = (SCRHEIGHT * dUp) / (dUp + dDown);
        if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
        {
            historyWeight = 0.95f;
            historySample = history[(int)prev_x + (int)prev_y * SCRWIDTH];
        }
    }
    float3 pixel = historyWeight * historySample + (1 - historyWeight) * sample;
    accumulator[x + y * SCRWIDTH] = pixel;
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel );
}</pre></div>



<p class="wp-block-paragraph">Note how the weight that we apply to the history value simply becomes zero when we can&#8217;t reproject. In that case, we will use the new sample alone.</p>



<p class="wp-block-paragraph">The result of all this effort is&#8230; Underwhelming.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/underwhelm.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 8: The initial result of reprojection.</figcaption></figure>
</div>


<p class="wp-block-paragraph">At this point, it is easy to be discouraged or to assume that the approach is buggy or not working at all. But, let&#8217;s not give up just yet! There&#8217;s two important problems that need to be solved, which should get us a lot closer to a correct looking result:</p>



<ol class="wp-block-list">
<li>The reprojected coordinate is not an integer coordinate. Yet, we unceremoniously casted it to integer to read a single pixel from the history.</li>



<li>Not all history values are valid. What if the point we see through the reprojected pixel location is not <span class="wp-katex-eq" data-display="false">P</span> at all, but something closer, or farther away?</li>
</ol>



<p class="wp-block-paragraph">We will tackle these one by one.</p>



<h2 class="wp-block-heading">Bilerp</h2>



<p class="wp-block-paragraph">To read a pixel from a floating point pixel coordinate we use a technique called <em>bilinear interpolation</em>. This is illustrated in the following image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/bilerp.jpg" alt=""/><figcaption class="wp-element-caption">Figure 9: Bilinear interpolation: Replacing a point sample by an area sample.</figcaption></figure>
</div>


<p class="wp-block-paragraph">To read at the position indicated by the yellow dot, we currently simply use pixel <span class="wp-katex-eq" data-display="false">P_0</span>. But, if we do not take a <em>point sample</em> but instead read a 1&#215;1 sized square, we need <em>four</em> pixels, blended in a very specific way: Pixel <span class="wp-katex-eq" data-display="false">P_0</span> should have a weight proportional to the area of the overlap between <span class="wp-katex-eq" data-display="false">P_0</span> and the white rectangle; similarly, <span class="wp-katex-eq" data-display="false">P_1</span>, <span class="wp-katex-eq" data-display="false">P_2</span> and <span class="wp-katex-eq" data-display="false">P_3</span> contribute to the blend depending on their overlap with the white rectangle. Obviously, the sum of the four weights is 1, that is the area of the white rectangle.</p>



<p class="wp-block-paragraph">We calculate the weights by looking at the fractional part of the pixel coordinate. Let&#8217;s say that the yellow dot is at position <span class="wp-katex-eq" data-display="false">x=14.2</span>, <span class="wp-katex-eq" data-display="false">y=8.2</span>. In that case, the fractional position of the dot is <span class="wp-katex-eq" data-display="false">x=0.2, y=0.2</span>, and the area of overlap is <span class="wp-katex-eq" data-display="false">(1-0.2)*(1-0.2)=0.64</span>. The full set of weights, in C code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float fx = fracf( prev_x ), fy = fracf( prev_y );
float w0 = (1 - fx) * (1 - fy);
float w1 = fx * (1 - fy);
float w2 = (1 - fx) * fy;
float w3 = fx * fy;</pre></div>



<p class="wp-block-paragraph">We can now read 2&#215;2 pixels, and scale them by these weights.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">int a = (int)prev_x + (int)prev_y * SCRWIDTH;
float3 p0 = history[a]; // (x,y)
float3 p1 = history[a + 1]; // (x+1,y)
float3 p2 = history[a + SCRWIDTH]; // (x,y+1)
float3 p3 = history[a + SCRWIDTH + 1]; // (x+1,y+1)
historySample = p0 * w0 + p1 * w1 + p2 * w2 + p3 * w3;</pre></div>



<p class="wp-block-paragraph">One important change is needed when we read 2&#215;2 pixels. We cannot read outside the history buffer, but at position <code>x=SCRWIDTH-1</code> we will do just that. The easiest fix is to limit <code>prev_x</code> and <code>prev_y</code> to a smaller range:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 2 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 2)
{
    ...
}</pre></div>



<p class="wp-block-paragraph">Time to put the bilinear interpolation code to the test. The result is <em>much</em> better:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/birepro.jpg" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 10: Reprojection with bilinear interpolation of reads from the history buffer.</figcaption></figure>
</div>


<h2 class="wp-block-heading">(Dis)occlusions</h2>



<p class="wp-block-paragraph">The second problem that remains to be solved is the issue of geometry that gets occluded or disoccluded during camera movement. When that happens, point <span class="wp-katex-eq" data-display="false">P</span> wasn&#8217;t visible in the previous frame; we can look in its direction but if we do that, we will find a different point. Luckily, it&#8217;s easy to check this. For this, we need the previous camera position. Add a global variable to it, just below the <code>Frustum previous</code> definition:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 prevCamPos;</pre></div>



<p class="wp-block-paragraph">We update this variable just before the call to <code>camera.HandleInput()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">prevCamPos = camera.camPos;</pre></div>



<p class="wp-block-paragraph">And finally, we use the previous camera to fire a ray at <span class="wp-katex-eq" data-display="false">P</span> in the previous frame. If this ray hits something that is close to P, we&#8217;re good; otherwise, we will assume that the reprojection failed after all.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (prev_x &gt;= 0 &amp;&amp; prev_x &lt; SCRWIDTH - 1 &amp;&amp; prev_y &gt;= 0 &amp;&amp; prev_y &lt; SCRHEIGHT - 1)
{
    // verify reprojection
    Ray r( prevCamPos, P - prevCamPos );
    scene.FindNearest( r );
    float3 Q = prevCamPos + r.t * r.D;
    if (sqrLength( P - Q ) &lt; 0.001f)
    {
        ...</pre></div>



<p class="wp-block-paragraph">And this time, reprojection is as good as it gets.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/reprofinal.jpg" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 11: Reprojection with sample rejection.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Now, this image still has issues. There are some rather noisy areas, and the picture as a whole looks a bit blurry. Some ghosting also remains. We can tweak the ghosting by finetuning the maximum distance between <span class="wp-katex-eq" data-display="false">P</span> and <span class="wp-katex-eq" data-display="false">Q</span>, but there is no perfect setting. The blurring can be countered somewhat using a sharpening filter.</p>



<p class="wp-block-paragraph">But, this is already a very lengthy episode&#8230; So I will leave these challenges as an &#8216;exercise for the reader&#8217;. Literally.</p>



<p class="wp-block-paragraph">Next time: Path Tracing. There is mathematical beauty ahead, and although it will introduce more noise, it also is capable of producing some breath-taking pictures. See you next week!</p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> As suggested in the text, post-process the final image with a 3&#215;3 sharpening filter to reduce the blurriness of the reprojected image. The process is explained quite well on <a href="https://en.wikipedia.org/wiki/Unsharp_masking">Wikipedia</a>. Applying the sharpening filter will cause quite some memory traffic on your CPU. Consider using multi-threading to speed it up.</p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> The article uses a ray to detect (dis)occlusions. A more performant method is to reject history samples if their color differs too much from the colors in the new frame. The method is described in the paper &#8220;<a href="http://behindthepixels.io/assets/files/TemporalAA.pdf">A Survey of Temporal Antialiasing Techniques</a>&#8221; by Yang et al., in Section 4.2. Implement this method. You can also find an implementation in <a href="https://www.shadertoy.com/view/4dSBDt">this Shadertoy</a>.</p>



<p class="wp-block-paragraph"><strong>Challenge 3.</strong> Pixels for which reprojection failed are relatively noisy, as shown in Figure 11. It is possible to send these pixels extra rays, to improve the estimate, at the expense of more new samples. This is known as <em>adaptive sampling</em>. Implement this technique.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1839">Noise reduction: Stratification and blue noise</a>.</li>



<li><strong>Converging under movement: Reprojection (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 4</title>
		<link>https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/</link>
					<comments>https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 15 May 2024 07:47:10 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1839</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray </a><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">tracing</a><a href="https://jacco.ompf2.com/?p=1715"> template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, </a><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft </a><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">shadows</a>.</li>



<li><strong>Noise reduction: Stratification and blue noise (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">In the last article we enabled some complex rendering features for the ray tracer using random sampling and accumulation over time. This yields pretty images, except when the camera is moving. It&#8217;s not going to be easy to get rid of this noise entirely, but there are a lot of things we can do to improve the situation. We start at the basis: The random numbers we use to generate samples.</p>



<p class="wp-block-paragraph">Warning: This is a somewhat theoretical episode.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">For this episode we will need a simple scene and some noise. A suitable scene can be constructed by replacing <code>Scene::Scene()</code> in <code>scene.cpp</code> by:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    grid = (uint*)MALLOC64( GRIDSIZE3 * sizeof( uint ) );
    for (int i = 0; i &lt; 128 * 128 * 128; i++)
    {
        const int x = i &amp; 127, y = (i &gt;&gt; 7) &amp; 127, z = i &gt;&gt; 14;
        bool v = y &lt; 10, p = z &gt; 90 &amp;&amp; z &lt; 94;
        p &amp;= (x &amp; 31) &gt; 10 &amp;&amp; (x &amp; 31) &lt; 18 &amp;&amp; y &lt; 80;
        Set( x, y, z, p || v ? 0xffffff : 0 );
    }
}</pre></div>



<p class="wp-block-paragraph">This produces a floor and four pillars. Next, we render the scene with an area light and some basic shading, using the following minimalistic <code>Renderer::Trace</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int x, int y )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    float3 P( (RandomFloat() + 1) / 2, (RandomFloat() + 6) / 5, 3 );
    float3 I = ray.IntersectionPoint(), L = normalize( P - I );
    if (scene.IsOccluded( Ray( I, L, 10 ) )) return 0.2f;
    return 2 * max( 0.2f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">This should produce the following output. It should run in real-time; if it instead looks like a slide show, you may be running a Debug build. Select &#8216;Release&#8217; to resolve this.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="659" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-1024x659.jpg" alt="" class="wp-image-1851" style="width:542px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-1024x659.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-300x193.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-768x494.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-897x577.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars-360x232.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/pillars.jpg 1212w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 1: Soft shadows using white noise.</figcaption></figure>
</div>


<p class="wp-block-paragraph">And that&#8217;s where this article begins.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Stratification</h2>



<p class="wp-block-paragraph">The noise in the <em><a href="https://en.wikipedia.org/wiki/Umbra,_penumbra_and_antumbra#Penumbra">penumbra</a></em> of the soft shadows of the pillars has a name: It&#8217;s <em><a href="https://en.wikipedia.org/wiki/White_noise">white noise</a></em>. We obtain it by using a proper pseudo-random number generator: &#8216;Pseudo&#8217;, because that&#8217;s the best a computer can do. The RNG used in the template is a fast but good one: Marsaglia&#8217;s <a href="https://www.jstatsoft.org/article/view/v008i14">Xor32</a> algorithm. You can find its implementation in <code>tmpl8math.cpp</code>. Each time we call <code>RandomFloat</code> we get a number between 0 and 1. The random number is <em>uniform</em>, which means that every value between 0 and 1 should have the same probability of being generated. If we use this RNG to produce 100 x-coordinates and 50 y-coordinates, we get this image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="828" height="808" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32.png" alt="" class="wp-image-1853" style="width:320px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32.png 828w, https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32-300x293.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32-768x749.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/xor32-360x351.png 360w" sizes="auto, (max-width: 828px) 100vw, 828px" /><figcaption class="wp-element-caption">Figure 2: White noise distribution.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The RNG has a problem. Quite often, two or more white dots are right next to each other. In fact, some of them are in the same position. To make matters worse, some parts of the picture have rather few dots. The same pattern, clusters and all, appears in the noisy penumbra of the soft shadow.</p>



<p class="wp-block-paragraph">An easy way to improve matters is a technique called <em>stratification.</em> It works like this: We calculate 100 random dots, but instead of giving each dot the full rectangle to pick a spot on, we limit each to a <em>stratum</em>:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="804" height="800" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata.png" alt="" class="wp-image-1854" style="width:320px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata.png 804w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-300x300.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-150x150.png 150w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-768x764.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata-360x358.png 360w" sizes="auto, (max-width: 804px) 100vw, 804px" /><figcaption class="wp-element-caption">Figure 3: Stratification with 10&#215;10 strata.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Here, the rectangle is divided in 100 equal <em>strata</em>, and each <em>stratum</em> receives one random dot. The effect is interesting: Each location in the full rectangle still has a chance of being covered by a dot, but the dots are now much better distributed.</p>



<p class="wp-block-paragraph">We can use this technique to improve the shadow. Change the call to Trace inside <code>Renderer::Tick()</code> to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = Trace( r, 0, x, y );</pre></div>



<p class="wp-block-paragraph">This tells <code>Trace</code> what the pixel coordinate is for the ray we&#8217;re tracing; we need that info inside <code>Renderer::Trace</code> to determine the stratum. Inside <code>Renderer::Trace()</code>, change the single line that picks a random point <code>P</code> on the light. It reads:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 P( (RandomFloat() + 1) / 2, (RandomFloat() + 1) / 5, 3 );</pre></div>



<p class="wp-block-paragraph">Modify it to:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float r0 = RandomFloat(), r1 = RandomFloat();
if (x &gt; SCRWIDTH / 2)
{
    if (x &amp; 1) r0 *= 0.5f; else r0 = (r0 + 1) * 0.5f;
    if (y &amp; 1) r1 *= 0.5f; else r1 = (r1 + 1) * 0.5f;
}
float3 P( (r0 + 1) / 2, (r1 + 6) / 5, 3 );</pre></div>



<p class="wp-block-paragraph">For the left side of the screen this changes nothing, so we have something to compare to. For the right half of the screen however, groups of 2&#215;2 pixels become strata: The top-left pixel of the group will use random numbers for x and y in the range 0 .. 0.5, while the bottom-right pixel uses random numbers in the range 0.5 .. 1. This works&#8230; Sort of:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="472" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1024x472.png" alt="" class="wp-image-1855" style="width:542px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1024x472.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-300x138.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-768x354.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1536x708.png 1536w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-2048x943.png 2048w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-1222x563.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-897x413.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/badstrata-360x166.png 360w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 4: One sample per pixel. Left: White noise. Right: Stratification over 2&#215;2 pixels, resulting in patterns due to correlation.</figcaption></figure>
</div>


<p class="wp-block-paragraph">When you think about it, it makes sense. For each pixel in a 2&#215;2 pixel group, each pixel will <em>always</em> sample the <em>same</em> quadrant of the area light. The pixel next to it will <em>always</em> sample a different quadrant. If one quadrant is fully visible, while the other isn&#8217;t, we get patterns: There is now a <em>correlation</em> between the position of a pixel, and the random numbers generated for it.</p>



<p class="wp-block-paragraph">The solution is simple. If we sample each stratum for each pixel, we no longer skip quadrants, but we do keep the benefits of stratification. In this case we have four strata, so we take four samples in <code>Renderer::Tick()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = 0.25f *
    (Trace( r, 0, x + 1, y + 1 ) + Trace( r, 0, x, y ) +
    Trace( r, 0, x + 1, y ) + Trace( r, 0, x, y + 1 ));</pre></div>



<p class="wp-block-paragraph">The result:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="334" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-1024x334.png" alt="" class="wp-image-1859" style="width:640px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-1024x334.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-300x98.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-768x250.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-897x293.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4-360x117.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/strata4.png 1110w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 5: Four samples per pixel. Left: White noise. Right: Stratification with four strata.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It is quite clear that even with four strata the result is much better than just white noise. More strata will be even better &#8211; with diminishing returns, though. Sadly, there is a drawback to stratification: For <span class="wp-katex-eq" data-display="false">N</span> strata, we need to take <span class="wp-katex-eq" data-display="false">N</span> samples for each pixels to avoid correlation, and that will quickly reduce the ray tracer to a slideshow&#8230;</p>



<p class="wp-block-paragraph">Luckily, there is a way to get the benefits of stratification even with a single sample per pixel.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Blue Noise</h2>



<p class="wp-block-paragraph">Stratification for an area light works because it ensures that four samples actually sample all four quadrants of the area light. But, we can do even better. How about this distribution of samples over the surface of the light source:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" src="https://upload.wikimedia.org/wikipedia/commons/b/bb/Poisson_disk_sampling.svg" alt=""/></figure>
</div>


<p class="wp-block-paragraph">This is <em>blue noise</em>, where each sample has a minimum distance to other samples. This beats even the 10&#215;10 strata we saw earlier. Problem is: How do we generate the positions of these samples? The answer is: We don&#8217;t; we use pre-calculated values. Have a look at this texture, which is generously provided by Christoph Peters on his <a href="https://momentsingraphics.de/BlueNoise.html">Moments in Graphics</a> blog:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="256" height="256" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/LDR_RG01_0-1.png" alt="" class="wp-image-1864" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/LDR_RG01_0-1.png 256w, https://jacco.ompf2.com/wp-content/uploads/2024/04/LDR_RG01_0-1-150x150.png 150w" sizes="auto, (max-width: 256px) 100vw, 256px" /><figcaption class="wp-element-caption">Figure 7: Precalculated blue noise. Source: Christoph Peters / Moments in Graphics.</figcaption></figure>
</div>


<p class="wp-block-paragraph">In this texture the red and green channels are used to store the precalculated blue noise. Image data is generally integer data, but if we extract red and green and divide by 256, we get numbers in the range 0..1, which we can then use as random numbers.</p>



<p class="wp-block-paragraph">Let&#8217;s put that to the test. For this, we tile the texture over the screen, and use the values in red and green as our &#8216;random numbers&#8217;. </p>



<p class="wp-block-paragraph">First, undo the last change to <code>Tick</code>, so pixels once again use a single sample:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = Trace( r, 0, x, y );</pre></div>



<p class="wp-block-paragraph">After that, the modifications in <code>Renderer::Trace()</code> are modest.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">static Surface blue( "assets/LDR_RG01_0.png" );
float r0 = RandomFloat(), r1 = RandomFloat();
if (x &gt; SCRWIDTH / 2)
{
    int pixel = blue.pixels[(x &amp; 63) + (y &amp; 63) * 64];
    int red = pixel &gt;&gt; 16, green = (pixel &gt;&gt; 8) &amp; 255;
    r0 = red / 256.0f;  
    r1 = green / 256.0f;
}</pre></div>



<p class="wp-block-paragraph">The result is staggering.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="426" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-1024x426.png" alt="" class="wp-image-1867" style="width:640px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-1024x426.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-300x125.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-768x320.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-1222x509.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-897x373.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow-360x150.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/blueshadow.png 1230w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 8: Sampling an area light using precalculated blue noise.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Blue noise is indeed far better than white noise, and even better than stratification. We will still need to deal with the stationary nature of the blue noise though before we can use it together with the accumulator from the <a href="https://jacco.ompf2.com/?p=1803">previous article</a>.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Converge</h2>



<p class="wp-block-paragraph">There are several ways to make the blue noise animate over time. We could for instance use multiple blue noise tiles, or shift the tile data. In practice, it turns out that these options are not all that great. More details on that can be found in <a href="https://link.springer.com/content/pdf/10.1007/978-1-4842-7185-8_24.pdf">Chapter 24</a> of Ray Tracing Gems II, by NVIDIAs Alan Wolfe, but I am sharing here his conclusion:</p>



<p class="wp-block-paragraph">To animate blue noise, we just repeatedly add the <em>golden ratio</em> to the values. This will yield values outside the range 0..1, so we keep just the fractional part. Like so:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">r0 = fracf( r0 + frame * 0.61803399f );
r1 = fracf( r1 + frame * 0.61803399f );</pre></div>



<p class="wp-block-paragraph">We made quite some changes, so here is the full <code>Renderer::Trace()</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int frame, int x, int y )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    static Surface blue( "assets/LDR_RG01_0.png" );
    float r0 = RandomFloat(), r1 = RandomFloat();
    if (x &gt; SCRWIDTH / 2)
    {
        int pixel = blue.pixels[(x &amp; 63) + (y &amp; 63) * 64];
        int red = pixel &gt;&gt; 16, green = (pixel &gt;&gt; 8) &amp; 255;
        r0 = fracf( red / 256.0f + frame * 0.61803399f );
        r1 = fracf( green / 256.0f + frame * 0.61803399f );
    }
    float3 P( (r0 + 1) / 2, (r1 + 6) / 5, 3 );
    float3 I = ray.IntersectionPoint(), L = normalize( P - I );
    if (scene.IsOccluded( Ray( I, L, 10 ) )) return 0.2f;
    return 2 * max( 0.2f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">This function now requires a &#8216;frame&#8217; argument, which we provide from <code>Renderer::Tick()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pixel = Trace( r, frame, x, y );</pre></div>



<p class="wp-block-paragraph">Here, &#8216;frame&#8217; is a static variable that we increment each frame. It can be placed just before the <code>#pragma omp parallel for</code> line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">static int frame = 0;
frame++;</pre></div>



<p class="wp-block-paragraph">Combined with accumulation (see challenges!), the image now greatly benefits from the blue noise.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="386" src="https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-1024x386.png" alt="" class="wp-image-1906" style="width:640px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-1024x386.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-300x113.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-768x289.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-897x338.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue-360x136.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/04/animblue.png 1190w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 9: Accumulating over time with blue noise samples.</figcaption></figure>
</div>


<p class="wp-block-paragraph">And with that, we reached the end of the fourth episode. Episode 5 will be about accumulating over time when the camera moves. See you next week!</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> Combine the concepts of this article with those of previous articles in the series to produce a real-time accumulating voxel renderer with colored voxels, glass, mirrors, anti-aliasing, and blue-noise soft shadows, all accumulating to a converged image for a stationary camera.</p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> The sampling problem in this episode is a 2D one: each sample needs two random numbers. Applying blue noise to Fresnel (see episode 2) is a 1D problem, but applying it to a light transport path that involves an area light <em>and</em> a single Fresnel event makes the dimensionality of the path 3. Research how to apply blue noise to paths with an even higher dimensionality.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/?p=1715">Starting point: Voxel ray </a><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">tracing</a><a href="https://jacco.ompf2.com/?p=1715"> template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1755&amp;preview=true">Whitted-style: Reflections, recursion, </a><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">glass</a>.</li>



<li><a href="https://jacco.ompf2.com/?p=1803">Stochastic techniques: Anti-aliasing and soft </a><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">shadows</a>.</li>



<li><strong>Noise reduction: Stratification and blue noise (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 3</title>
		<link>https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/</link>
					<comments>https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 08 May 2024 07:23:37 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1803</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><strong>Stochastic techniques: Anti-aliasing and soft shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">In this article we move beyond <em>Whitted-style</em> ray tracing with some stochastic rendering techniques. This will unlock new and interesting features, such as soft shadows from area lights, motion blur and depth of field. It all starts with anti-aliasing, as this simple technique already uses the ingredients we will need for the more impactful techniques. And finally, we will see how stochastic rendering solves the main problem of Whitted-style ray tracing: Performance.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">As with the previous articles, we start with the standard template for this series, which you can find in its <a href="https://github.com/jbikker/voxpopuli">repository on Github</a>. Let&#8217;s change <code>Renderer::Trace</code> to a smaller version of the code used in <a href="https://jacco.ompf2.com/?p=1755">article 2</a>: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.5f, 0.6f, 1.0f );
    static const float3 L = normalize( float3( 3, 2, 1 ) );
    return max( 0.3f, dot( ray.GetNormal(), L ) );
}</pre></div>



<p class="wp-block-paragraph">When you zoom in on an edge, maybe after taking a screenshot, an issue emerges:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/jaggies.png" alt="" style="width:540px;height:auto"/><figcaption class="wp-element-caption">Figure 1: &#8216;Jaggies&#8217;: rasterization / point sampling artifacts.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The &#8216;jaggies&#8217; on the edges are <em>aliasing artifacts</em>. They result from displaying an image on a computer screen, which is a raster of more or less square pixels. If we zoom in on a small set of pixels, the root cause of the problem emerges.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/onespp.png" alt="" style="width:396px;height:auto"/><figcaption class="wp-element-caption">Figure 2: Point samples detect geometry only at a single point on the area of a pixel.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The pixel colors are supposed to be a representation of the geometry that we can see though a small rectangle. But, the ray tracer <em>samples</em> the geometry using a single ray, here depicted by a yellow dot. So, when a pixel should display a blend of the sky color and a shaded voxel, it <em>actually</em> displays one or the other.</p>



<p class="wp-block-paragraph">Take the bottom right pixel. Based on the sample, that pixel is blue. A better color would be ~90% blue and ~10% grey: This ratio depends on the <em>area</em> of the blue and the grey patches. IN this particular case, this ratio could theoretically be calculated, but this becomes hard when the scene is more complex. We can however <em>estimate</em> it, by using multiple rays per pixel.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/fourspp.png" alt="" style="width:290px;height:auto"/><figcaption class="wp-element-caption">Figure 3: Multi-sampling gives us a coarse estimate of the true color of a pixel.</figcaption></figure>
</div>


<p class="wp-block-paragraph">This time, the bottom right corner more or less accurately estimates the color to be half blue, half grey, since two rays hit the sky, and two rays hit the geometry. The top-right pixel however is still just blue, despite the extra work we spent on it. We can fix this by sending more rays, and as the number of rays approaches infinity, the answer will become correct, no matter how complex the things we &#8216;see&#8217; through the pixel. This technique is called <em>numerical integration</em>. We <em>estimate</em> the energy arriving through a pixel by taking a number of <em>point samples</em>. More samples improve the estimate.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Code</h2>



<p class="wp-block-paragraph">Let&#8217;s implement anti-aliasing with multiple rays per pixel. On line 37 of <code>Renderer::Tick</code> we currently create a single primary ray for each pixel:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r = camera.GetPrimaryRay( (float)x, (float)y );</pre></div>



<p class="wp-block-paragraph">Let&#8217;s make that four rays.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r1 = camera.GetPrimaryRay( (float)x, (float)y );
Ray r2 = camera.GetPrimaryRay( x + 0.5f, (float)y );
Ray r3 = camera.GetPrimaryRay( (float)x, y + 0.5f );
Ray r4 = camera.GetPrimaryRay( x + 0.5f, y + 0.5f );
float3 sample1 = Trace( r1 );
float3 sample2 = Trace( r2 );
float3 sample3 = Trace( r3 );
float3 sample4 = Trace( r4 );
float3 pixel = 0.25f * (sample1 + sample2 + sample3 + sample4);</pre></div>



<p class="wp-block-paragraph">First observation after running this program: This works. The jaggies have substantially been reduced. Second observation: It now runs four times slower. Yeah, ray tracers tend to do that. Luckily, the template lets you remedy that relatively easily. Open up <code>camera.h</code>, and you&#8217;ll see the screen resolution used by the template:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// default screen resolution
#define SCRWIDTH	1280
#define SCRHEIGHT	800
// #define FULLSCREEN
// #define DOUBLESIZE</pre></div>



<p class="wp-block-paragraph">Change the resolution to 640 by 400, and uncomment DOUBLESIZE. This will render every pixel as a 2&#215;2 block, effectively cutting the work the program has to do to 25%.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/aa2x2.png" alt="" style="width:540px"/><figcaption class="wp-element-caption">Figure 4: 2&#215;2 samples per pixel greatly reduce the jaggies.</figcaption></figure>
</div>


<p class="wp-block-paragraph">There is however a different solution to the performance problem, and that solution is a bit more fundamental.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">One Sample</h2>



<p class="wp-block-paragraph">Instead of sending 4, 9, 16, 25 or even infinite rays through each pixel, we can do something clever: We send <em>one ray</em> through every pixel, but, instead of aiming it at a <em>fixed</em> position on the pixel, we aim at a <em>random</em> position. This has two consequences:</p>



<ol class="wp-block-list">
<li>We immediately get our original performance back, because each pixel is calculated using one ray;</li>



<li>Geometry edges are now noisy.</li>
</ol>



<p class="wp-block-paragraph">The code we need looks like this:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
float3 pixel = Trace( r );</pre></div>



<p class="wp-block-paragraph">And the output is noisy, as promised:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/jaggies1spp.png" alt="" style="width:500px"/><figcaption class="wp-element-caption">Figure 5: Random point samples on pixels yield a noisy result.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It turns out that things improve when we send <em>multiple</em> random rays through each pixel. Try the following snippet, starting at line 32:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    float3 pixel( 0 );
    for ( int sample = 0; sample &lt; 8; sample++ )
    {
        Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
        pixel += Trace( r );
    }
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel * 0.125f );
}</pre></div>



<p class="wp-block-paragraph">This produces the following image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/jaggies4spp.png" alt="" style="width:500px"/><figcaption class="wp-element-caption">Figure 6: Multiple random samples show a result that is still noisy, but closer to the correct solution.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It&#8217;s still noisy, but it is approaching the result that we are looking for, similar to the 2&#215;2 raster of samples that we used earlier.</p>



<p class="wp-block-paragraph">This experiment reveals that there is something special about the noisy pixels. More of them get us closer to the correct result, because the <em>probability</em> that a random sample finds a particular color through a pixel is proportional to the area of that particular color. Let that sink in, because it is important. We just replaced the <em>calculation</em> of the area of a sub-pixel feature by the <em>chance</em> that we hit it with a random ray. Or, in math terms, we replaced an <em>integral</em> by the <em>expected value</em> of a random process.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Converge</h2>



<p class="wp-block-paragraph">Now that we know that more random samples improve the quality of the anti-aliasing, it&#8217;s time to add something cool to the ray tracer. We start with a modification to <code>Renderer::Init</code> in <code>renderer.cpp</code>. This function is called once before all frames are drawn and is useful to do things we need only once. Modify it as follows: </p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Renderer::Init()
{
    accumulator = new float3[SCRWIDTH * SCRHEIGHT];
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<p class="wp-block-paragraph">The pixel plotting loop is restored to the single random sample variant:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
    float3 pixel = Trace( r );
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( pixel );
}</pre></div>



<p class="wp-block-paragraph">The <code>accumulator</code> array is pure magic. We use it to calculate multiple samples per pixel <em>over time</em>. It starts empty, with every pixel set to 0. Observe the low-level magic used here: The 32-bit <em>integer</em> number 0, when interpreted as 32-bit floating point data, is also 0.0f, which allows us to quickly zero the large <code>accumulator</code> array. We then add a value for each pixel to it:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
    accumulator[x + y * SCRWIDTH] += Trace( r );
}</pre></div>



<p class="wp-block-paragraph">The value in the accumulator will thus get brighter with each frame. But, if we divide the accumulated values by the number of frames, we will get the correct average. So, just above function <code>Renderer::Tick</code>, we add a line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">static int spp = 1;</pre></div>



<p class="wp-block-paragraph">Then, we add a line just before the <code>#pragma omp</code> parallel line, so that the value is available to all rendering threads:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">const float scale = 1.0f / spp++;</pre></div>



<p class="wp-block-paragraph">Almost there. We now modify the pixel loop so that the average of each accumulated pixel is plotted to the screen:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// trace a primary ray for each pixel on the line
for (int x = 0; x &lt; SCRWIDTH; x++)
{
    Ray r = camera.GetPrimaryRay( x + RandomFloat(), y + RandomFloat() );
    accumulator[x + y * SCRWIDTH] += Trace( r );
    float3 average = accumulator[x + y * SCRWIDTH] * scale;
    screen-&gt;pixels[x + y * SCRWIDTH] = RGBF32_to_RGB8( average );
}</pre></div>



<p class="wp-block-paragraph">Now run <em>this.</em> The result is <em>absolutely perfect</em> anti-aliasing, thanks to some basic probability theory.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/perfectaa.png" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 7: Perfectly converged anti-aliasing for a stationary camera, accumulated over time.</figcaption></figure>
</div>


<p class="wp-block-paragraph">One problem remains: When you move the camera, nothing happens, or at best a massive smear is the result. There&#8217;s an easy fix for that: Whenever the camera moves, we should clear the accumulator, and restart accumulation. Replace the last line of <code>Renderer::Tick</code> with:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (camera.HandleInput( deltaTime ))
{
    spp = 1;
    memset( accumulator, 0, SCRWIDTH * SCRHEIGHT * sizeof( float3 ) );
}</pre></div>



<p class="wp-block-paragraph">That&#8217;s all! Function <code>Camera::HandleInput</code> will let you know when user input changed the view; when this happens, we reset the static <code>spp</code> (&#8216;samples per pixel&#8217;) variable to 1, and clear the values in the accumulator. This time the image is noisy only when the camera moves, and quickly converges when it becomes stationary.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Soft Shadows</h2>



<p class="wp-block-paragraph">With perfect anti-aliasing in place, it turns out to be pretty easy to add soft shadows to the renderer. </p>



<p class="wp-block-paragraph">Soft shadows represent a pretty high end rendering feature. They occur naturally when light is cast by an <em>area light</em>, i.e. any light that is not a point. </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/photoshadows.png" alt="" style="width:534px;height:auto"/><figcaption class="wp-element-caption">Figure 8: Soft-shadows in a photograph.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Even the sun is an area light: In fact, point lights were pretty rare until we got LEDs, which sometimes approach point lights.</p>



<p class="wp-block-paragraph">Some terminology: The soft edge of a soft shadow is called the <em>penumbra</em>, this is the area from which the area light source is partially visible. The part of the shadow for which the light is fully blocked is called the <em>umbra</em>. To calculate a soft shadow in a ray tracer, we are thus interested in the <em>visibility</em> of a light source. For a point light, this is all or nothing: A shadow ray can get there, or it is blocked. For an area light, we may be able to get to some part of the light, or all of it, or some percentage. You probably can see where this is going: If we would fire a shadow ray to a <em>random</em> point on a light source, and we would determine the <em>probability</em> that this ray arrives unobstructed, then this probability can perfectly <em>replace visibility</em>.</p>



<p class="wp-block-paragraph">Let&#8217;s setup a basic area light to play with. The simplest shape is a horizontal rectangle. A random point on such a rectangle is easily obtained:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 RandomPointOnLight()
{
    return float3( RandomFloat() - 1, 3, RandomFloat() - 1 );
}</pre></div>



<p class="wp-block-paragraph">Recall that the world is 1x1x1, located at the origin, so this would be a large plane floating some distance diagonally above it. We use the new <code>RandomPointOnLight</code> function in modified version of the <code>Renderer::Trace()</code> code from the <a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">first article</a>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.4f, 0.5f, 1.0f );
    float3 I = ray.IntersectionPoint();
    float3 L = RandomPointOnLight() - I;
    float distance = length( L );
    L = normalize( L );
    float cosa = max( 0.0f, dot( ray.GetNormal(), L ) );
    Ray shadowRay( I, L, distance );
    if (scene.IsOccluded( shadowRay )) return 0;
    return 20 * ray.GetAlbedo() * cosa / pow2f( distance );
}</pre></div>



<p class="wp-block-paragraph">Using the <code>RandomPointOnLight</code> function we now apply the same magic that allowed us to do anti-aliasing with just <em>one </em>ray. Without the accumulator, things are interesting already: </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/noisy.jpg" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 9: Taking random samples on an area light source yields soft shadows, where the density of the black spots is proportional to the visibility of the light source.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Even with one sample per pixel, the soft shadow already emerges. Every individual sample is still &#8216;hit&#8217; or &#8216;miss&#8217;, but <em>on average</em>, these samples capture the smoothly varying visibility of the area light. That becomes even more clear when we use the accumulator:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/gorgeous.png" alt="" style="width:600px"/><figcaption class="wp-element-caption">Figure 10: Combining the accumulator with point samples on the pixel and the light yields a perfect result.</figcaption></figure>
</div>


<p class="wp-block-paragraph">That looks just gorgeous. And here comes the kicker: <em>One </em>sample through every pixel not only gets us this beautiful soft shadow; we <em>still </em>have the anti-aliasing as well! And all of that with an absolutely tiny piece of code.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">And Finally</h2>



<p class="wp-block-paragraph">There&#8217;s one last thing to introduce here. So far we have been working with rather boring test data. To improve on that situation I have converted a 3D mesh from author <a href="https://sketchfab.com/PabloDebusschere">PabloDebusschere</a> on Sketchfab to voxels and compressed it using zlib. You can find the resulting file, <code>viking.bin</code>, in the assets folder. To load it, replace <code>Scene</code> constructor by the following code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Scene::Scene()
{
    // allocate room for the world
    grid = (uint*)MALLOC64( GRIDSIZE3 * sizeof( uint ) );
    gzFile f = gzopen( "assets/viking.bin", "rb" );
    int3 size;
    gzread( f, &amp;size, sizeof( int3 ) );
    gzread( f, grid, size.x * size.y * size.z * 4 );
    gzclose( f );
}</pre></div>



<p class="wp-block-paragraph">After carefully picking a good looking camera view, the result is as shown below. </p>



<p class="wp-block-paragraph">And with that we end this week&#8217;s episode. In the next episode we will look at methods to reduce the noise that is clearly visible when the camera is moving. See you then! </p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="563" src="https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-1024x563.jpg" alt="" class="wp-image-1965" style="width:600px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-1024x563.jpg 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-300x165.jpg 300w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-768x422.jpg 768w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-1222x672.jpg 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-897x493.jpg 897w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1-360x198.jpg 360w, https://jacco.ompf2.com/wp-content/uploads/2024/05/viking-1.jpg 1244w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><figcaption class="wp-element-caption">Figure 11: Viking military outpost scene by <a href="https://sketchfab.com/PabloDebusschere">PabloDebusschere</a> on Sketchfab.</figcaption></figure>
</div>


<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1.</strong> Combine the concepts of this article with those described in article 1 and 2. Concrete, add support for multiple lights, as well as reflective and refractive materials to produce high quality images. Make sure to share some online. And if you made a game at the end of article 1, by now it should look extremely nice!</p>



<p class="wp-block-paragraph"><strong>Challenge 2.</strong> Now that everything is random, we can solve the &#8216;splitting ray&#8217; issue of Whitted-style ray tracing. For your glass material, chose randomly between the reflected and refracted directions. The probability of each should of course be determined by Fresnel.</p>



<p class="wp-block-paragraph"><strong>Challenge 3.</strong> You can find several <code>.bin</code> files in the <code>assets</code> folder. Create some code that adds them to a world, even when their size is not exactly 128x128x128 voxels, as with the Viking scene. You can even modify <code>Scene::Scene</code> to load several <code>.bin</code> files, perhaps at a custom location in the world.</p>



<p class="wp-block-paragraph"><strong>Challenge 4.</strong> In <a href="https://jacco.ompf2.com/2022/05/27/how-to-build-a-bvh-part-8-whitted-style/">another series of articles</a> on <a href="https://jacco.ompf2.com/">this blog</a> you can find instructions for adding a skydome to your scene. Follow the instructions. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><strong>Stochastic techniques: Anti-aliasing and soft shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 2</title>
		<link>https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/</link>
					<comments>https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 01 May 2024 09:53:58 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1755</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows.</a></li>



<li><strong>Whitted-style: Reflections, recursion, glass (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">To the basic ray tracer of the first article we will now add reflections (including recursive reflections) and glass, to turn it into a full <em>Whitted-style</em> ray tracer. This requires the concept of <em>materials</em>, so we can differentiate between regular, mirror and glass voxels. We will test the new features in a fresh test scene, the code for which you will find in the next paragraph.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">For this article we will use the unmodified <a href="https://github.com/jbikker/voxpopuli">template code</a> as a starting point. You are encouraged to combine concepts from this second article with the lights and shadows introduced in the first article, but this is not required.</p>



<p class="wp-block-paragraph">Let&#8217;s first make some modifications, for the purpose of this article. Replace the world creation code in <code>Scene::Scene</code> in file <code>scene.cpp</code>, line 30:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for (int z = 0; z &lt; 128; z++)
    for (int y = 0; y &lt; 128; y++) for (int x = 0; x &lt; 128; x++ )
        if (x &lt; 2 || x &gt; 125 || z &gt; 125 || y &lt; 2 || y &gt; 125)
            Set( x, y, z, 0xeeeeee );
        else if (y &gt; 30 &amp;&amp; y &lt; 50 &amp;&amp; z &gt; 50 &amp;&amp; z &lt; 70 &amp;&amp; x &gt; 20)
            if (x &lt; 40) Set( x, y, z, 0xff7777 );
            else if (x &gt; 55 &amp;&amp; x &lt; 75) Set( x, y, z, 0xaaffaa );
            else if (x &gt; 90 &amp;&amp; x &lt; 110) Set( x, y, z, 0x7777ff );</pre></div>



<p class="wp-block-paragraph">Next, replace the <code>Renderer::Trace</code> function in <code>renderer.cpp</code> with:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3( 0.5f, 0.6f, 1.0f ); // or a fancy sky color
    float3 N = ray.GetNormal();
    float3 I = ray.IntersectionPoint();
    float3 albedo = ray.GetAlbedo();
    static const float3 L = normalize( float3( 3, 2, 1 ) );
    return albedo * max( 0.3f, dot( N, L ) );
}</pre></div>



<p class="wp-block-paragraph">The result is a basic room scene with three floating cubes, each with a different color.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="612" src="https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-1024x612.png" alt="" class="wp-image-1792" style="width:512px" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-1024x612.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-300x179.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-768x459.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-897x536.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14-360x215.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/03/image-14.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Reflections</h2>



<p class="wp-block-paragraph">In the first article we saw that ray tracing is all about light transport between light sources and the camera. A ray through a pixel finds an object; from there, a shadow ray attempts to reach the light source. If there is no obstacle, the object seen through the pixel is illuminated by the light source. But what if the object is a <em>mirror?</em> </p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/reflsitu.png" alt=""/></figure>



<p class="wp-block-paragraph">Like other surfaces, a mirror reflects light. However: Only in very specific directions. In fact, for a perfect mirror, a single incoming direction is linked to a single outgoing direction. In the right image, one of the two rays that hit the mirror ball bounces to the green sphere. The corresponding pixel will thus show a green sphere, mirrored in a dark, shiny sphere. </p>



<p class="wp-block-paragraph">Note that the green sphere reflects green light because it is visible from the light source. There is thus light transport: From the light to the green sphere, then via the mirror to the pixel, and finally to the camera.</p>



<p class="wp-block-paragraph">To add reflections to the voxel ray tracer, we need two things:</p>



<ol class="wp-block-list">
<li>A way to calculate the reflected direction, so we can spawn a new ray;</li>



<li>A way to detect that an object is reflective.</li>
</ol>



<p class="wp-block-paragraph">Regarding that second point on the list: We will introduce the concept of <em>materials</em>. A mirror is fundamentally different from our basic (&#8216;diffuse&#8217;) material. And, later we will add a third type of material, which is used for glass and water.</p>



<p class="wp-block-paragraph">Let&#8217;s take another look at the world creation code. We used four &#8216;HTML&#8217; colors, which are in fact simply 24-bit hexadecimal numbers: <code>0xEEEEEE</code> for (almost) white, <code>0xFF7777</code> for (pastel) red, <code>0xAAFFAA</code> for green and <code>0x7777FF</code> for blue. A voxel actually can store 32-bit data, so there&#8217;s some headroom. Let&#8217;s agree that <code>0x00xxxxxxxx</code> means that we have a diffuse material with color xxxxxx, and that <code>0x01xxxxxx</code> indicates that the material is in fact reflective. So, we can make the floor reflective by changing its color to 0x019999BB:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">...
if (x &lt; 2 || x &gt; 125 || z &gt; 125 || y &lt; 2 || y &gt; 125)
    Set( x, y, z, y == 1 ? 0x19999bb : 0xffffff );
...</pre></div>



<p class="wp-block-paragraph">Now, in <code>Renderer::Trace</code> we can easily detect the mirror material. Replace the last line, which returns the shaded albedo, with the following construct:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if ((ray.voxel &gt;&gt; 24) == 1)
{
    // mirror material
    // TODO
}
else
{
    // diffuse material
    return albedo * max( 0.3f, dot( N, L ) );
}</pre></div>



<p class="wp-block-paragraph">The bitshift operator <code>&gt;&gt;</code> shifts the contents of the 32-bit <code>ray.voxel</code> variable to the right by the specified number of bits. This effectively makes the top 8 bits, in which we stored the material type, the only remaining bits. </p>



<p class="wp-block-paragraph">To calculate the reflected color we need a reflection ray. The <em>origin</em> of this ray is simply the end of the primary ray. The <em>direction</em> is a bit more involved. The reflection direction depends on the orientation of the surface we hit, and thus we use the local normal vector, like we did with the calculation of the shading. The formula for vector reflection is:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">R=D-2N(D \cdot N)</span>  </p>



<p class="wp-block-paragraph">Here, <span class="wp-katex-eq" data-display="false">D</span> is the direction of the incoming ray and <span class="wp-katex-eq" data-display="false">R</span> is the reflected direction. The reflected ray can now be constructed:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R = ray.D - 2 * N * dot( ray.D, N );
Ray r( I, R );</pre></div>



<p class="wp-block-paragraph">Things get interesting when we actually use this new ray. Behold the final reflection code:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if ((ray.voxel &gt;&gt; 24) == 1)
{
    // mirror material
    float3 R = ray.D - 2 * N * dot( ray.D, N );
    return albedo * Trace( Ray( I, R ) );
}</pre></div>



<p class="wp-block-paragraph">We use a <em>recursive </em>call to Renderer::Trace to handle the reflection. This is powerful: Whatever we find at the end of the reflected ray will be handled by <em>code we already have</em>. This will work if we find a diffuse surface: in that case, the existing code in Trace will cast a shadow ray. It will <em>also </em>work if we find <em>another mirror</em>. In that case, we just bounce again.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/reflfloor.png" alt="" style="width:512px"/></figure>
</div>


<p class="wp-block-paragraph">With great power comes great responsibility. It is not hard to setup a scene where rays may bounce infinitely (there&#8217;s a reason I suggested to make just the floor reflective). We&#8217;ll need to somehow limit how often we bounce. For that, we can use the optional &#8216;depth&#8217; argument of <code>Renderer::Trace</code>. By default it is called with 0. We can increase it for each recursion step:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return albedo * Trace( Ray( I, R ), depth + 1 );</pre></div>



<p class="wp-block-paragraph">Now it is straight-forward to cap recursion. Just add a line at the start of the <code>Trace</code> function:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if (depth == 5) return{ 0 };</pre></div>



<p class="wp-block-paragraph">Instead of <code>5</code> you can use larger (or smaller) numbers. Just be careful: Many bounces will bring down the performance of the ray tracer.</p>



<p class="has-text-align-center wp-block-paragraph"> &#8211; o &#8211; </p>



<h2 class="wp-block-heading">Refraction</h2>



<p class="wp-block-paragraph">The final feature for this article is <em>glass</em>. In the real world, glass has surprisingly complex behavior. It transmits light, but it is also reflective. To make matters worse, reflection doesn&#8217;t just happen on the outside of a glass object, but also on the inside, when we try to leave the object.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/fresnelsitu.png" alt=""/><figcaption class="wp-element-caption">Left: The water surface is reflective when seen from below. Right: Also when seen from above.</figcaption></figure>



<p class="wp-block-paragraph">So, in order to add <em>refraction</em> to the ray tracer, we need three things:</p>



<ol class="wp-block-list">
<li>A <em>reflected</em> ray</li>



<li>A <em>refracted </em>(or: <em>transmitted)</em> ray, into the glass or water</li>



<li>A way to <em>blend</em> the two.</li>
</ol>



<p class="wp-block-paragraph">The reflection is easy: This is identical to the mirror functionality we already added.</p>



<p class="wp-block-paragraph">For the direction of a refracted ray we need to look at the work of an old Dutch scientist, named Willebrord Snel van Royen, better known as &#8216;Snellius&#8217;, or just &#8216;Snell&#8217;. Snell has a physics law named after him that looks like this:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">\frac{sin \theta_i}{sin \theta_o} = \frac{v_1}{v_2}</span></p>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Here, <span class="wp-katex-eq" data-display="false">\theta_i</span> (&#8220;theta i&#8221;) is the angle at which a ray arrives at a surface (relative to the normal); <span class="wp-katex-eq" data-display="false">\theta_o</span> is the angle at which the ray leaves the surface at the other side, and <span class="wp-katex-eq" data-display="false">v_1</span> and <span class="wp-katex-eq" data-display="false">v_2</span> are the speeds at which light travels on either side of the surface. Instead of <span class="wp-katex-eq" data-display="false">v_1</span> and <span class="wp-katex-eq" data-display="false">v_2</span> we can also use <span class="wp-katex-eq" data-display="false">n_1</span> and <span class="wp-katex-eq" data-display="false">n_2</span>, i.e. the <em>refraction indices</em> of the media on either sides of the surface.</p>



<p class="wp-block-paragraph">That&#8217;s great, but we are looking for a vector, not an angle. To obtain the refracted vector, we can borrow some formulas from the <a href="https://registry.khronos.org/OpenGL-Refpages/gl4/html/refract.xhtml">glsl reference manual</a>, which states that it is calculated as follows:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">k = 1 - eta * eta * (1 - dot(N, D) * dot(N, D));
if (k &lt; 0)
    R = 0;
else
    R = eta * D - (eta * dot(N, D) + sqrtf(k)) * N;</pre></div>



<p class="wp-block-paragraph">And that is actually useful for our purposes. Variable &#8216;eta&#8217;, by the way, is calculated as <span class="wp-katex-eq" data-display="false">n_1 / n_2</span>. For air, <span class="wp-katex-eq" data-display="false">n_1</span> is simply 1.0. For glass, <span class="wp-katex-eq" data-display="false">n_2</span> is approximately 1.46. So, when going from air to glass, eta is 1/1.46. But, in the opposite direction eta is 1.46/1. This is relevant when we leave a block of glass on the other side. </p>



<p class="wp-block-paragraph">Refractive indices of more materials can be found <a href="https://en.wikipedia.org/wiki/List_of_refractive_indices">here</a>.</p>



<p class="wp-block-paragraph">The final ingredient is the blending of energy returned by the reflected and refracted rays. Another scientist studied this topic: His name is Fresnel. His &#8216;Fresnel Equations&#8217; are intimidating, but luckily, someone (mr. Schlick) made a simpler approximation, which is gets pretty close:</p>



<p class="wp-block-paragraph"><span class="wp-katex-eq" data-display="false">f=R_0+(1-R_0)(1-(D \cdot N))^5</span>, where <span class="wp-katex-eq" data-display="false">R_0=(\frac{n_1-n_2}{n_1+n_2})^2</span></p>



<p class="wp-block-paragraph">We can now put everything together in the ray tracer. Let&#8217;s label the new &#8216;glass&#8217; material &#8216;<code>02</code>&#8216; in the scene, to differentiate it from the regular material &#8216;<code>00</code>&#8216; and the mirror material &#8216;<code>01</code>&#8216;. To make the green cube a glass cube we change its color to <code>0x02AAFFAA</code>. We then detect the new material in <code>Renderer::Trace</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">if ((ray.voxel &gt;&gt; 24) == 2)
{
    // glass material
    // TODO
}</pre></div>



<p class="wp-block-paragraph">We start the new material code with specifying <span class="wp-katex-eq" data-display="false">n_1</span> and <span class="wp-katex-eq" data-display="false">n_2</span>. And note: If we hit the plane that separates air and glass from <em>within</em> the glass, we need to swap <span class="wp-katex-eq" data-display="false">n_1</span> and <span class="wp-katex-eq" data-display="false">n_2</span>. In the template, we can just &#8216;ask&#8217; the ray if this is the case.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float n1 = 1.0f, n2 = 1.46f; // ior for glass
if (ray.inside) swap( n1, n2 );</pre></div>



<p class="wp-block-paragraph">Next, we prepare for calculating the refracted ray direction. Efficiently calculating <code>k</code> requires some care. The dot product between <span class="wp-katex-eq" data-display="false">N</span> and <code>-ray.D</code> is used a few times and should thus be precalculated. Also note that, instead of the generic &#8216;std::powf&#8217; function (which is <em>very</em> costly), we use a simple function from the template to calculate the square of the dot product.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float d = dot( N, -ray.D );
float eta = n1 / n2;
float k = 1 - eta * eta * (1 - pow2f( d ));</pre></div>



<p class="wp-block-paragraph">Now we can trace the refracted ray, if <code>k</code> is greater than <code>0</code>.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 reflected( 0 ), refracted( 0 );
if (k &gt; 0)
{
    float3 R = eta * ray.D + (eta * d - sqrtf( k )) * N;
    refracted = Trace( Ray( I, R ), depth + 1 );
}</pre></div>



<p class="wp-block-paragraph">As discussed, glass also is reflective. This uses the same logic we have seen before.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 R = ray.D - 2 * N * d;
reflected = Trace( Ray( I, R ), depth + 1 );</pre></div>



<p class="wp-block-paragraph">And finally, we blend reflection and refraction using Fresnel. Something special happens when refraction is not possible: We get <em>total internal reflection</em>. In that case, the reflected ray gets a <span class="wp-katex-eq" data-display="false">1.0</span> weight. We can detect this situation by looking at variable <code>k</code>, which should be greater than <code>0</code>.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float R0 = pow2f( (n1 - n2) / (n1 + n2) );
float fresnel = k &gt; 0 ? R0 + (1 - R0) * pow5f( 1 - d ) : 1;
return albedo * (fresnel * reflected + (1 - fresnel) * refracted);</pre></div>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/glassworx.png" alt="" style="width:512px"/></figure>
</div>


<p class="wp-block-paragraph">And there it is&#8230; A pretty complex block, with light going in, changing direction, getting reflected on the inside, and so on. At each surface interaction the path splits off a reflected and refracted ray, so be gentle with that recursion depth!</p>



<p class="has-text-align-center wp-block-paragraph"> &#8211; o &#8211; </p>



<h2 class="wp-block-heading">Whitted</h2>



<p class="wp-block-paragraph">We now have a full implementation of the famous paper by Turner Whitted, which he wrote in 1980: &#8220;An Improved Illumination Model for Shaded Display&#8221;. You can find a copy of the paper <a href="https://www.cs.drexel.edu/~deb39/Classes/Papers/p343-whitted.pdf">here</a>. The groundbreaking idea of the paper is that we can &#8216;do graphics&#8217; by applying principles from the field of optics, including shadows, reflection and refraction. The technique is ever since known as <em>Whitted-style ray tracing</em>. Now you know!</p>



<p class="has-text-align-center wp-block-paragraph"> &#8211; o &#8211; </p>



<h2 class="wp-block-heading">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1</strong>: Combine the concepts of this article with those from the first article. In short, add point lights and shadows, and make them work together with the recursive reflections and refractions.</p>



<p class="wp-block-paragraph"><strong>Challenge 2</strong>: The way we blended between refraction and reflection can also be applied to materials that are partially diffuse and partially reflective. Create a material for which a shadow ray <em>and </em>a reflection ray is cast, and blend the two layers using a weight of 50% for each.</p>



<p class="wp-block-paragraph"><strong>Challenge 3</strong>: The template comes with <a href="https://github.com/ocornut/imgui">ImGui</a> integration. Use this to make the refraction index of the glass configurable at run-time. Find a way to change properties of other materials via the interface as well.</p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/">Starting point: Voxel ray tracing template code. Lights and shadows.</a></li>



<li><strong>Whitted-style: Reflections, recursion, glass (this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Ray Tracing with Voxels in C++ Series &#8211; Part 1</title>
		<link>https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/</link>
					<comments>https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Wed, 24 Apr 2024 12:43:02 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1715</guid>

					<description><![CDATA[In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this series we build a physically based renderer for a dynamic voxel world. From &#8216;Whitted-style&#8217; ray tracing with shadows, glass and mirrors, we go all the way to &#8216;unbiased path tracing&#8217; &#8211; and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is <a href="https://github.com/jbikker/voxpopuli">available on Github</a> and is written in easy-to-read &#8216;sane C++&#8217;.</p>



<p class="wp-block-paragraph">This series consists of nine articles. Contents:  <em>(tentative until finalized)</em></p>



<ol class="wp-block-list">
<li><strong>Starting point: Voxel ray tracing template code. Lights and shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.   </li>
</ol>



<h2 class="wp-block-heading">In This Article&#8230;</h2>



<p class="wp-block-paragraph">In this first article we will use the bare-bones template and add some color to it, as well as lights, and shadows. Shadows will be calculated using rays to the light sources. If these concepts are already clear to you, feel free to skip to the <a href="#challenges"><strong>challenges</strong></a> at the end of the article, or to the next article <em>(once it is released)</em>: Each article starts with the same template code, so you can jump in at any point.</p>



<h2 class="wp-block-heading">Starting Point</h2>



<p class="wp-block-paragraph">For this series we will use a somewhat unusual starting point: a ready-made template that renders a basic image using ray tracing. The scene is a small voxel world, procedurally generated. You can find this template in <a href="https://github.com/jbikker/voxpopuli">its github repo</a>. It runs out-of-the-box on a Windows system: just open the .sln file in Microsoft Visual Studio <a href="https://visualstudio.microsoft.com/vs/community/">Community Edition</a> and press F5 to build and run it.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/barebones.png" alt="" style="width:414px;height:auto"/><figcaption class="wp-element-caption">Figure 1: Output of the unmodified template: 128³ voxels with color-coded normals, and 50 million rays per second.</figcaption></figure>
</div>


<p class="wp-block-paragraph"><em><strong>Note: </strong>Compared to starting &#8216;from scratch&#8217;, the template has the benefit that we quickly get to the interesting ray tracing topics: shadows, reflections, fancy cameras and so on. At the same time, the template is simple enough to make low-level optimizations worthwhile. Article 8 exploits this as we add a multi-level grid to improve the performance of the base code.</em></p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211;</p>



<h2 class="wp-block-heading">A Brief Tour</h2>



<p class="wp-block-paragraph">In its pure form, <em>ray tracing</em> is a process that produces an image from a 3D scene by following the path that light takes, from a light source, to a camera, or rather: in the opposite direction.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/shdsituation.png" alt=""/><figcaption class="wp-element-caption">Figure 2, left: primary rays finding the nearest object. Right: using shadow rays to establish light transport.</figcaption></figure>



<p class="wp-block-paragraph">This is shown in the left image. The camera (or eye) looks at pixels on a screen. This is simulated with a &#8216;ray&#8217;, i.e. a line of (potentially) infinite length, originating at the camera. The ray continues until it encounters an object. The first object along the ray is the object we &#8216;see&#8217; through the pixel. Some rays hit nothing; they disappear into the void and do not bring back any light. In that case we can plot a black pixel, or perhaps a blue one, to simulate the sky.</p>



<p class="wp-block-paragraph">You can find this functionality implemented in source file <code>renderer.cpp</code>, in the <code>Renderer::Tick</code> function. The code in this function loops over the pixels on the screen, creates a primary ray for each, and uses the <code>Renderer::Trace</code> function to determine what the color of the pixel should be. The <code>Renderer::Trace</code> function finds the nearest intersection of the ray and the scene. If nothing is found, it simply returns <code>float3(0)</code>, i.e. black. Otherwise, it calculates a color for the hitpoint, but this functionality is not complete yet.</p>



<p class="wp-block-paragraph"><em><strong>Note:</strong> We&#8217;re intentionally skipping details here. Line 31, for example: This line assigns each row of pixels to a thread, using OpenMP. This way, the renderer runs significantly faster on a multi-core CPU. And, on line 39, a floating point color is converted to an integer color. Monitors expect integer values, but ray tracing requires floating point colors for range and precision. More on that later.</em></p>



<p class="wp-block-paragraph">For the rays that did hit an object we now need to determine if light flows via that object. This is illustrated in the right image. New rays are created from the hitpoint to the light source. If these rays get to the light without encountering any obstructions, we know that the surface may reflect light, via the pixel, to the camera.</p>



<p class="wp-block-paragraph">Determining the flow of light via the object is what ray tracing is all about. Initially, the light is a simple <em>point light</em>, and the object has a simple material. But soon, we will be illuminating using many complex lights, and reflect via subtle materials. Light will travel via mirrors and through glass. The camera will have an aperture, which causes depth of field.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/mcrt.png" alt="" style="width:411px;height:auto"/><figcaption class="wp-element-caption">Figure 3: Minecraft with ray tracing effects.</figcaption></figure>
</div>


<p class="wp-block-paragraph">Rendering images like the above one is not all that hard. On top of that, we can do it in real-time, on a CPU. Have a look at the code in <code>scene.cpp</code>: The code in there is all that is needed to replicate the behavior of modern ray tracing enabled GPUs. It may not be the simplest code, but at 150-ish lines of code it is hardly a vast code base either.</p>



<p class="wp-block-paragraph">This concludes our brief tour. And now, it&#8217;s time to establish <em>light transport</em>.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Into the Light</h2>



<p class="wp-block-paragraph">Let&#8217;s start by adding a light source to the world. The simplest light is a<em> point light:</em> all it needs is a <em>position </em>and a <em>color</em>. So, just above <code>Renderer::Trace</code> we add:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 pos( 1, 1, 1 );
float3 color( 1, 1, 1 );</pre></div>



<p class="wp-block-paragraph">A word about the light position <code>pos</code>: In the template, the voxel object occupies space between x=0..1, y=0..1 and z=0..1. The whole shape is thus a 1x1x1 cube. The size of the world can be changed in <code>scene.h</code>, where <code>WORLDSIZE</code> is set to <code>128</code>. Changing this value does however not change the size of the voxel object; it merely changes its resolution. Funny thing is: <em>that&#8217;s the same thing.</em> We can simply bring the camera closer to make the object <em>look</em> larger, or move it back to make it look smaller.</p>



<p class="wp-block-paragraph">So, a light at x=1, y=1 and z=1 is located on one of the corners of the voxel object. </p>



<p class="wp-block-paragraph">Note that the <em>color</em> of the light is also its <em>intensity:</em> Because we use floating point colors, a bright yellow light might have a color like <code>float3(100,100,20)</code>. Obviously, for a nearby light that would be blinding, but if the light is very far away, such a color is not extreme at all.</p>



<p class="wp-block-paragraph">The effect of light on a point on the surface of a voxel depends on four factors:</p>



<ol class="wp-block-list">
<li>The <em>distance</em> between the light and the surface point;</li>



<li>The <em>brightness</em> and <em>color</em> of the light source;</li>



<li>The <em>orientation</em> of the surface to the light;</li>



<li>The mutual <em>visibility</em> of the light and the surface point.</li>
</ol>



<p class="wp-block-paragraph">And, since we are interested in how much light the surface point reflects towards the camera, we must also take into account the <em>color</em> of the material (in ray tracing jargon: the <em>albedo</em>).</p>



<p class="wp-block-paragraph">Let&#8217;s see what information we have inside <code>Renderer::Trace</code> to work with.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 Renderer::Trace( Ray&amp; ray, int depth, int, int )
{
    scene.FindNearest( ray );
    if (ray.voxel == 0) return float3(0); // or a fancy sky color
    float3 N = ray.GetNormal();
    float3 I = ray.IntersectionPoint();
    float3 albedo = ray.GetAlbedo();
    return (N + 1) * 0.5f;
}</pre></div>



<p class="wp-block-paragraph">To calculate the <strong>distance </strong>between the light and the intersection point, we create a vector between the two positions, and take its length:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float3 L = pos - I;
float distance = length( L );</pre></div>



<p class="wp-block-paragraph">With this information we evaluate the first factor on our list: <em>Distance attenuation.</em> The strength of a light decreases by the squared distance, so we scale by <span class="wp-katex-eq" data-display="false">1/distance^2</span>.</p>



<p class="wp-block-paragraph">The vector to the light, <span class="wp-katex-eq" data-display="false">L</span>, is also used to take into account the <em>orientation </em>of the surface towards the light. For this we take the dot product between the surface normal <span class="wp-katex-eq" data-display="false">N</span> and the normalized vector <span class="wp-katex-eq" data-display="false">L</span>. This value becomes negative when the light is behind the surface, so we clamp it to zero.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">float cosa = max( 0.0f, dot( N, normalize( L ) ) );</pre></div>



<p class="wp-block-paragraph">Putting everything together, we can now calculate the light reflected by the surface:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">return color * albedo * (1 / (distance * distance)) * cosa;</pre></div>



<p class="wp-block-paragraph"><code>Renderer::Trace</code> now produces the following image:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/newlight.png" alt="" style="width:527px;height:auto"/><figcaption class="wp-element-caption">Figure 4: Basic lighting on the voxels.</figcaption></figure>
</div>


<p class="wp-block-paragraph">The only thing missing is <em>shadows</em>. We need to find out if the light is visible from the intersection point.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Into the Shadows</h2>



<p class="wp-block-paragraph">For that we use a new ray: the <em>shadow ray</em>. It&#8217;s a bit different from the primary ray that we cast from the camera through a pixel: instead of detecting the nearest object along an infinite line, a shadow ray merely detects an obstacle between two points. All it needs to give us is a yes/no answer: can we get there? And: The ray is just as long as the distance between the intersection point and the light; we are not interested in geometry beyond the light source.</p>



<p class="wp-block-paragraph">The template provides shadow ray functionality, in the form of the <code>Scene::IsOccluded</code> function. It takes a <code>Ray</code>, and it returns a boolean.</p>



<p class="wp-block-paragraph">We can set up the shadow ray and cast it into the scene:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Ray shadowRay( I, L, distance );
if (scene.IsOccluded( shadowRay )) return float3( 0 );</pre></div>



<p class="wp-block-paragraph">Placing this before the line that returned the reflected light gets us shadows.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/blackvox.png" alt="" style="width:552px;height:auto"/><figcaption class="wp-element-caption">Figure 5: Lighting and shadows.</figcaption></figure>
</div>


<p class="wp-block-paragraph">As you can see, there is a lot of pitch-black pixels: the &#8216;sky&#8217; is black, and so are the shadows. Fixing the sky is easy: we can for example return <code>float3( 0.7f, 0.8f, 1 )</code> instead of <code>float3( 0 )</code>. To fix the black shadows, we should add <em>more</em> lights. With just the single source of light, blackness is a logical consequence. See for example this photo of Saturn, which is also illuminated (almost exclusively) by a single point light.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/nasa.png" alt="" style="width:513px;height:auto"/><figcaption class="wp-element-caption">Figure 6: Saturn illuminated by the sun, with (almost) hard shadows on the rings. Image: JPL/NASA</figcaption></figure>
</div>


<p class="wp-block-paragraph">Scenes on Earth rarely have pitch black shadows. There is always a source of light: the sky, distant light sources or subtle reflections between objects. How to render this properly is a topic for another day.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Beyond Black and White</h2>



<p class="wp-block-paragraph">The pictures we have rendered so far are all black and white. This is inevitable: The light we added is white, and the voxels are all white, since that is really the only color ever returned by <code>Ray::GetAlbedo()</code>. To do something about this, we have to look into the Creation of the World.</p>



<p class="wp-block-paragraph">This monumental event is handled by the code in the <code>Scene</code> constructor, which starts on line 23 of file <code>scene.cpp</code>. The world in the template consists of 128x128x128 voxels. Each voxel stores a 32-bit value. If this value is <code>0</code>, the voxel is considered to be empty space. All other voxels are set to <code>0xFFFFFF</code>, which in a HTML editor would be the color white. We can swap this uniform whiteness for an orange gradient based on the y-coordinate in the world:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">Set( x, y, z, n &gt; 0.09f ? 0x020101 * y : 0 );</pre></div>



<p class="wp-block-paragraph">Together with a slightly yellow light source and a blue sky, the world now looks a lot nicer.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/orangevox.png" alt="" style="width:572px;height:auto"/><figcaption class="wp-element-caption">Figure 7: Shading, shadows and better colors.</figcaption></figure>
</div>


<p class="wp-block-paragraph">It&#8217;s time to finish this article. In the next section you will find some (totally optional) challenges to practice with the theory presented here. In the next article we will add reflections, glass and a more realistic sky to the world.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading" id="challenges">Challenges</h2>



<p class="wp-block-paragraph"><strong>Challenge 1:</strong> Increase the resolution of the world to 256x256x256. Add three freely floating cubes of 16x16x16 voxels each to the world: one green, one red, one blue cube. <strong>Note:</strong> Generating the world will now take pretty long: it will help to cache the world to disk and load it from a file on subsequent runs.</p>



<p class="wp-block-paragraph"><strong>Challenge 2:</strong> Add support for multiple light sources to <code>Renderer::Trace</code>. Use this to add a red, a green and a blue light. Demonstrate that overlapping the three light colors creates white light. Make the lights dynamic and give them interesting paths.</p>



<p class="wp-block-paragraph"><strong>Challenge 3</strong>: Replace the world generation code by something creative. This could be a mathematical shape, or a 3D room, or something you load from a <a href="https://ephtracy.github.io/">MagicaVoxel</a> file.</p>



<p class="wp-block-paragraph"><strong>Challenge 4:</strong> Produce a minimalist game in the voxel world. For example: Recreate <a href="https://www.ponggame.org/">Pong</a>. Later on, the dynamic game world will be a great test scenario for newly added functionality.</p>



<p class="has-text-align-center wp-block-paragraph">&#8211; o &#8211; </p>



<h2 class="wp-block-heading">Etc.</h2>



<p class="wp-block-paragraph">If you want to share some of your work, consider posting on X about it. You can also follow me there <em>(<a href="https://twitter.com/j_bikker">@j_bikker</a>)</em>, or contact me at <a href="mailto:bikker.j@gmail.com">bikker.j@gmail.com</a>.</p>



<p class="wp-block-paragraph"><strong>Want to read more about computer graphics?</strong> Also on this blog:</p>



<ul class="wp-block-list">
<li><a href="https://jacco.ompf2.com/2022/04/13/how-to-build-a-bvh-part-1-basics/">How to build a BVH series</a></li>



<li><a href="https://jacco.ompf2.com/2020/04/07/speeding-up-lighthouse-2/">Speeding up the Lighthouse 2 renderer</a></li>



<li><a href="https://jacco.ompf2.com/2020/03/18/opt1profiling/">Software Optimization</a></li>
</ul>



<p class="wp-block-paragraph">Other articles in the &#8220;Ray Tracing with Voxels in C++&#8221; series:</p>



<ol class="wp-block-list">
<li><strong>Starting point: Voxel ray tracing template code. Lights and shadows</strong> <strong>(this article).</strong></li>



<li><a href="https://jacco.ompf2.com/2024/05/01/ray-tracing-with-voxels-in-c-series-part-2/">Whitted-style: Reflections, recursion, glass</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/08/ray-tracing-with-voxels-in-c-series-part-3/">Stochastic techniques: Anti-aliasing and soft shadows</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/15/ray-tracing-with-voxels-in-c-series-part-4/">Noise reduction: Stratification, blue noise</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/22/ray-tracing-with-voxels-in-c-series-part-5/">Converging under movement: Reprojection</a>.</li>



<li><a href="https://jacco.ompf2.com/2024/05/29/ray-tracing-with-voxels-in-c-series-part-6/">Path tracing: Basics first; then: Importance Sampling</a>.</li>



<li>Denoising fundamentals.</li>



<li>Acceleration structures: Extending the grid to a multi-level grid.</li>



<li>Acceleration structures: Adding a TLAS.    </li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/04/24/ray-tracing-with-voxels-in-c-series-part-1/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>Reprojection in a Ray Tracer</title>
		<link>https://jacco.ompf2.com/2024/01/18/reprojection-in-a-ray-tracer/</link>
					<comments>https://jacco.ompf2.com/2024/01/18/reprojection-in-a-ray-tracer/#respond</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Thu, 18 Jan 2024 08:53:54 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1679</guid>

					<description><![CDATA[This is a short blog post on reprojection. In it, I describe an alternative to the commonly...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This is a short blog post on reprojection. In it, I describe an alternative to the commonly used method involving camera matrices. I argue that this method is more suitable for ray tracing. Ray tracing typically relies less on matrices, and operates mostly in world space.</p>



<p class="wp-block-paragraph">Reprojection is commonly used to reduce noise for stochastic effects, i.e. techniques involving randomness, such as soft shadows, depth of field, motion blur and even anti-aliasing. There is a nice <a href="https://www.shadertoy.com/view/ldtGWl" data-type="link" data-id="https://www.shadertoy.com/view/ldtGWl">Shadertoy</a> that illustrates the concept:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="604" src="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1024x604.png" alt="" class="wp-image-1680" style="width:525px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1024x604.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-300x177.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-768x453.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1536x906.png 1536w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1222x721.png 1222w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-897x529.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-360x212.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image.png 1638w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">Note how reprojection is used here to average results of multiple frames, even when the camera is moving. Also note typical problem cases for reprojection: areas that were not visible in the previous frame obviously cannot be reprojected, so those surfaces show noise.</p>



<p class="wp-block-paragraph">In a rasterizer, reprojection is implemented using motion vectors. A motion vector for a vertex is obtained by transforming it using the current camera matrix and the camera matrix of the previous frame. The difference (in screen space) is the motion vector. More information about reprojection can be found in the excellent <a href="http://behindthepixels.io/assets/files/TemporalAA.pdf">survey on TAA</a> by NVIDIA&#8217;s Lei Yang, Shiqiu Liu and Marco Salvi.</p>



<h2 class="wp-block-heading">Frustum Approach</h2>



<p class="wp-block-paragraph">Let&#8217;s dive right into the alternative. The situation at hand looks like this:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="572" src="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1-1024x572.png" alt="" class="wp-image-1681" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1-1024x572.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1-300x168.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1-768x429.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1-897x501.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1-360x201.png 360w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-1.png 1203w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p class="wp-block-paragraph">On the left, the ray tracer evaluated the color for one pixel by tracing a primary ray. It found the red sphere. Let&#8217;s assume the red sphere is illuminated by a partially blocked area light; shading is therefore noisy and we wish to reduce variance by taking into account the shading value for the same world space location in the previous frame.</p>



<p class="wp-block-paragraph">This is illustrated on the right. Since the previous frame (dashed), we translated the camera diagonally. We can see that point <strong><em>P</em></strong> is within the previous view frustum, so intuition tells us that we should be able to reproject from the previous frame to the current frame.</p>



<p class="wp-block-paragraph">With just the two view pyramids, it turns out we have sufficient information to do the actual reprojection. Here is the situation in the current frame:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="525" height="603" src="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-2.png" alt="" class="wp-image-1682" style="width:375px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-2.png 525w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-2-261x300.png 261w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-2-360x413.png 360w" sizes="auto, (max-width: 525px) 100vw, 525px" /></figure>
</div>


<p class="wp-block-paragraph">The location of point <em><strong>P</strong></em> in world space can be expressed in terms of distances to the planes of the view frustum. The horizonta location is simply the distance to the left plane, divided by the summed distance to the left plane and the right plane. The vertical location is calculated in the same way. Obviously, we learn nothing new, because the screen space coordinate for point <strong><em>P</em></strong> was already known: we generated a primary ray for it, after all.</p>



<p class="wp-block-paragraph">However, the same calculations work in the view pyramid of the <em>previous </em>frame.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="495" height="669" src="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-3.png" alt="" class="wp-image-1683" style="width:338px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-3.png 495w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-3-222x300.png 222w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-3-360x487.png 360w" sizes="auto, (max-width: 495px) 100vw, 495px" /></figure>
</div>


<p class="wp-block-paragraph">Here, point <strong><em>P</em></strong> is the same point we used previously, since everything happens in world space. The same math therefore lets us calculate <em>x</em> and <em>y</em>. From here, we can use this knowledge in the usual way.</p>



<p class="wp-block-paragraph">Note that the calculations are cheap: </p>



<p class="wp-block-paragraph">Based on the camera position <em><strong>E</strong></em> and the four corners of a virtual screen plane in world space we can calculate the four bounding planes of the view pyramid. Since this is done only once per frame, the cost is negligible.</p>



<p class="wp-block-paragraph">To reproject a world space position we calculate the four distances to the planes using dot products. We then calculate the horizontal and vertical position in screen space, which is the desired result.</p>



<p class="wp-block-paragraph">One final thing: you may wonder why I simply assumed a linear relation between <em>d<sub>1</sub></em> and <em>x</em>, and <em>d<sub>2</sub></em> and <em>1-x</em>. This becomes clear with the following diagram:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="1011" height="786" src="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-4.png" alt="" class="wp-image-1689" style="width:298px;height:auto" srcset="https://jacco.ompf2.com/wp-content/uploads/2024/01/image-4.png 1011w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-4-300x233.png 300w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-4-768x597.png 768w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-4-897x697.png 897w, https://jacco.ompf2.com/wp-content/uploads/2024/01/image-4-360x280.png 360w" sizes="auto, (max-width: 1011px) 100vw, 1011px" /></figure>
</div>


<p class="wp-block-paragraph">It is clear that angle DPF equals CPA, and since F and A are right angles, FPE and APB also must be equal. Therefore, all proportions in EPF are the same in APB. Thanks Quinten Bikker for clarification and the above diagram!</p>



<h2 class="wp-block-heading">Final Remarks</h2>



<p class="wp-block-paragraph">The described method was used in the <a href="https://jacco.ompf2.com/lighthouse-2-rtx-path-tracing-benchmark/" data-type="link" data-id="https://jacco.ompf2.com/lighthouse-2-rtx-path-tracing-benchmark/">Lighthouse 2</a> real-time path tracer as part of the SVGF implementation in the filtering rendercore. Source code is <a href="https://github.com/jbikker/lighthouse2">available on Github</a>.</p>



<p class="wp-block-paragraph">I probably did not invent this. If you have seen this technique before, please let me know so I can proper reference earlier implementations. You can respond to this article, or reach me on <a href="https://twitter.com/j_bikker" data-type="link" data-id="https://twitter.com/j_bikker">Twitter/X</a> or <a href="https://bsky.app/profile/jbikker.bsky.social" data-type="link" data-id="https://bsky.app/profile/jbikker.bsky.social">BlueSky</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2024/01/18/reprojection-in-a-ray-tracer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Writing an MSX2 game&#8230; in 2023 &#8211; PART 1</title>
		<link>https://jacco.ompf2.com/2023/09/14/writing-an-msx2-game-in-2023-part-1/</link>
					<comments>https://jacco.ompf2.com/2023/09/14/writing-an-msx2-game-in-2023-part-1/#comments</comments>
		
		<dc:creator><![CDATA[jbikker]]></dc:creator>
		<pubDate>Thu, 14 Sep 2023 06:58:26 +0000</pubDate>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[MSX]]></category>
		<category><![CDATA[Tutorial]]></category>
		<guid isPermaLink="false">https://jacco.ompf2.com/?p=1610</guid>

					<description><![CDATA[One day before writing this I submitted a game to the MSXDev&#8217;23 contest. &#8220;Eggy&#8217;s Maze&#8221; will be...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">One day before writing this I submitted a game to the <a href="https://www.msxdev.org/msxdev23/">MSXDev&#8217;23 contest</a>. &#8220;Eggy&#8217;s Maze&#8221; will be the 15th entry to the competition, with almost two months to go. Last year&#8217;s winner, &#8220;<a href="https://www.msxdev.org/2022/10/05/msxdev22-31-lillys-saga-the-stones-of-evergreen/">Lilly&#8217;s Saga</a>&#8220;, is on sale as a <a href="https://cotegamers.com/shop/en/accueil/142-lilly-s-saga-the-stones-of-evergreen.html">physical cartridge</a>, just like many other <a href="https://cotegamers.com/shop/en/35-msxmsx2">new games</a> for the 1984 platform that MSX is. My favorite retro machine is not an exception either; people are writing software for the <a href="https://youtu.be/WHy7DR-9QwI?list=PLxOanVBhqd3tifbfdE3mgtIgpBmpij6qp">ZX-Spectrum</a> and <a href="https://www.lemonamiga.com/games/list.php?list_year=2023&amp;list_hardware=AGA">Amiga</a> as well as the <a href="https://www.lemon64.com/games/list.php?list_year=2023">C64</a> and many other platforms, and there&#8217;s even new hardware being developed (<a href="https://msxmakers.design.blog/proyectos/">MSX</a>, <a href="https://www.specnext.com/">ZX-Spectrum</a>, <a href="https://wereallgeeks.wordpress.com/2023/04/06/diy_c64/">C64</a>).</p>



<p class="wp-block-paragraph"><em>Why?</em></p>



<p class="wp-block-paragraph">Nostalgia is a big factor, obviously. Or, <a href="https://www.theguardian.com/games/2021/sep/15/kids-raised-in-the-digital-era-are-yearning-for-this-the-people-making-new-games-for-old-consoles">experiencing computer history</a>, rather than just collecting it. But also: the challenge of making something work on hardware that was not remotely designed for it. Did you know that you can play <a href="https://doom.fandom.com/wiki/Game_Boy_Advance">Doom on a GBA</a>, and <a href="https://www.calculatorti.com/ti-games/ti-83-plus-ti-84-plus/mirageos/wolfenstein-3d/">Wolfenstein 3D on a TI-83</a> calculator (well, sort of)?</p>



<p class="wp-block-paragraph">Or perhaps it&#8217;s just about building something of a reasonable scale, all by yourself, without deadlines. A hobby. This is not about improving the world or paying the bills. It does bring a sense of power though: internet is far better than the smudgy magazines and manuals of the past, and PCs (with their emulators, cross-compilers and multiple monitors) are mighty development machines. It&#8217;s not hard to do <em>much </em>better than what was possible in the 80s.</p>



<p class="wp-block-paragraph">My point is: I may not be completely out of my mind for trying this. So, with this apologetic introduction, let&#8217;s dive in the main topic: Writing an MSX2 game&#8230; In 2023.</p>



<h2 class="wp-block-heading">Hardware</h2>



<p class="wp-block-paragraph">The MSX standard was introduced in 1983. It was a bit different than other offerings of the time: Like the early PCs, it was extendable and backed by multiple vendors.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://raw.githubusercontent.com/jbikker/ompf2/main/msx1.jpg" alt=""/></figure>



<p class="wp-block-paragraph">An MSX computer (as well as MSX2 and MSX2+ successors) is powered by a Zilog Z80A processor, running at 3.58MHz, the same CPU used in the ZX-Spectrum, TRS-80, Amstrad CPC and others. To get a sense of how it compares to a modern CPU: It can do <em>at most </em>1 million instructions per second, operate on at most 16 bits at a time, it doesn&#8217;t support floating point numbers at all, and it has no cache. It can also only address 64KB of memory. Luckily, the MSX standard lets you swap chunks of 16KB ROM/RAM in and out of that 64KB range, to get access to more memory, if needed.</p>



<p class="wp-block-paragraph">For graphics, another common processor of the era is used: The Texas Instruments TMS9918, which was already battle-tested in the <a href="https://www.retrogames.cz/konzole_SegaSG1000.php">SEGA SG-1000</a>. This is a reasonably advanced chip, which supports tile mapped graphics modes and hardware sprites. The MSX2 uses a revamped version of this chip, the Yamaha <a href="https://www.msx.org/wiki/Yamaha_V9938">V9938</a>. It adds more sprites, but also color palettes and more versatile graphics modes. Understanding and programming this chip is probably the main challenge when writing games.</p>



<p class="wp-block-paragraph">Sound on the MSX is handled by a 3-voice &#8216;PSG&#8217; (programmable sound generator), the <a href="https://en.wikipedia.org/wiki/General_Instrument_AY-3-8910">AY-3-8910</a>. This is a rather basic chip, so it was rather common to add a sound chip via the cartridge slot. Many Konami games did this.</p>



<p class="wp-block-paragraph">So, in short: one painfully slow CPU, a tiny memory pool, and simple coprocessors for graphics and sound. How does one program such a beast if any decent level of performance is required?</p>



<h2 class="wp-block-heading">Software</h2>



<p class="wp-block-paragraph">&#8220;Back in de days&#8221; it was common to write software straight in assembler. The alternative was BASIC, the programming language that was built into many homecomputers of the era. BASIC was executed using an interpreter, making it impractically slow for many applications. Assembler on the other hand is hard to use, especially without today&#8217;s emulators.</p>



<p class="wp-block-paragraph">But, things have changed. Assembler for Z80A processors can now be generated by the &#8216;small device C compiler&#8217;, <a href="https://sdcc.sourceforge.net/">SDCC</a>, which reached version 4.3.0 recently and is quite mature. It runs on modern PCs; the actual retro hardware will thus only be needed to test the final code. SDCC lets you use inline assembly code for performance-critical parts, but it is rather great that at least the application skeleton can now be written in efficient C code.</p>



<p class="wp-block-paragraph">Besides SDCC, there is are several accurate emulators for the MSX platform (and all common extensions). The most well-known emulators (for PC) are <a href="https://openmsx.org/">OpenMSX</a>, <a href="https://www.bluemsx.com/">BlueMSX</a> and <a href="https://webmsx.org/">WebMSX</a>.</p>



<p class="wp-block-paragraph">There are also debuggers. The well-known <a href="https://emulicious.net/">Emulicious</a> has support for MSX and MSX2 (besides other Z80A platforms) and will talk directly to Visual Studio while it executes the Z80A code.</p>



<p class="wp-block-paragraph">The final important piece of software is <a href="https://github.com/aoineko-fr/MSXgl">MSXgl</a>, a library of functions that make it easy to control the hardware. It can also serve as a library of knowledge about the video processor and memory system. The code truly is a treasure trove for MSX game developers.</p>



<p class="wp-block-paragraph">Although the PC-based C compiler, emulators, debugger and libraries make it relatively easy to develop for the ancient platform, it still remains a significant challenge. Writing code without std::vector, uint_64 and float is difficult; debugging the subtleties of the video hardware can be a nightmare with finicky timing issues, hardcoded special-purpose values, and of course those tiny memories.</p>



<h2 class="wp-block-heading">Let&#8217;s do this</h2>



<p class="wp-block-paragraph">Enough introduction, let&#8217;s compile something for MSX. Follow the steps below to produce your first ROM.</p>



<ol class="wp-block-list">
<li>Download the MSXgl <a href="https://github.com/aoineko-fr/MSXgl/archive/refs/heads/main.zip">source package</a> from github.</li>



<li>Extract the contents of the resulting MSXgl-main.zip to a folder, e.g. <code>c:\projects</code>.</li>



<li>Open a command prompt in folder <code>c:\projects\template_msx2</code>.</li>



<li>Execute <code>build.bat</code>.</li>
</ol>



<p class="wp-block-paragraph">The build.bat script will invoke the SDCC build system on MSXgl library files and the source files in the <code>template_msx2</code> folder (<code>template.c, template.h</code>). It produces a <code>.rom</code> file in the &#8217;emul/rom&#8217; folder. This ROM can now be executed using WebMSX: </p>



<ol class="wp-block-list">
<li>Navigate to <a href="https://webmsx.org/">webmsx.org</a></li>



<li>In Windows explorer, drag <code>template.rom</code> to the WebMSX tab in your browser.</li>
</ol>



<p class="wp-block-paragraph">If this all worked (it should), you can try to make life easier by automatically deploying compiled ROM files to a emulator installed on your machine. Edit <code>project_config.js</code> to suit your needs, but be prepared to spend some time setting up everything correctly.</p>



<details class="wp-block-details is-layout-flow wp-block-details-is-layout-flow"><summary>Click here to learn how to use OpenMSX to deploy your ROM.</summary>
<p class="wp-block-paragraph">While WebMSX works well for most ROMs, dragging a ROM file from a folder to a browser tab is cumbersome. To alleviate this, you can install OpenMSX to the tools folder in <code>c:\projects\MSXgl-main</code>. First, <a href="https://github.com/openMSX/openMSX/releases/download/RELEASE_19_1/openmsx-19.1-windows-vc-x64-bin.zip">download OpenMSX</a>. Add a folder <code>OpenMSX</code> to the <code>tools</code> folder and add the contents of the downloaded zip file to it. Then, edit <code>default_config.js</code> in <code>c:\projects\MSXgl-main\projects</code>: disable line 41, and enable line 42 to use OpenMSX. And finally, in the <code>template_msx2</code> folder, edit <code>project_config.js</code> to change line 18 to <code>DoRun = true;</code> . Now <code>built.bat</code> will run your ROM in OpenMSX, if there are no errors.</p>
</details>



<h2 class="wp-block-heading">Moving in</h2>



<p class="wp-block-paragraph">Now that all the tools are operational, we can start replacing the template code by our own. Here&#8217;s a minimal application that will draw a red square on the screen:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "msxgl.h"
void main()
{
	VDP_SetMode(VDP_MODE_GRAPHIC4);
	for( u8 y = 50; y &lt; 100; y++ )
		for( u8 x = 25; x &lt; 50; x++ )
			VDP_Poke_128K(0x99, x + y * 128, 0 );
	while(true) {}
}</pre></div>



<p class="wp-block-paragraph">Paste this code in <code>template.c</code> (overwriting existing content), and build the ROM. On my machine this produces the following output:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="746" src="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1024x746.png" alt="" class="wp-image-1623" style="width:523px;height:381px" srcset="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1024x746.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-300x218.png 300w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-768x559.png 768w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-897x653.png 897w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-360x262.png 360w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image.png 1148w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">There is a red square, but there&#8217;s also some garbage. The easiest way to get rid of that is by adding one line, just before the <code>for</code> loops, that reads: <code>VDP_ClearVRAM();</code> .</p>



<p class="wp-block-paragraph">The code is illustrating many aspects of MSX graphics programming. There is some typical C code: a main function, and the inclusion of the MSXgl library. At the end of main, the code simply &#8216;hangs&#8217; using an infinite while loop; we produce a ROM after all so there&#8217;s nothing to return to at the end of the program.</p>



<p class="wp-block-paragraph">A more interesting line is the VDP_SetMode command, which calls a function in MSXgl. The code for this function can be found in <code>c:\projects\MSXgl-main\engine\src\vdp.c</code>. At the time of writing, it starts on line 1501. The constant <code>VDP_MODE_GRAPHIC4</code> refers to one of the graphics modes of the V9938 chip. Detailed info about this mode can be found in the MSX2 Technical Handbook, in <a href="https://konamiman.github.io/MSX2-Technical-Handbook/md/Chapter4a.html#36-graphic-4-mode">Chapter 4</a>. Here we read that GRAPHIC4 is an MSX2-only mode, where we have 256&#215;212 pixels, each of which can be set to one of 16 colors. The 16 colors are stored in a <em>palette</em>. Each palette entry can be picked from 512 unique colors. The manual also specifies that the &#8216;pattern table&#8217; (in this case: the pixel buffer) for this mode starts at address 0 in VRAM. This table holds 2 pixels per byte; a full screen is thus 128&#215;212 bytes, so 26.5KB. By the way: We can change the address of the pattern table, which will be useful if we want to use double buffering later on.</p>



<p class="wp-block-paragraph">Two pixels per byte means: each pixel takes 4 <em>bits</em>. However, we can only write whole <em>bytes</em> to VRAM. So, to plot 1 pixel, we need to determine if its x-coordinate is odd or even. If it is even, the color goes to the left half of the byte, otherwise it is stored in the right half. When plotting one pixel, the other half must remain unchanged, so we first must obtain its contents from VRAM. Putting it all together, plotting one pixel becomes pretty complex:</p>



<p class="wp-block-paragraph">Note that bit fiddling is not optional on this platform; it is ubiquitous. And not just that: variable types are carefully chosen to be as simple as possible. An address must be 16 bit, but has no sign, so we use <code>u16</code>. A color needs only 4 bits, and no sign, so we pick the smallest type: <code>u8</code>. Odd or even is established by looking at the lowest bit (here: <code>x &amp; 1</code>): all odd numbers have this set to 1. Moving data to the left side of a byte: <code>c &lt;&lt; 4</code>. And so on. It grows on you, but initially, this leads to some pretty alien code.</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">void Plot( const u8 x, const u8 y, const u8 c /* 0..15 */)
{
	const u16 a = x / 2 + y * 128;
	const u8 v = VDP_Peek_128K( a, 0 );
	if (x &amp; 1) VDP_Poke_128K( (v &amp; 0xF0) + c, a, 0 );
	else VDP_Poke_128K( (v &amp; 15) + (c &lt;&lt; 4), a, 0 );
}</pre></div>



<details class="wp-block-details is-layout-flow wp-block-details-is-layout-flow"><summary>Click here to learn how to change the palette.</summary>
<p class="wp-block-paragraph">MSX computers have a default palette, which we used in the above example. In this palette, color 9 is bright red. You can find the full palette <a href="https://paulwratt.github.io/programmers-palettes/HW-MSX/HW-MSX-palettes.html">here</a>. To change the palette, use the MSXgl function <code>VDP_SetPalette</code>. This takes a <code>u16</code> array of 15 elements (palette 0 is not used), in which each 16-bit value encodes one of the 512 possible colors. To construct a color, pick a value between 0..7 for red, green and blue, and combine them as follows: <code>entry=(green&lt;&lt;8)+(red&lt;&lt;4)+blue</code>. For example: In hexadecimal numbers, white is 0x777, red is 0x070, blue is 0x007 and yellow is 0x770.</p>
</details>



<h2 class="wp-block-heading">Speed</h2>



<p class="wp-block-paragraph">Drawing the red rectangle using the custom Plot function is <em>slow</em>. In the emulator, the square visibly builds up. Obviously, this is not the way to draw interactive game content. The original code was a lot faster by the way:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">for( u8 y = 50; y &lt; 100; y++ )
		for( u8 x = 25; x &lt; 50; x++ )
			VDP_Poke_128K(0x99, x + y * 128, 0 );</pre></div>



<p class="wp-block-paragraph">That is because it always plots two pixels at a time. But even that code is not fast enough to render the square in real-time. We can do better, but before we attempt that, let&#8217;s establish what we <em>can</em> do in a single frame. For that, we need to have some way to measure performance.</p>



<p class="wp-block-paragraph">The code that we overwrite contained an important line:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">VDP_EnableVBlank(TRUE);</pre></div>



<p class="wp-block-paragraph">This enables an <em>interrupt handler</em>. Interrupts are hardware events that the Z80A CPU can respond to. Such events include key presses, but also the <em>vertical retrace</em> (a.k.a. <em>vsync</em>), which is the event that the electron beam on a <em>cathode ray tube</em> (CRT) moves back to the top of the screen to start a new frame. That&#8217;s not relevant for modern monitors, but the event is still there, and it happens 50 (or 60) times per second. Synchronizing to that event lets us write code that runs at a consistent speed.</p>



<p class="wp-block-paragraph">The nice thing about the VBlank interrupt is: We can wait for it. For this, we use the command Halt(). The new code, with some changes to make the rectangle move:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "msxgl.h"
void main()
{
	VDP_SetMode(VDP_MODE_GRAPHIC4);
	u8 pos = 0;
	while (true)
	{
		for( u8 y = 50; y &lt; 100; y++ )
		{
			// clear pixel on left side of square
			VDP_Poke_128K(0, pos + y * 128, 0 );
			// draw a horizontal line of pixels
			for( u8 x = 1; x &lt; 25; x++ )
			VDP_Poke_128K(0x99, x + pos + y * 128, 0 );
		}
		Halt();
		pos++;
	}
}</pre></div>



<p class="wp-block-paragraph">Clearing the screen each frame is obviously not an option, so the above code only removes pixels on the left side of the rectangle. That is of course something that would also work on the right side: many pixels do not need to be changed from frame to frame. It&#8217;s a simple change:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">// draw a horizontal line of pixels
		if (pos == 0) for( u8 x = 1; x &lt; 25; x++ )
			VDP_Poke_128K(0x99, x + pos + y * 128, 0 );
		else
			VDP_Poke_128K(0x99, 24 + pos + y * 128, 0 );</pre></div>



<p class="wp-block-paragraph">This time, the rectangle <em>almost</em> moves smoothly. Sadly, the <em>tearing</em> tells us that even this small amount of work is not completed within one frame. If we optimize the code a bit, we get close:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">while (true)
	{
		u16 a = pos + 50 * 128;
		for( u8 y = 50; y &lt; 100; y++ )
		{
			// clear pixel on left side of square
			VDP_Poke_128K(0, a, 0 );
			// draw a horizontal line of pixels
			if (pos == 0) for( u8 x = 1; x &lt; 25; x++ )
				VDP_Poke_128K(0x99, a + pos, 0 );
			else
				VDP_Poke_128K(0x99, a + 24, 0 );
			a += 128;
		}
		Halt();
		pos++;
	}</pre></div>



<p class="wp-block-paragraph">In this code, variable <code>a</code> holds the start address of a line of pixels for the rectangle. The top-left corner is on pixel <code>pos + 50 * 128</code>; after that we simply add 128 to a to get to the next line. As a result, the formulas in the VDP_Poke calls are much simpler, and that clearly helps.</p>



<p class="wp-block-paragraph">We reach our goal with one more improvement:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">#include "msxgl.h"
void main()
{
	VDP_SetMode(VDP_MODE_GRAPHIC4);
	// clear the screen to black (palette entry 1)
	for( u8 y = 0; y &lt; 212; y++ ) VDP_FillVRAM_128K( 0x11, y * 128, 0, 128 );
	// draw initial rectangle
	for( u8 y = 50; y &lt; 100; y++ ) VDP_FillVRAM_128K( 0x99, y * 128, 0, 25 );
	// move the rectangle
	u8 pos = 0;
	while (true)
	{
		u16 a = pos + 50 * 128;
		for( u8 y = 50; y &lt; 100; y++, a += 128 )
		{
			// clear pixel on left side of square
			VDP_Poke_128K(0x11, a, 0 );
			// draw a pixel on the right side
			VDP_Poke_128K(0x99, a + 24, 0 );
		}
		Halt();
		pos++;
	}
}</pre></div>



<p class="wp-block-paragraph">This time, after clearing the screen, a full rectangle is drawn once; after that, we can unconditionally remove two pixels on the left, and add two on the right. Skipping the conditions that we had before matters: This time the work is done without tearing.</p>



<p class="wp-block-paragraph">So, it seems that the work fits in a single frame. But, we can be more precise than that.</p>



<p class="wp-block-paragraph">The MSXgl command <code>VDP_SetColor</code> lets us set the screen border color. It defaults to color 0 (which is apparently blue), but we can also make it red, like the rectangle:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">VDP_SetColor(9);</pre></div>



<p class="wp-block-paragraph">We can then change it to green once we are done working on the rectangle, just before the <code>Halt()</code>:</p>



<div class="wp-block-urvanov-syntax-highlighter-code-block"><pre class="urvanov-syntax-highlighter-plain-tag">VDP_SetColor(3);</pre></div>



<p class="wp-block-paragraph">If we set the border to red at the start of the body of the while loop, and change it to green just before the <code>Halt()</code>, we get an interesting effect:</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="1024" height="748" src="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-1024x748.png" alt="" class="wp-image-1632" style="width:523px;height:382px" srcset="https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-1024x748.png 1024w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-300x219.png 300w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-768x561.png 768w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-897x655.png 897w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1-360x263.png 360w, https://jacco.ompf2.com/wp-content/uploads/2023/09/image-1.png 1180w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="wp-block-paragraph">The border color now is an indication of the frame time used for updating the rectangle. And, apparently only about half a frame is used, so we have time for other things. Note the red border at the bottom: the vertical retrace interrupt happens once the last pixels have been send to the screen. For the MSX system, the bottom of the screen is the bottom of the black rectangle. The monitor is still emitting the border color beyond that point, but that color gets changed.</p>



<h2 class="wp-block-heading">Finally</h2>



<p class="wp-block-paragraph">We covered quite some ground: Something runs on MSX <em>(well, on an emulator)</em>, and we can specify what it is in plain C. We plotted pixels in GRAPHIC4 mode and made them fast using some optimization tricks. It is clearly very important to write compact code that is easy to digest for the Z80A CPU.</p>



<p class="wp-block-paragraph">To move a bit more per frame we will need additional tricks. The next article will explain how to add sprites to the screen. We will also investigate a more efficient screen mode.</p>



<p class="wp-block-paragraph">Until that time: leave a comment below if something was unclear.</p>



<p class="wp-block-paragraph">Happy retro coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jacco.ompf2.com/2023/09/14/writing-an-msx2-game-in-2023-part-1/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
	</channel>
</rss>
