<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by emre_baba66 on Medium]]></title>
        <description><![CDATA[Stories by emre_baba66 on Medium]]></description>
        <link>https://medium.com/@Ksatese?source=rss-e39be7749aab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uCLzsaj-a8NBmEJirTaU4g.jpeg</url>
            <title>Stories by emre_baba66 on Medium</title>
            <link>https://medium.com/@Ksatese?source=rss-e39be7749aab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:13:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Ksatese/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vulkan Path Tracer]]></title>
            <link>https://medium.com/@Ksatese/vulkan-path-tracer-b719b296285a?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b719b296285a</guid>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 20:54:21 GMT</pubDate>
            <atom:updated>2026-06-25T20:54:21.717Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! This one will be a bit of a departure from the recent FlyOver series where I built a basic OpenGL flight game/sim. For the Computer Graphics II course term project I built a hardware-accelerated path tracer in Vulkan. While building, with some suggestions I decided to make the main point of it to compare three different ways of doing ray tracing on the GPU and see how they actually stack up against each other. The course itself is mostly OpenGL based, but trying Vulkan was encouraged. So this turned into equal parts learning Vulkan and Vulkan ray tracing properly, and actually measuring something people have a general idea of the right way, but barely measure that themselves.</p><p>I will not go through every line of the Vulkan setup here. If I explained every descriptor set, pipeline barrier and buffer allocation, this post would be three times as long and mostly boilerplate. There is a mountain of that in the code, which might be on my GitHub in a couple of days: github.com/distortedfuzz. Instead I want to focus on the ray/path tracing concepts, the three backends, and the actual performance results, since that is the interesting part. The goal here wasn’t to learn Vulkan, it was to actually get a path tracer going and compare the ways of achieving that.</p><p>Quick note on scope: I implemented everything I set out to in my intro presentation, with one exception. I had planned to add Russian roulette for path termination but ended up cutting it, partly for time but mostly because it would have undercut the comparison, stochastic termination makes the three backends do different amounts of work per frame, and the whole point here is timing them on identical workloads. I more than made up for it by going well beyond the original plan with the three-way backend comparison, which became the real focus of the project.</p><p>Also a quick note on hardware before we start, because it matters here: everything runs on an NVIDIA RTX 5070Ti, on Ubuntu 24.04. I will come back to why the specific GPU is important when we get to the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*em8ClnmwGbiBc4RTMUUrgg.png" /><figcaption>Vulkan Path Tracer — Ray Tracing Pipeline Next Event Estimation Accumulated Result</figcaption></figure><h3>Background</h3><p>If you have read my Advanced Ray Tracer series, you already know how a path tracer works conceptually. We shoot rays from the camera, bounce them around the scene accumulating light, and average a ton of samples per pixel to get a clean image. I covered Monte Carlo integration, importance sampling, next event estimation and all of that back in ART: Part 6, so I will not re-derive everything here. The math is the same, I advise you to check that blog post out to understand the basic path tracing ideas. What is completely different this time is where the path tracer runs.</p><p>In the old project everything was on the CPU, and I even built the BVH acceleration structure by hand (ART: Part 2). Here, the entire path tracer lives on the GPU and uses the actual ray tracing hardware, the RT cores, to do the ray-scene intersection. The driver builds the acceleration structures for us and the hardware traverses them. That alone is a massive change from doing it all yourself on the CPU. But here is what this project is really about: once you decide to use hardware ray tracing in Vulkan, there is more than one way to structure your tracer, and they are not equivalent in performance and in difficulty. I implemented three of them, and most of the post is about why they differ.</p><h3>Vulkan Ray Tracing</h3><p>Before the three backends, let me lay out the Vulkan machinery at a high level, because the three approaches are built on top of these pieces and it is hard to talk about them otherwise.</p><p>There are three main extensions in play. VK_KHR_acceleration_structure is the one that handles building and managing the acceleration structures (the trees the hardware traverses). VK_KHR_ray_tracing_pipeline gives you the dedicated ray tracing shader stages and pipeline. And VK_KHR_ray_query lets you fire rays inline from any shader stage, including a regular compute shader, without the whole pipeline. The acceleration structure extension is the common base, both of the other two need it. Two of my three backends use the ray tracing pipeline and one uses ray query, so I needed all three.</p><h4>Acceleration Structures</h4><p>Just like in my CPU ray tracer, we do not want to test every ray against every triangle, that is O(n) and miserable. We want a tree we can traverse in roughly logarithmic time. On the GPU this is split into two levels, and this two-level idea is actually the same TLAS-BLAS structure I used for instancing back in ART: Part 2.</p><p>A bottom level acceleration structure (BLAS) wraps the actual geometry, the triangles of a mesh. A top level acceleration structure (TLAS) holds instances, where each instance points at a BLAS and carries a transform. So you build a BLAS once for a mesh, and you can place it many times in the TLAS with different transforms, without duplicating the geometry. When a ray traverses, it goes through the TLAS to find which instance it hits, then down into that instance’s BLAS to find the actual triangle. The hardware does all of this traversal for you, which is the whole point of the RT cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdoEkcFgsloii3InlJG5uA.png" /><figcaption>BLAS/TLAS Acceleration Structure Explanation 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsuWraQPD7Yfikztb2WJjw.png" /><figcaption>BLAS/TLAS Acceleration Structure Explanation 2</figcaption></figure><p>Building one of these is a bit of a ceremony in Vulkan. The rough flow is: describe what you are building (type, geometry, counts) in a build-info struct, ask the driver how much memory it needs, allocate that memory plus a scratch buffer for the build to work in, create the acceleration structure object in that buffer, and finally record and submit the actual build on a command buffer. It is verbose but mechanical once you have done it once.</p><p>There are also flags you pass at build time that are worth knowing about, since they are hints to the driver about what you care about. PREFER_FAST_TRACE builds a higher-quality tree that traverses faster but takes longer to build, and PREFER_FAST_BUILD is the opposite. There are also opt-in capabilities like ALLOW_UPDATE (cheaply refit the tree when objects move) and ALLOW_COMPACTION (squeeze the structure into a tighter buffer afterwards). Since my scene is static, I just used PREFER_FAST_TRACE and did not bother with updates or compaction. The geometry never moves, so I build the structures once and forget about them.</p><h4>The Ray Tracing Pipeline</h4><p>The ray tracing pipeline is completely separate from the rasterization pipeline you use for normal rendering. No vertex or fragment shaders. Instead it has its own set of shader stages, and the ones that matter for me are:</p><p><strong>Ray generation shader (RGS):</strong> the entry point. It gets launched over a grid, basically like a compute shader, one invocation per pixel. It constructs the camera ray and kicks off tracing with traceRayEXT().</p><p><strong>Closest-hit shader (CHS):</strong> runs when a ray hits the nearest piece of geometry. This is where shading would normally happen, and you can have more than one of them for different materials.</p><p><strong>Miss shader (MS):</strong> runs when a ray hits nothing. Classic use is sampling an environment map or sky.</p><p>There are also any-hit and intersection shaders, but I did not need them since I only have opaque triangles.</p><p>The way the hardware knows which shader to run for a given ray is the Shader Binding Table (SBT). This is a GPU buffer holding handles to all the shader groups, laid out in regions (raygen, miss, hit). When a ray hits something, the hardware looks up the right hit shader in the SBT and runs it. This indirection is powerful, it is what lets you have per-material hit shaders, but as we will see it is not free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lT8bA--7d-kW4WBbtbqJbg.png" /><figcaption>Vulkan Ray Tracing Pipeline Mechanism (Mihut, 2020)</figcaption></figure><h4>Iterative vs Recursive Path Tracing</h4><p>One important decision in the pipeline approach is where you put your bounce loop. You can call traceRayEXT() recursively from inside the closest-hit shader, so each hit shoots the next bounce itself, or you can call it iteratively from the ray generation shader in a loop, where the hit shader just reports back and raygen fires the next ray.</p><p>I went iterative, in the raygen shader, for both pipeline backends. Recursion on the GPU is something you generally want to avoid, it eats stack space and the hardware is not built for deep recursion. An iterative loop in raygen that bounces a payload around is the cleaner, faster pattern, and it also keeps the bounce logic in one readable place.</p><h3>Path Tracing Core</h3><p>The actual light transport is the same across all three backends, since the whole point is that only the structure changes, not the result. I will keep this brief since it is mostly ART: Part 6 material.</p><p>We estimate the rendering equation’s hemisphere integral with Monte Carlo: sample a bounce direction, weight by the probability of having sampled it, average enough samples and it converges. I do cosine-weighted hemisphere sampling for the diffuse bounces. For the glass I do a Fresnel-weighted coin flip between reflection and refraction, mainly the same dielectric logic from ART: Part 1. In there, we definitely sent one refractive and one reflective ray, but here, we do accumulation and the sheer volume of rays makes up for it.</p><p>I implemented three lighting modes that all work across all three backends. <strong>Naive</strong> just bounces until a ray randomly hits the emitter, which is correct but noisy. <strong>Next event estimation (NEE)</strong> samples the light directly at each diffuse bounce, which cuts the noise dramatically, and it is the mode I used for the actual comparison since it is what you would really use. <strong>Sky</strong> mode has no emitter at all, light comes from a gradient sky whenever a ray escapes the scene, which I mostly use for the Sponza scene as there are no emissive meshes there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DR4KCpUVtLaZG5b4BoUOXg.png" /><figcaption>Naive Path Tracing — Single Frame</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2A22PLOEaVEPfjhNafDRg.png" /><figcaption>Next Event Estimation — Single Frame</figcaption></figure><p>To get a clean image we accumulate. I keep a float accumulation buffer and keep adding each frame’s samples into it, displaying the running average, and the count rides along in the alpha channel (which you’ll observe in the video). When the camera moves I reset the accumulation. So if you sit still the image keeps refining and the noise melts away, which is very satisfying to watch live.</p><p>One small implementation note I am a little happy with: I compute face normals directly from the triangle vertices in the shader with a cross product, instead of trusting the normals stored in the glTF file. I had some issues with inconsistent stored normals early on and just solved the whole problem this way. The stored normals are still loaded, they are just dead weight now. I left them in because ripping them out touched a lot of code, and removing them seemed like unnecessary work.</p><h3>The Three Backends</h3><h4>Ray Query in Compute</h4><p>The simplest backend. A regular compute shader, and inside it I just ask the hardware to trace a ray with an inline ray query call. Traversal happens, the hit comes back, and I keep going, all inside one shader, in one dispatch. Everything stays in the compute shader’s registers the whole time. There is no separate shading stage, no payload, nothing handed off. This is the megakernel approach, the whole tracer is one big kernel with all of the different material shading happening in there.</p><h4>RT Pipeline Megakernel Style</h4><p>This approach uses the real ray tracing pipeline with raygen, closest-hit and miss stages. I call traceRayEXT() from raygen, the hardware runs the closest-hit shader, and the result comes back through the payload. But I deliberately keep all the actual shading and bouncing logic in the raygen shader, the closest-hit shader basically just reports what it hit (normal, material, color) and raygen does the rest. So it is megakernel in spirit, just expressed through the pipeline. There is one hit shader for everything.</p><h4>RT Pipeline Separated</h4><p>The proper, textbook pipeline usage. Instead of one reporting hit shader, I have a separate closest-hit shader per material, a diffuse one and a glass one, and each does its own material’s work right there in the hit shader. The hardware picks which to run per ray via the SBT. On top of this I added Shader Execution Reordering (SER), an NVIDIA feature where the hardware regroups threads by what they hit before running the hit shaders, so threads doing the same work run together.</p><p>So the spectrum goes from everything running in one kernel, data never leaving registers (ray query) to fully separated per-material shaders dispatched by the hardware, with reordering (separated pipeline), with the megakernel pipeline sitting in between, paying for the pipeline machinery but only running one hit shader. The structural difference between these is really about how far the data has to travel. In the ray query version, the whole thing is one compute shader. The trace is just an inline call in the middle of it. I ask for a hit, the hit comes back, and I keep going, all in the same shader, with the hit data sitting in registers the entire time. The data flow is a straight line that never leaves the kernel.</p><p>The pipeline versions break that line apart. The trace is no longer a local call, it is a jump out to separate shader stages. The raygen shader fires a ray, the hardware traverses and then dispatches into a closest-hit shader (or a miss shader if nothing was hit), and the result has to come back to raygen through a payload, a little struct that rides along with the ray. So instead of staying in registers, the hit data gets written out at the hit shader and read back in raygen every single bounce. The megakernel pipeline does this with one closest-hit shader that just reports back. The separated version goes one step further and fans out: based on the material of whatever the ray hit, the SBT routes it to the diffuse hit shader or the glass hit shader, each doing its own shading work, and SER can step in before that dispatch to regroup threads by material so the per-material shaders run coherently. More flexibility, but more places for the data to stop and turn around.</p><h3>The Scene</h3><p>I went with a Cornell box, like most basic renderers. Colored walls, diffuse interior, and I put a glass Suzanne monkey in the middle so there is at least one interesting non-diffuse material refracting light around (check out ART: Part 1 for refractiion). An emissive square is the light. The controlled, simple nature of the box is exactly what I wanted for a clean comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*em8ClnmwGbiBc4RTMUUrgg.png" /><figcaption>Cornell Box NEE Pipeline Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHxXnrrr5NkbaUF4FetVeQ.png" /><figcaption>Cornell Box NEE Pipeline Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPDGrcIWVTu3W0HXE75amA.png" /><figcaption>Cornell Box NEE Pipeline Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYIlDkK8JRXN1TGX_tg4qw.png" /><figcaption>Cornell Box Pipeline Results</figcaption></figure><p>I also support loading Sponza, lit by the gradient sky instead of an emitter, as a bigger and more realistic stress for the backends. It is fully grey since I skipped textures as they add a ton of extra work, but the geometry is dense enough to be a real workload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQ5las6BRGHYrLoFcgb-qw.png" /><figcaption>Sponza NEE Pipeline Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IksLa7wE1deY3hZ0IWb9sw.png" /><figcaption>Sponza NEE Pipeline Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSOTFVWv28RF3ZMxyc5yIw.png" /><figcaption>Sponza NEE Pipeline Results</figcaption></figure><h3>The Comparison Setup</h3><p>To make this a fair fight, all three backends render the exact same scene from the exact same fixed camera, with the same samples and bounces, accumulating into the same kind of float buffer. I time only the actual trace work with GPU timestamps, not CPU-side timing which would fold in all sorts of unrelated noise, and I print a one-second average so the number settles and I can read it off comfortably. Validation layers are off during timing so they do not skew anything. So whatever differences show up are differences in how the tracing is structured, full stop. Same scene, same workload, same result, only different plumbing.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1nIAKrKHx44%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1nIAKrKHx44&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F1nIAKrKHx44%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dc1097c44280e07d6e55e8712263097/href">https://medium.com/media/3dc1097c44280e07d6e55e8712263097/href</a></iframe><h3>The Results</h3><p>Here is the ordering I got on the Cornell box with NEE, fastest to slowest:</p><ol><li><strong>Ray query in compute</strong> (fastest)</li><li><strong>RT pipeline, megakernel</strong></li><li><strong>RT pipeline, separated</strong> (slowest)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*u7gjpChnzx1kd6tuFF5vVg.png" /><figcaption>Per-frame trace time in milliseconds in Cornell Box, lower is better</figcaption></figure><p>The ordering holds under naive lighting too, ray query then megakernel then separated, so it is the structure driving it, not the lighting mode. One thing to keep in mind reading the table: NEE costs more per frame than naive because of the extra shadow ray, but it converges to a clean image far faster, which is the whole reason to use it. Lower ms per frame is not the same as getting a better image sooner.</p><p>Honestly this is exactly what I expected once I thought it through, even though it is maybe the opposite of what you would guess if you assume the proper separated pipeline must be the optimized one. The ray query version wins because it is the leanest. Everything stays in the compute shader’s registers the whole time. No payload written out and read back, no separate stage dispatched, no SBT lookups. The traversal uses the same RT cores as the others, but everything around it is as bare bones as it gets. A nice way I saw this put somewhere: the inline approach keeps your data in registers, while the pipeline approach moves your payload out through memory and back. That round-trip is not free.</p><p>The megakernel pipeline adds the dispatch overhead and the payload round-trip, but it still only has one hit shader, so there is not much beyond that. The separated pipeline is the slowest, and this is the interesting one. Every ray has to look up which hit shader to run in the SBT, dispatch into a separate per-material shader, then haul the results back through a fatter payload. That is real overhead per ray. And in this scene, you get nothing back for paying it.</p><h3>Why the Pipeline Loses Here</h3><p>This is the part I find genuinely interesting, and it took me a while to fully wrap my head around.</p><p>The separated pipeline and SER exist to solve one specific problem: <strong>divergence</strong>. GPUs run threads in groups (warps), and all threads in a warp run in lockstep. If half the threads in a warp hit glass and half hit diffuse, the warp has to run both materials’ code one after the other, each half sitting idle during the other’s turn. That wasted work is divergence. SER fixes it by regrouping threads so that threads hitting the same material end up together in a warp, and the separated pipeline gives each material its own tight shader to run coherently.</p><p>But here is the catch: my scene barely has any divergence to begin with. The glass monkey is one compact object in the middle. The rays that hit it are clustered together on screen, so the warps looking at the monkey are already mostly coherent, and the warps looking at the walls are already all diffuse. There is almost nothing for SER to reorder, because the geometry already grouped the threads by luck. And the materials themselves are cheap, diffuse is a few lines and glass is a Fresnel coin-flip, so even when a warp does diverge, running both is cheap.</p><p>So the separated pipeline pays the full price of per-ray dispatch and the fat payload, and on this scene there is little divergence to recover and the materials are too cheap to matter. SER on top does something genuinely interesting though: its sign flips depending on the lighting mode. Under naive lighting it actively hurts, the separated pipeline goes from 0.8ms to 1.54ms with SER on. That makes sense, after the reorder there is barely any per-hit work to make coherent (naive just picks a bounce direction and continues), so you pay the reordering cost and get nothing back. But under NEE it helps, 1.92ms down to 1.71ms, because NEE does real work at every diffuse hit: a shadow ray plus the light-sampling math. That is finally enough work after the reorder for the regrouping to pay for itself. So even on this simple scene, SER’s value depends entirely on whether there is enough divergent work downstream of the reorder to recover its cost, which is a small, but very concrete echo of the bigger story.</p><p>I actually tried to force the separated version to win. I added a synthetic workload knob, a busy loop in the shading code that I could crank up to make materials artificially expensive, with the glass path made heavier than the diffuse one to try to create divergence on purpose. The idea was to push the materials expensive enough that the coherence benefit would finally pay off and flip the ordering. It did not flip. The cost went up roughly evenly everywhere instead of creating the kind of divergence SER feeds on, because the warps were still spatially coherent, I was just making every thread do more work, not making neighboring threads do <strong>different </strong>work. I ended up ripping the experiment back out.</p><h3>When the Separated Pipeline Wins</h3><p>This is an extremely important point of this project: the separated pipeline is not bad, my scene is just not the kind it was built for. The literature backs up exactly what I am seeing, and also says when it reverses.</p><p>The classic reference seems to be Laine, Karras and Aila’s “Megakernels Considered Harmful: Wavefront Path Tracing on GPUs” (NVIDIA, HPG 2013). Their whole argument is that the<strong> separated / wavefront style overtakes the megakernel style specifically when materials are expensive to evaluate and divergent</strong>. They even cite earlier work (Wald 2011) noting that for simple materials the megakernel is perfectly fine, which is precisely my result. As material count and divergence grow, which they only ever do in real production scenes, the separated approach gets more and more appealing.</p><p>You can see this idea in shipping renderers. Cyberpunk 2077’s path tracing uses many per-material hit shaders hit in a divergent way, with SER, and NVIDIA reports meaningful gains from SER there. Unreal Engine 5’s path tracer compiles per-material shader permutations too. These are exactly the separated approach, used at scale, because their scenes have the expensive divergent materials that make it worth the overhead. My Cornell box just is not that.</p><p>So the honest framing of my result: on this cheap, low-divergence workload, the ordering is ray query &lt; megakernel pipeline &lt; separated pipeline, because the separated design’s overhead dominates with no divergence or material cost to win it back. I did get a tiny preview of the reversal with SER under NEE, the one place where added per-hit work made the reordering worth its cost. The literature says this ordering is expected to reverse once materials get expensive and divergent enough. Figuring out exactly where that crossover sits would have been nice, but I kept the scene deliberately on the simple end so I could reason about it cleanly (also it is too much work to write 10–20 different BRDFs). There is no clean published “N materials and you flip” number anyway, because it depends heavily on the hardware and the workload, which is sort of the whole point.</p><p>There is also a hardware angle, which is why I keep mentioning the specific GPU. On NVIDIA, ray query and the RT pipeline are pretty close, within a few percent in some comparisons. On AMD the gap can be much larger. So even “ray query wins” is not a universal law, it is a statement about this card.</p><h3>Conclusion</h3><p>This was a really different project from FlyOver and Advanced Ray Tracer, and I learned a huge amount. Getting hardware ray tracing working in Vulkan from scratch was difficult, there is a ton of setup before you trace your first ray, and the three extensions, the TLAS-BLAS build, and the SBT all took real time to get right. But the backend comparison came out clean and made sense: on a simple scene, the leanest approach (inline ray query) wins, and the fancy separated pipeline loses because it pays for divergence handling it does not need. And the literature lines up, telling me this would flip if I pushed the materials into expensive-and-divergent territory like a real game does.</p><p>If there is one takeaway, it is that the most advanced way is not automatically the fastest, it is the <strong>fastest for the workload it was designed for. </strong>Matching your renderer’s structure to your actual scene is the whole game.</p><p>I kept the scope tight on purpose: no textures, no MIS (although I thought I would add it), no denoiser. I also thought about a denoiser, since a path tracer always looks nicer with one, but it would clean up all three backends identically and not change the comparison at all, so it would just be work that muddies the point. Same for textures, that is a big pile of Vulkan plumbing unrelated to the backend question.</p><p>I would love to extend this later, the obvious next step is building that divergent, expensive-material scene and finding the crossover empirically, maybe with a real material system with many BRDFs. But that is a project for another time. The code will probably be on my GitHub in a few days. See you in the next one!</p><h3>References</h3><p>Einhorn, E. (2023, March 22). ‘Cyberpunk 2077’ brings beautiful path-traced visuals to GDC. NVIDIA Blog. <a href="https://blogs.nvidia.com/blog/cybe%EE%80%80rpunk-2077-path-traced-visuals%EE%80%80-gdc/">https://blogs.nvidia.com/blog/cyberpunk-2077-path-traced-visuals-gdc/</a></p><p>Koch, D., Hector, T., Barczak, J., &amp; Werness, E. (2020, December 15). Ray tracing in Vulkan. The Khronos Group. <a href="https://www.khronos.org/blog/ray-tracing%EE%80%80-in-vulkan">https://www.khronos.org/blog/ray-tracing-in-vulkan</a></p><p>Laine, S., Karras, T., &amp; Aila, T. (2013). Megakernels considered harmful: Wavefront path tracing on GPUs. High-Performance Graphics 2013.</p><p>Lefrançois, M. K. (2026). Vulkan ray tracing tutorial (v2). GitHub. <a href="https://github.com/nvpro-sa%EE%80%80mples/vk_raytracing_tutori%EE%80%80al_KHR">https://github.com/nvpro-samples/vk_raytracing_tutorial_KHR</a></p><p>Mihut, A. (2020, November 23). Vulkan ray tracing best practices for hybrid rendering. The Khronos Group. <a href="https://www.khronos.org/blog/vulkan-ray-%EE%80%80tracing-best-practices-for-hybrid-rend%EE%80%80ering">https://www.khronos.org/blog/vulkan-ray-tracing-best-practices-for-hybrid-rendering</a></p><p>Wald, I. (2011). Active thread compaction for GPU path tracing. High-Performance Graphics 2011.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b719b296285a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FlyOver: Part 3]]></title>
            <link>https://medium.com/@Ksatese/flyover-part-3-3f9f77f95e64?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f9f77f95e64</guid>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 20:52:01 GMT</pubDate>
            <atom:updated>2026-06-09T20:55:15.682Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! It has been a couple of weeks since the last blog post I wrote. In this part I will talk about the final additions to our terrain renderer: generating volumetric clouds over a cubemap texture blended with our existing HDR map, and creating a rain particle system with proper scene collisions. A large focus here is on making the rain dynamically collide and splash against our moving aircraft, which creates an extremely immersive atmosphere.</p><p>This is the third part of the FlyOver series, which is the 3rd assignment of the Computer Graphics 2 course at METU. I briefly mentioned at the end of the previous blog post that I would love to continue working on this project even if the next homework wasn’t a continuation of it, and as you can see, it turned out to be exactly that. I really like this progression, it feels like we are slowly building an actual cohesive little game step by step instead of doing isolated graphics assignments.</p><p>As usual, in a few weeks you can find the code on my GitHub: github.com/distortedfuzz. This part includes some more theoretical stuff compared to the previous part. I will briefly explain the concepts and the math, and show the small key snippets where I think they help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZpNcbE41tdGsrKvfiLzIA.png" /><figcaption>FlyOver: Part 3 — Procedural Clouds and Rain</figcaption></figure><h3>Volumetric Clouds and Ray Marching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAJapUOX-BaYESAEnxJaCg.png" /><figcaption>FlyOver with Procedural Clouds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tffuWIqKn0bpFZ_8E_n0SA.png" /><figcaption>FlyOver without Procedural Clouds</figcaption></figure><p>In the previous part, I talked about mapping equirectangular HDR environment maps onto a full-screen quad. Here, instead of doing that directly, we project the HDR map onto a cubemap. While doing this conversion, we procedurally generate volumetric clouds and blend them in. As you might have guessed, this is done in a compute shader to take full advantage of the parallel processing power of the GPU. There are other ways to handle this cubemap thing like one per face draw calls on a flat quad or rendering the cube from 6 viewpoints, which I didn’t delve that deep into. For our case, combined with the procedural clouds we will create, compute shaders are the most obvious tool to use.</p><p>Remember in the last part I said I could’ve used ImGui to change the middle grey value interactively, but that seemed like too much work, so I didn’t? In this part, I had so many cloud variables: noise scale, octaves, coverage, density, cloud steps, light steps, max march distance, sun color. I finally caved in and set up ImGui properly. With this setup it is so much nicer to tweak the cloud coverage on the fly than to close the app, change a float, and recompile every single time.</p><h4>Cubemap Conversion Setup</h4><p>First things first, we need a cubemap. An equirectangular map is great for a simple background, but a cubemap lets us sample directions in 3D space easily, which is nice for skyboxes, reflections, and most importantly here, ray marching. This is the backbone of the procedural clouds we will add to the sky.</p><p>To handle this, I created a compute shader that dispatches over the six faces of a 1024x1024 cubemap. For each pixel on each face, we need the 3D direction vector that goes from the center of the cube through that pixel. We take the 2D pixel coordinates, normalize them to the [-1, 1] range, and then place them on the correct X, Y or Z plane depending on which of the six faces we are currently working on. For the +X face for example, a pixel at (u, v) maps to the direction (1, −v, −u) before normalizing, and the other five faces are just permutations and sign flips of this. I believe this is really intuitive and visualizable.</p><p>Once we have this direction, we sample our existing HDR equirectangular map using spherical coordinates to get the base sky color, exactly the same atan/asin sampling I talked about in the previous part. But instead of just writing this color to the cubemap, we use this exact direction to march through the procedural clouds before deciding the final pixel color. But to do that, first we need to create the procedural noice to march through and sample from.</p><h4>Perlin Noise Generation</h4><p>As you might remember, I already implemented Perlin noise from scratch in a previous blog post more than a year ago: Advanced Ray Tracer: Part 4. The main idea is exactly the same, but here it runs inside the compute shader. I just adapted my old CPU implementation to use a 1D permutation array and a hash function right in the shader to pseudo-randomly pick the gradients. I still use my 18 gradient vectors and take the hash mod 18, same as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*fak3TtB-QHB-YcUKjVS04g.png" /><figcaption>2D Perlin Noise from CENG469 Course Notes (Akyuz, 2025–2026)</figcaption></figure><p>To make the clouds look like natural, we use a multi-octave approach (which we used in ART: Part 4 to get marble-like visuals). If you recall Ken Perlin’s paper (“Improving Noise”, 2002), he talked about directional bias and using a fixed set of gradients to avoid grid-like artifacts. The base noise gives the broad shape of the clouds, and then we add more octaves. Further Perlin iterations are at higher frequency (more detail) but lower weight (less impact). This carves out the fluffy, wispy edges. The accumulation is the same multi-octave sum I used before, where each octave k doubles the frequency and halves the weight:</p><blockquote>noise(p) = Σ (1 / 2ᵏ) · n(2ᵏ · scale · p), for k = 0 … K−1</blockquote><p>We then turn the noise into a density using a coverage parameter. This acts as a subtraction threshold so clouds only form where the noise is high enough, otherwise the density drops to zero and we are left with empty sky:</p><blockquote>density = max(0, noise − coverage) · density_scale</blockquote><p>Another thing is that clouds don’t exist infinitely on the Y axis, they have a bottom and a top bound in the atmosphere. To handle this I used a smoothstep on both ends so the clouds fade softly at their upper and lower limits instead of having a harsh cutoff that would completely ruin the visuals. This also helps with clouds looking way above the terrain we have. I believe this looks more realistic than creating clouds everywhere on the cubemap, because we actually fly over the terrain. I guess creating clouds everywhere could look better if our situation was closer to walking or driving on the terrain.</p><h4>Ray Marching and Single Scattering</h4><p>At this point we have the cubemap and the noise to create the procedural clouds. To actually shade these clouds and give them a sense of volume now, we need to simulate how light travels through them. This is where ray marching comes in. Again like Perlin noise, I previously implemented ray marching with more complex scattering on the CPU at Advanced Ray Tracer: Part 7. I received nice volumetric looking clouds, that actually included cloud and smoke looks, but I got some weird polygonal looking visuals, which I believe was due to me doing direct volumetric rendering on generic meshes. But nevertheless, in that part I explained a lot of stuff about volumetric rendering, which I won’t do here. I suggest you check that out if you like this kind of stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*nBQkhd6tEFLLB4WggGNTqg.png" /><figcaption>Basic Ray Marching Diagram (Scratchapixel, n.d.)</figcaption></figure><p>Ray marching we use here is closely related concept to ray tracing which you might know better. Unlike normal ray tracing where we find an exact analytical intersection with a solid surface like a sphere or a triangle, clouds don’t have a surface. They are volumes of varying density. So we can’t just solve an equation for a hit point. Instead, ray marching takes small incremental steps along the viewing ray we calculated earlier.</p><p>At each step we check if we are inside the cloud layer bounds. If we are, we sample the Perlin density. If it is greater than zero, we are inside a cloud and we need to figure out how much sunlight reaches this exact point. To do that, we pause our main view ray and shoot a second ray from the current position towards the sun’s direction. I find this sun direction once from the HDR map before everything starts (there’s a find_sun_direction step), since our dominant light is the environment map and there is no single hardcoded light. We march along this secondary light ray, accumulate the density, and plug it into the Beer-Lambert law to get the transmittance, which tells us how much light survives before reaching our point. Continuously this is an exponential decay over the optical depth:</p><blockquote>T(s) = exp( −∫₀ˢ σ(x) dx )</blockquote><p>and since we are marching in discrete steps, this just becomes a running product of one exponential per our marching step:</p><blockquote>T = Π exp(−σᵢ · Δt)</blockquote><p>This nested marching (marching along the view ray, and at each step marching again along the light ray) is sound, but it gets expensive easily. We accumulate the scattered light and the transmittance as we step through the camera ray, and finally blend the scattered light with the base sky color. The nice thing is that because we write directly to the cubemap in a compute shader, we don’t have to run this heavy math for every screen pixel every frame, only for the cubemap faces, and only when the cloud parameters actually change, so not each frame or specific render. The results look great, you get those nice silver linings when you look towards the sun.</p><p>Here are some examples with different variable settings, so you see the flexibility of the cloud system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*seo8SuYqry0daV1tIwdbxQ.png" /><figcaption>Cloud Example 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKSi_5vZFMOEAmNxv21yUg.png" /><figcaption>Cloud Example 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Xx7TNzTExCnb-5Icx0hPQ.png" /><figcaption>Cloud Example 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVJblaxTtO7GF8n103BIxQ.png" /><figcaption>Cloud Example 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U66c7GAk3cZGH4B6WvUM7g.png" /><figcaption>Cloud Example 5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxHjUsCP1jCXIJ3scOBrbQ.png" /><figcaption>Cloud Example 6</figcaption></figure><h3>Rain Particle System and Aircraft Collisions</h3><p>The second major part of this assignment was adding a dynamic rain effect: 20,000 raindrops falling down, hitting the scene, splashing on impact, and then resetting. To do this efficiently, the CPU is completely out of the question. You cannot loop over that many particles, update their physics, check collisions, and push all that data over the bus every frame without killing your performance. So the architecture is to use a Shader Storage Buffer Object (SSBO) to hold all the particle data on the GPU, a compute shader to update the physics, and a geometry shader to render them.</p><p>The obvious biggest challenge wasn’t making the rain drops fall, it was making them collide realistically. And specifically, collision with the airplanes was extremely important. Since our third person quaternion camera orbits the plane and follows it closely, the plane covers a large and dynamic chunk of screen space. We want the rain to smash against the wings, the body, and especially that shiny cockpit glass we did last time, instead of passing through it like a ghost down to the terrain.</p><h4>Compute Shader State Machine</h4><p>The first thing we need to think about here is what values do we need to actively store for each rain drop. Here, each particle is a small struct in the shader with a 3D position, a falling speed, a state, and an animation timer. This is designed as a state machine: state 0 means the particle is live and falling, state 1 means it has hit something and is splashing, and state 2 means it is dead and waiting to be recycled.</p><p>In the compute shader we launch one thread per particle. If the state is 0, we just subtract from its Y based on the speed and the frame’s delta time. If it falls below the bottom of the bounding cube without hitting anything, we recycle it by resetting its height back to the top of the cube. The cube follows the camera, so the rain is always around us. This is again a smart trick to get the illusion of rain without increasing the cost.</p><h4>Collision Detection via Depth Buffer</h4><p>Doing actual ray-triangle intersection for all these particles against the plane’s four meshes and the millions of terrain triangles would drop the frame rate to single digits. So here we need a smart trick to make this happen without increasing the development complexity too much. The strategy used here is a really nice screen-space trick using the depth texture from our HDR framebuffer. We already render the whole scene (including the terrain, water and the aircraft) into the FBO during the main pass, and that FBO has a depth attachment storing the distance of the closest object at every pixel. Because the camera is always focused on the plane, the plane’s depth values dominate the center of this depth texture. So this actually works well in practice despite being somewhat crude.</p><p>Here is how the math flows. For each falling particle, we take its world position p and run it through the whole projection:</p><blockquote>clip = VP · p, ndc = clip.xyz / clip.w</blockquote><p>The perspective divide leaves us in Normalized Device Coordinates, where x, y and z all sit between −1 and 1. If the particle is on screen, we remap its x and y to texture space, which gives exactly the UV coordinates we need to sample the depth buffer:</p><blockquote>uv = 0.5 · ndc.xy + 0.5</blockquote><p>Then the collision test is just a depth comparison at that uv, with both depths mapped to the same [0, 1] range:</p><blockquote>collision ⇔ z_particle ≥ depth(uv)</blockquote><p>If the particle’s depth is greater than or equal to the scene depth, it means it has reached or gone behind the surface we see on screen, so it collided. We switch its state to 1 (hit) and reset the animation timer. Because the plane is right in front of the camera, a big chunk of these collisions naturally happen on the wings and the cockpit, which creates great visuals especially when we zoom in and see the hits.</p><p>One honest shortcoming of this whole approach is that it is screen-space, so a particle can only collide with something that is actually in the depth buffer. Anything off-screen or fully occluded is invisible to it. This also causes issues where if we rotate the camera to the bottom of the plane, we see hits there though we shouldn’t. For rain centered on the plane right in front of the camera though, and for most purposes, this method works well and cheaply in practice.</p><p>Here’s a problematic case. To be perfectly honest, if this was a real game and people were playing it, this probably wouldn’t be much of an issue as the camera would be more restricted and there would be no reason to look under the plane. But it still bugs me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTqWSp-wDqF-MM4BCGH7FQ.png" /><figcaption>Rain Problematic Example</figcaption></figure><h4>Geometry Shader Billboards</h4><p>At this point our SSBO has the updated positions and states. But OpenGL points are just single pixels. To draw a textured drop or an animated splash, we need a flat quad made of two triangles. Instead of generating all 80,000 quad vertices on the CPU (4 per rain drop), we just issue a draw call over single points. The vertex shader passes the data along, and the geometry shader does the actual work. A geometry shader can emit new vertices on the fly, so for each incoming point we build a “right” and “up” vector and emit 4 vertices to form a quad. With the particle at position p and the camera at c, the right vector is the cross product of the world up and the direction from the particle to the camera:</p><blockquote>right = normalize( up × (c − p) )</blockquote><p>The up vector here stays the world up. The four quad corners are then p offset by the right and up vectors, each scaled by the quad’s half-width and half-height (it’s taller than it is wide, which suits the falling streaks). This means the quads face the camera horizontally (they rotate with yaw) but stay upright vertically, which is exactly what the assignment asks for and looks right for falling rain. This technique is called billboarding, and is used widely across domains. So before the sprite animation part which is important for visualizing hits, here are some examples of one image rain drops from afar, combined with our procedural clouds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDkQzikSmDRq8pyEggvQ1Q.png" /><figcaption>Rain Example Image</figcaption></figure><h4>Sprite Animation</h4><p>When a drop hits the plane or the ground, its state becomes 1, and in the fragment shader we handle the transition from a falling drop to a shattering splash. I used a sprite sheet with 4 horizontal frames which was provided. While a drop is still falling it just shows the first frame (frame 0). Once it hits, the splash runs through frames 1 to 3 based on how far along the animation timer t is relative to the hit duration t_hit. The frame index during the splash is</p><blockquote>frame = 1 + ⌊ 3 · clamp(t / t_hit, 0, 1) ⌋</blockquote><p>and that frame maps to the horizontal sub-range [frame/4, (frame+1)/4] of the sheet, while the vertical coordinate is used as is.</p><p>When the animation timer passes the hit duration, the particle is marked dead, and a dead particle then gets recycled back up to the top of the cube to fall again. To keep things clean we also discard any fragment with an alpha below a small threshold, so the billboards don’t draw their invisible bounding boxes over the plane geometry.</p><p>Here you can zoom in to see the hit animations and the rendered rain drop image changing when there’s a hit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xsoI9wj23GuuoHgkpOB_g.png" /><figcaption>Rain Hit Image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umlcDRW48EKCnfvsC7qn4w.png" /><figcaption>Rain Hit Image 2</figcaption></figure><h3>Conclusion</h3><p>This part was definitely challenging but also rewarding. It took the FlyOver project to a much more complete and atmospheric state. I really like procedural generation, and combining it with real-time effects like rain splashing directly onto the vehicle you control was a lot of fun and gave immersive results. The compute shaders carried most of the workload here, and the new stuff I learnt about GPU driven particle systems is a big plus. The cleverness of using the depth buffer for cheap, accurate screen-space collisions is a concept I will definitely carry forward into my future projects.</p><p>I still plan to keep working on this FlyOver project even after the term ends. Combining all this atmospheric tech with actual flight physics, gravity, wind, procedural infinite terrain, and a nice looking HUD would turn this from a graphics assignment into a really complete game. But anyways, see you in the next part!</p><h3>References</h3><p>Akyüz, A. O. (2025–2026). CENG469 Computer Graphics II course notes. Middle East Technical University, Department of Computer Engineering.</p><p>Perlin, K. (2002). Improving noise. ACM SIGGRAPH 2002 Conference Proceedings, 681–682. ACM. <a href="https://doi.org/10.1145/566570.566636">https://doi.org/10.1145/566570.566636</a></p><p>Scratchapixel. (n.d.). <em>Volume Rendering of a 3D Density Field</em>. Retrieved June 9, 2026, from <a href="https://www.scratchapixel.com/lessons/3d-basic-rendering/volume-rendering-for-developers/volume-rendering-3D-density-field.html">https://www.scratchapixel.com/lessons/3d-basic-rendering/volume-rendering-for-developers/volume-rendering-3D-density-field.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f9f77f95e64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FlyOver: Part 2]]></title>
            <link>https://medium.com/@Ksatese/flyover-part-2-512fdde1f314?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/512fdde1f314</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[3d-computer-graphics]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[graphics]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Tue, 05 May 2026 02:54:58 GMT</pubDate>
            <atom:updated>2026-05-05T02:54:58.509Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! In this part I will talk about environment mapping, HDR tonemapping, texturing, creating a cosine wave water plane, reading 3D meshes and a proper third person orbiting camera. This will build upon the previous blog post where I talked about terrain generation and rendering using b-splines, and quaternion cameras. I briefly mentioned at the start of the previous blog post that the second homework of the course this series is a part of might be a continuation of the first one, and as you can see it turned out to be just that.</p><p>I don’t know yet if the next homework will be on the same topic, but even this foundation feels strong so I’ll perhaps build upon this even after the end of the term. Nevertheless I wanted to give this project an overall name so it stays coherent when I further add new features. The name I came up with is FlyOver, because we fly over a generated terrain following a plane model. I will also talk about some new cool features that could be added to the project that would make it even cooler and perhaps take it to the next level.</p><p>The previous part of this project is already public. You can find this public version of the code on my GitHub profile in a couple of weeks: <a href="https://github.com/distortedfuzz">https://github.com/distortedfuzz</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpV6Qym-Q-1EfyWOLFYwtA.png" /><figcaption>FlyOver Image</figcaption></figure><h3>HDR and Tonemapping</h3><p>I have previously implemented this stuff as part of the Advanced Ray Tracer project. You can check out a more thorough explanation in part 5 of that project if you want. Here, I will focus on the real-time OpenGL side of HDR rendering.</p><h4>HDR Framebuffer</h4><p>Generic, also called LDR rendering has a problem where every color value must be in the range [0, 1]. This creates a problem in the sense that we lose a lot of the color data which makes a huge visual difference. To keep all the juice in the images, we first render the image without limiting everything to the [0, 1] range. After rendering the whole scene like that pixel by pixel, we then apply tonemapping, where we map every color value so that all the differences are visible, and we can properly see the relative color changes.</p><p>To keep the initially rendered color values, we create a framebuffer (FBO) of the same size of the window. In this framebuffer, I used a 16-bit floating point texture as its color attachment, which can store values well beyond the tiny [0, 1] range. All rendering we do initially goes into this texture instead of directly rendering to the screen. The fourth channel of this kind of texture or color (alpha) is normally used for transparency, but in this case, we use it to store the log luminance of each separate pixel. Each fragment shader writes this value explicitly each time it’s called like:</p><pre>float luminance = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));<br>frag_color = vec4(color.rgb, log(luminance + 0.00001));</pre><p>This is the commonly used luminance formula. It is the formula that converts RGB colors to a single value which represents perceived brightness. The formula takes into consideration the human eyes and their sensitivity to different colors. As you can see, the green channel has the most weight and blue the least. This is because the cones in our eyes that observe the color green are the most numerous, and blue is the least.</p><p>We also need the average luminance of the whole scene for later tonemapping. This is where mipmaps come in. They are progressively halved versions of a texture, and we can halve the texture up until 1x1. An example continuation could look like this: 1000x800, 500x400, 250x200, 125x100 ….. 1x1. In OpenGL, these are generated using glGenerateMipmap, it does this halving and averages the values from the level above. So at the end the final 1x1 mip level contains the average log luminance of every pixel. This gives us the mean luminance value we will use.</p><h4><strong>HDR Environment Map</strong></h4><p>An environment map is a spherical panoramic image that spans the whole space. Everywhere we look we should basically see the environment map. As you might guess, these are usually sky images that cover especially the entire upper hemisphere. Again, these are spherical panoramic images, and equirectangular projection is used to map them into 2D properly, a concept I talked about in the previous part.</p><p>We need to read these images in some way different than normal images, as they are not just 8-bit integers in the range [0, 255]. This project uses stb_image to read these HDR texture images. The stbi_loadf function just handles this and we can store everything as a GL_RGB16F texture.</p><p>So let’s say we load one of these images, and want to render them all over the scene. To do that, we create a quad which covers the entire screen in NDC space. In the fragment shader of this environment map quad, we reconstruct the world space view direction by multiplying through inverse projection and inverse view matrices for each pixel, and we sample the HDR environment map with these directions. We put this quad at the very back of everything, so it doesn’t cover any object, but acts as the environment.</p><p>Another critical issue here is that we have to sample the environment map texture by using these directions. We do this by using the formula:</p><pre>float u = atan(direction.z, direction.x) / (2.0 * PI) + 0.5;<br>float v = asin(clamp(direction.y, -1.0, 1.0)) / PI + 0.5;</pre><p>These are just generic spherical coordinates, the atan part forms the longitude and asin the latitude. There are a ton of resources on the math behind this formula, and it’s quite easy to grasp. I talked about it more in detail again in part 5 of the Advanced Ray Tracer project I believe, you can look into that.</p><p>At this point we have an environment map that we can see as the environment from the camera, also if we wanted to use the environment map for the rendering of some other object, we can just use this environment map sampling method to get the environment color of the reflection or normal directions.</p><h4><strong>Reinhard Tonemapping Operator</strong></h4><p>The steps of Reinhard tonemapping are these 4: luminance mapping, sigmoidal compression (the core Reinhard operator), burnout and gamma correction. Gamma correction might actually not be considered as a part of Reinhard tonemapping, but it is nonetheless a part of the full tonemapping pipeline. I will explain each part separately, provide the code snippets, and also explain why they’re important to the pipeline.</p><p><strong>Luminance Mapping</strong>:<strong> </strong>First, we want to scale the HDR color values so that the average brightness of the scene lands at a perceptually neutral middle grey (Advanced Ray Tracer: Part 5 for further explanation). This scales down the bright scenes and scales up the dark ones. This is like an initial mapping of any scene to an acceptable starting point.</p><pre>float avg_luminance = clamp(exp(textureLod(hdr_map, uv_coords, 10000.0).a), 0.1, 2.0);<br>float exposure = 1.0 / (avg_luminance + 0.00001);<br>color_val = color_val * exposure;</pre><p>The middle grey value is actually 0.18, but I didn’t quite like the image that value produced. It made everything look a little dark for my liking, maybe that’s because the environment map is a little too grey. So I changed that value until I liked it. I could’ve used ImGUI to change this middle grey value interactively, but that seemed like too much work, so I didn’t.</p><p><strong>Reinhard Operator (Sigmoidal Compression)</strong>: Second, we map everything to the [0, 1) range using sigmoidal compression. This mainly helps that dark values don’t change much, middle values change slightly, but very bright values get compressed, but still pushed toward white. This also ensures that every color value gets a unique output.</p><pre>color_val = color_val / (color_val + vec3(1.0));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*qVr9PcfTChfRBgHsspkH6w.png" /><figcaption>Sigmoidal Compression (Reinhard TMO) from CENG469 Course Notes (Akyuz, 2025–2026)</figcaption></figure><p><strong>Burnout</strong>: Third, we can apply burnout above a certain luminance value. Burnout refers to allowing the brightest highlights to clip to pure white. We can add this for artistic effect, but it doesn’t have much practicality for our use. I also didn’t add it in this part, but here’s the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*WUAIlDbk-H4zsL_7ZR14Og.png" /><figcaption>Burnout Formula from CENG469 Course Notes (Akyuz, 2025–2026)</figcaption></figure><p><strong>Gamma Correction</strong>: This is the last step. The issue this step solves is that monitors do not display light linearly, instead they apply a power curve to input values. Gamma correction basically compensates for that later power curve by applying the inverse curve beforehand. This makes the final image look correct on the screen when we actually see it.</p><pre>color_val = pow(color_val, vec3(1.0/2.2));</pre><p>After completing all these steps, we can see a nice environment map by drawing the environment quad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQnozSaREXAXbLVcf4PKDg.png" /><figcaption>HDR Environment Map Image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkuFdf-6NVxSlX4vbfonfQ.png" /><figcaption>HDR Environment Map Image 2</figcaption></figure><h3>Texturing</h3><h4><strong>Terrain Textures</strong></h4><p>As you might remember from part 1, I used different colors for each height range. In this part we have something way better, we have 4 textures to properly visualize all different height values: shore, grass, rock and snow. The important thing here is that the texture is tiny compared to the terrain. So we need to properly tile the texture on it. For this we need to read the texture with the setting GL_REPEAT, so when we read the texture with a larger value than 1, it repeats itself. But we also need to properly set up repeating coordinates in the fragment shader. We can just do this by multiplying the current uv coordinate of that point by a larger constant. This can be the same for all of the terrain. I decided to make this tiling constant 50, which visibly repeats itself, but not that much stretching is seen.</p><h4><strong>Texture Mixing</strong></h4><p>In the previous part the different color mixed smoothly near layer change heights. In this case, we can again sample the current layer’s and the next layer’s textures, and then mix these two color values by weighing using height linear interpolation. I used the mix() function for the shore-grass and grass-rock transitions after using linear interpolation weight values. For the rock-snow transition I used smoothstep() to find the mixing weight so that the snow texture doesn’t dominate the larger heights.</p><p>This produced great looking results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZ_-JogJuT2vqF7RMIy9Vg.png" /><figcaption>Textured Terrain Image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDcGCMM-tE6c7HtIUXQMaQ.png" /><figcaption>Textured Terrain Image 2</figcaption></figure><p>As you can see we can clearly see the same texture tiling over and over again when we see the full terrain. Also you can see that the side that’s looking at the direction of the sun is brighter, and the other side is just in front of some clouds so it is visibly darker. That’s because in the shading step, I used the current point’s normal to sample the environment map for more realism.</p><h3>Water Plane</h3><h4><strong>Generating the Plane Mesh</strong></h4><p>The water plane is just a flat plane that exists at a certain height at first. This is extremely easy to create as I implemented tesselation in the previous part. There, I sampled splines to later create a terrain mesh, here the job is way easier. I just create a plane using a function that takes the 4 corners, the plane normal and the vertical and horizontal resolutions as input. Then we can just uniformly sample in between these points row by row and triangulate to form the mesh. After this we do the OpenGL array/buffer creation and upload steps and we’re done.</p><h4><strong>Cosine Waves</strong></h4><p>At this point we only have a flat mesh, but we want waves on our seas. We can see effects like these in a few ways. The most apparent could be changing the vertex positions using vertex shaders by using a trigonometric wave like cosine with a time parameter. This is the same as seeing a cosine wave on a plane instead of the 2D coordinate system.</p><p>Here, we can merge more than one cosine wave with different magnitudes, offsets and periods. By combining with different settings we can get more intriguing waves. Another thing to consider is that Y is the upper direction, whereas X and Z are the actual directions our water plane resides on. Instead of making the cosine waves move on just one direction, we can make them change with respect to both X and Z and have diagonal waves on the water plane. I tried a lot of different combinations here, and saw that when there are many waves, and also waves with small periods, the water looks tiled from certain angles. Because of that I decided to go with larger and more sparse waves by combining three cosine waves:</p><pre>    float w = 0.0;<br>    w += 2000.0 * cos(0.00007 * position.x + time * 1.5);<br>    w += 1500.0 * cos(0.00009 * position.z + time * 0.9);<br>    w += 1000.0  * cos(0.00012 * (position.x + position.z) + time * 2.3);<br>    return w;</pre><h4><strong>Normal Calculation</strong></h4><p>At this point the vertex coordinates change, but we also need to change the normals so that shading looks on point. I used the finite difference method here. We just get the height value of the current position, and the height value at a slightly x-offset height and a slightly z-offset height. Then we use these 3 new 3D coordinates to extract 2 tangent vectors and take the cross product to get the normal. We then reflect the viewing direction using this normal and sample the HDR environment map using this reflection vector. This is an extremely simple and intuitive method which gives good results.</p><p>Here are the sea and terrain meshes combined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxFBXpeB_3fJGkAfUfvDXg.png" /><figcaption>Waves and Terrain Image</figcaption></figure><p>As you can see, the environment map is also sampled similar to the terrain for shading, which gives us nice looking reflections.</p><h3>Plane Model</h3><h4><strong>Combining the Plane Model Components</strong></h4><p>The given plane model has 4 separate meshes to be combined: body, propeller, cables and cockpit. These are given as .obj files which are easy to parse so I’ll just pass that part. Three of these (propeller, cables and cockpit) require transformations to align to the body mesh. This is normal with most models as they are usually modeled separately and then combined into one. If you know the adequate transformation that lines up the parts, you can just pass that as the modeling matrix to the vertex shader, which is easy and what I did. But this will require some more work when the plane moves, and when we rotate the propeller. Another thing to note is the 3 plane parts propeller, cables and body use the same vertex and fragment shaders as they’re really straight forward, but the cockpit has separate ones as it needs careful attention about reflection.</p><h4><strong>Propeller Rotation Animation</strong></h4><p>This is relatively simple as we just rotate the propeller around its local Z direction before the other plane alignment and movement transformations. This is easily done by calculating a rotation angle based on time, and applying that. Here’s the propeller modeling transformation code:</p><pre>propeller_angle += delta_time * 700.0f;<br>glm::mat4 propeller_rot_transform = propeller_transformation<br>                           * glm::rotate(glm::mat4(1.0f),<br>                   glm::radians(propeller_angle), glm::vec3(0.0f, 0.0f, 1.0f));<br>plane_shader.set_uniform(&quot;model&quot;, plane_world * propeller_rot_transform);</pre><h4><strong>Cockpit Reflection</strong></h4><p>All 3 meshes other than the cockpit have textures and are straightforward. But the cockpit doesn’t have a texture, it needs to properly reflect the HDR environment map making it look like a shiny glass surface. This uses a similar technique to the water. The viewing direction from the camera to the cockpit point is reflected against the surface normal, and we just sample the HDR map with the resulting reflection direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p8B5kSlze4rTCoF-D-ZRSg.png" /><figcaption>Plane Model Image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HPxBMy9CuUOOOZWDv9wabw.png" /><figcaption>Plane Model Image 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KCb_mQftP8S2zd2whZgwA.png" /><figcaption>Plane Model Image 3</figcaption></figure><p>As you can see the plane body is shaded with the environment map, which creates some nice visuals. Observing the reflection of the cockpit is harder, as it is smaller and wide, but I rotated to show how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlyDd2o_xL5qJqAwOTO3lg.png" /><figcaption>Plane Cockpit Image</figcaption></figure><h3>Orbiting Camera and Controls</h3><h4><strong>Third Person Plane Camera</strong></h4><p>In the previous part, we controlled the camera. In this part, we mainly apply the same quaternion movements to the plane and follow it from a third person camera. The big difference is that the plane doesn’t have lateral movement like the previous camera. Other than that, we apply the exact same quaternion transformations to the plane position and orientation, then find the full transformation for all its vertices. While this happens, we need the camera to follow the plane from a distance.</p><h4><strong>Orbiting and Zooming</strong></h4><p>I use spherical coordinates to position the camera around the plane, basically using two orbit angles: orbit yaw and pitch. This defines the direction vector of the camera with respect to the plane, which gives us the camera’s orientation. There’s also a camera distance value I hold. When we scale this direction vector by the camera distance and transform it into world space using the plane’s orientation, we get the camera’s world position by adding it to the plane’s position.</p><p>The camera orbits around the plane by holding the right mouse button (RMB) and simultaneously moving the mouse. We can also zoom in and out to the plane by using the scroll wheel. This operation has some bounds that limits the camera getting too close to or too far from the plane.</p><h4><strong>The New Plane Flight Controls</strong></h4><p>The plane controls are extremely similar to the previous camera controls. Q and E apply yaw rotation which is exactly the same. W and S increase and decrease the plane’s forward speed instead of changing its absolute coordinates like before. Pressing the left alt and the left mouse buttons at the same time (LeftAlt + M1) while moving the mouse applies pitch and yaw with that single operation. There’s no roll here right now, which would be unrealistic for an actual flight simulation or game, but for this case it seems enough and makes things simpler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ar_u6DRqIlAYPjIp866LMw.png" /><figcaption>FlyOver Image 2</figcaption></figure><h3>Conclusion</h3><p>This part was definitely interesting and took things to a more complete state. It was fun to work on top of something I have completed before, I like the progression. This also feels more applied and real world, also nice in terms of the project’s nature. Other than that, I have always liked how HDR environment maps looked. In the Advanced Ray Tracer project, it was one of my favourite parts, I think they look so cool. It was nice to see it in real-time while moving around. The environment shading on the plane and the water also looked really nice.</p><p>I believe other stuff that could be added to the project that might make it a full-fledged OpenGL game. One idea is procedural terrain generation, where we can use Perlin noise to create grids with different levels of detail with respect to how close we are to them. This would ensure we do not actually see the ends of our terrain, and different grids connecting smoothly would be interesting to work on. The second thing could be instead of approaching the water as a global plane, putting smaller water layers to valleys or holes that are guaranteed to not produce weird waves. And also better and more complex wave simulations can be applied with similar structure. Another would be to actually implement realistic plane physics with gravity and perhaps wind. Combining all this stuff with a menu, a nice looking HUD and perhaps checkpoints to fly the plane through to get points make this a really nice and complete game.</p><p>I believe I will continue working on this project even if the next homework isn’t a continuation of it. But anyways, see you in the next part!</p><h3>References</h3><p>Akyüz, A. O. (2025–2026). <em>CENG469 Computer Graphics II course notes</em>. Middle East Technical University, Department of Computer Engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=512fdde1f314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FlyOver: Part 1]]></title>
            <link>https://medium.com/@Ksatese/b-spline-terrain-reconstruction-and-quaternion-camera-in-opengl-ec66491c0623?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec66491c0623</guid>
            <category><![CDATA[terrain-generation]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[3d-rendering]]></category>
            <category><![CDATA[quaternion]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 19:36:17 GMT</pubDate>
            <atom:updated>2026-05-04T08:31:23.313Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! It has been over a year since the last blog post I wrote and I am back. In this post I will briefly talk about stuff I recently had the chance to work on as part of the Computer Graphics 2 course at METU.</p><p>This part will be about terrain reconstruction using real life .dted height maps by fitting b-splines over them, and flying over this terrain using a quaternion controlled camera in OpenGL. So I will start briefly by how I structured the OpenGL base code, then move onto terrain reconstruction and the rendering of the terrain, and lastly the camera controls.</p><p>The next task in the course might be a follow up to this one, so this was an important one. If it appears to be a follow-up, I will probably change the title of this post and make the two a mini-series, so you can expect a change in the following weeks.</p><p>I will not make the code public yet, but again in a few weeks you can find it on my GitHub: <a href="https://github.com/distortedfuzz">github.com/distortedfuzz</a>. I don’t like writing code in my blog posts as I think code is not trivial for what we do but ideas are, and there’s no way I can put all relevant code here without throwing you off!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJqZZJTyrBGjWiIXWRQ96A.png" /><figcaption>Wireframe Terrain</figcaption></figure><h3>OpenGL Project Structure</h3><p>I have been doing computer graphics stuff since I took my first course on it more than 2 years ago. Since then OpenGL always felt hard to fully grasp and old for me. The API doesn’t fit the modern conventions at all, the usage of the libraries are outdated etc. So it has been always hard for me to come back to OpenGL after doing graphics work without it. Because of that the first thing I wanted to do was build a basic and powerful OpenGL template that includes the proper data handling and utility for VAOs, VBOs, EBOs, meshes and shaders. This is basically the path I found to make OpenGL simple without working on technicalities and buffer handling every time I want to create new stuff.</p><p>I believe the current structs, classes and functions are sufficient as the base template. It is simple and powerful while also leaving room for easy adjustments and new features. This is not directly relevant to the project itself but I wanted to briefly mention this as it made stuff so much easier for me! You can check it out when I publish the code.</p><h3>Terrain Reconstruction</h3><h4>DTED Height Maps</h4><p>In this project .dted heightmaps are used to create the terrain. The provided height map is from Dalaman, Turkey. What these files contain is longitude and latitude sample points with recorded height values. There’s a User Header Label which gives us the longitude and latitude of the origin corner which is at the bottom-left, also the longitude and latitude intervals in between the samples. Then there’s a section for the actual data where each scanline gives one longitude column. This is like iterating over the y values on a grid.</p><p>Parsing this file seems like a nightmare: there are certain byte values and offsets that needs careful handling, the height values are big-endian etc. Thankfully we were provided a default parser which worked great! I just changed some stuff according to my style and stuck with it. This parser basically gives us some valuable stuff: minimum and maximum longitude, latitude, height, number of rows and columns (latitude and longitude samples), and all height values (meters) at each sample.</p><p>So after parsing this file we’re basically left with all the height values, the size of the grid these height values stand on, and the data to find the actual geometric location at each height value. So this needs some extra processing to find the actual 3D sample points to use as b-spline nodes to create the shape of the terrain.</p><h4>Equirectangular Projection</h4><p>So it turns out after some search, we can map the latitude and longitude values to a 2D grid using equirectangular projection. I will leave the equirectangular projection Wikipedia page as a resource at the end of the post, but the projection formulae to be used are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*-dQw76jWBCIW2wCTgf1QbQ.png" /><figcaption>Equirectangular Projection (Wikipedia contributors, n.d.)</figcaption></figure><p>Here, λ is the longitude, φ is the latitude of the sample, λ₀ and φ₀ are the central latitude and longitude of the map. We can easily calculate the latitude and longitude values by using the min-max latitude-longitude ranges of the height map. φ₁ represents the standard parallel where we set the scale of the projection to be true, in this case I calculated this value as the average of the minimum and maximum latitude values. Lastly, R is the radius of the globe, which is 6371 kilometers. So after some dabbling and the need for not wanting to write that 6371 kilometers as meters, we end up with this:</p><pre>double x = (lon - longitude_range[0]) * METERS_PER_DEGREE_LATITUDE * cos(glm::radians(center_lat));<br>double y = height_values[i * column_count + j];<br>double z = (lat - latitude_range[0]) * METERS_PER_DEGREE_LATITUDE;</pre><p>So instead of directly handling that large number, adding the rather ugly longitude and latitude difference to center to radian casting to the radius gives us meters per degree latitude. This gives us a simple way to fill up the sample value coordinates to 3D: x as longitude, y as height, z as latitude.</p><p>It is also important to note that I created these 3D points once every 20 samples at each row and column. So I down-sampled a lot, which helps with keeping the terrain similar to real life while also giving a performance boost.</p><h4>B-Spline Fitting and Sampling</h4><p>So now we have geometrically accurate points along the surface that tell us what points the terrain should roughly go through. But this is not enough to create a mesh with good resolution which would actually be nice to look at. It is enough for us to use uniform non-rational b-splines here. I don’t want to delve that deep into curves and splines here as there are tonnes of resources you can find that would explain stuff better than I can here. But I will show you the overall formula I used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*gNGsHOvb8jzWDUVrtfOu5w.png" /><figcaption>Uniform Non-rational B-Spline from CENG469 Course Notes (Akyuz, 2025-2026)</figcaption></figure><p>Here, Q is the curve, G is the geometry/constraints matrix (each row is a point), M is the basis matrix. The important thing here is that each curve segment Q_i is defined in t_i ≤ t &lt; t_i+1, and each Q_i is only affected by 4 control points. The b-spline structs holds all the control points and goes 4 by 4 while producing samples.</p><p>To handle sampling, I used a segment sample frequency value that decides how many samples to be taken at each curve segment. This is also uniform, the first sample must be at t = 0, and then continues uniformly at the range [0, 1). t = 1 is not included as that would create duplicate points, it is only included at the end of the whole spline. With this strategy, the samples do not overlap, and are equally spread out through the terrain.</p><p>The height map is obviously 2D, so a strategy is needed to actually represent this whole grid. The strategy here is to create splines for each row and sample. Then create a spline for each corresponding sample at each row. So we fit splines normally for each row at first and sample, but instead of fitting splines for each column also, we fit splines for each corresponding sample at each row. An example would be to fit a spline through the 2nd sample of the 5th segment at each row. The segment sample frequency is the same for each row so this is guaranteed to work.</p><h4>Triangulation</h4><p>At this point, we have terrain points that were created by fitting splines through the initial height map points, and then sampling these splines. Now it is time to create the actual mesh from these points. This is extremely easy to do as we know the height map row and column counts, and the segment sample frequency.</p><p>The strategy I used here was to go row by row and triangulate the mesh, meaning setting up the triangle-vertex indices. Also here, the per-vertex normals are computed. These operations are done in parallel row-wise using OpenMP parallel for loops. This gives this process enough speed so that when the sampling frequency is changed, there’s no freeze.</p><h3>Terrain Shading</h3><p>So now that we have an actual terrain mesh, it is time to talk about the steps to visualize it properly. There are 3 shading modes available: Lambertian, Albedo and Normal shading. It is possible to cycle through these modes with the O and P keys on the app. There’s also the convention of giving the colors based on the height at the current point. So first I’ll talk about the height coloring, and then move on to the shading modes one by one.</p><h4>Height Colors</h4><p>I tried to follow geographic mapping color conventions during the coloring, but roughly changed it as how I like it, mixing the orders and percentages.</p><p>After the terrain is created, the height values at the 30th, 60th, 80th and 95th percentiles, and the minimum and the maximum are found. The minimum height corresponds to dark green, 30th percentile to bright green, 60th to brown, 80th to dark brown, 95th to bright grey and 100 to white. By linearly interpolating the colors based on the height values, I was able to create really smooth looking visuals.</p><h4>Albedo Shading</h4><p>Albedo is just the calculated height color values rendered as is. But again, the linear interpolation gives extremely smooth and nice looking visuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d68Uj4zuuk3DT-tsNCZgoA.png" /><figcaption>Albedo Shading</figcaption></figure><h4>Normal Shading</h4><p>Normal shading is also extremely simple. We already calculated the normals of the terrain. In the fragment shader, I just remap the normals to the [0, 1] range and use that for the coloring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZP9EmxbmYHm283vh-DXcw.png" /><figcaption>Normal Shading</figcaption></figure><h4>Lambertian Shading</h4><p>I decided to use Lambertian diffuse shading here. Could’ve gone for Phong with low or no specular shading, but terrain being shiny didn’t sit right with me at all. I add a little ambient lighting so that the shadowed areas do not look completely dark. These are extremely basic shading concepts. I believe if you want to learn more about these you can check out the LearnOpenGL Basic Lighting tutorial.</p><p>To calculate Lambertian shading, we need a light direction. I didn’t want to use a point light, as this is a terrain and we are outdoors and the light is coming from the sun which is so far away. Using a point light doesn’t really make sense. I set the direction such that the light comes from a 45 degree angle to our terrain. This way the scene isn’t too dark and we can see nice shadow-like features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZY2woaeFZ1hZmBL5xt0kw.png" /><figcaption>Lambertian Shading</figcaption></figure><h3>Quaternion Camera</h3><p>A big part of this task was to implement a camera with quaternion controls to wander around in this map we created. Quaternions are particularly nice convention to use for this, as they avoid gimbal lock when we implement yaw, roll and pitch movements utilizing them. Again here, I will briefly talk about what I did and not deeply explain what quaternions are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8JDbDLh01WL7G0wAg3J0w.png" /><figcaption>Yaw, pitch and roll axes of an aircraft (Wikipedia contributors, n.d.)</figcaption></figure><h4>Quaternion Operations</h4><p>The orientation of the camera is always kept as a quaternion, starting with the orientation (1, 0, 0, 0). Again, we implement the 3 generic orientation changing moves: yaw, roll and pitch. The basic approach for all 3 is the same, define a local direction, then transform this local direction into a world direction, create a quaternion that rotates around that world direction, and multiply this quaternion with the camera orientation quaternion. It is also nice to lastly normalize this quaternion. Overall, it looks like this for pitch:</p><pre>void camera::pitch(float angle) {<br>    glm::vec3 right_local = glm::vec3(1, 0, 0);<br>    glm::vec3 right_world = orientation * right_local;<br><br>    glm::quat pitch_rotation = glm::angleAxis(angle, right_world);<br>    orientation = pitch_rotation * orientation;<br><br>    orientation = glm::normalize(orientation);<br>}</pre><p>For yaw and roll, the local directions are up and forward respectively. At the end, these create a reliable and smooth camera.</p><h4>Position and Translation</h4><p>The position and overall translation of the camera is directly done by using regular vectors. To actually make the movement to a certain direction, we first find the direction using the current orientation of the camera. This is easy to handle by just multiplying the orientation by the local camera axes for each movement. For forward, backward, left and right, we would multiply the orientation by (0, 0, -1), (0, 0, 1), (-1, 0, 0) and (1, 0, 0) respectively. The orientation quaternion is then converted to a view matrix and sent to the vertex shader, combining the rotation and position to transform the scene correctly.</p><h3>Tessellation Rate and Height Scaling</h3><p>These are the other two features of this project. The tessellation rate (resolution) of the terrain is allowed to change at button presses. Same with scaling the height of the terrain. I will briefly explain how I handle these.</p><h4>Tessellation Rate</h4><p>As I have previously mentioned, I use a segment sampling frequency to decide how many sample points will be at each spline segment. The nice thing here is I never re-create or restructure the spline objects to be used. At button press to increase or decrease the terrain resolution, I run the per-row spline creation and sampling in parallel, and put all points in a container. Then (as I explained previously at the b-spline part) I create splines through each row’s corresponding samples and sample them. This is also done in a separate parallel loop. Then I run another parallel row by row loop to create the triangle indices, and then another one to recalculate the per-vertex normals.</p><p>Implementing this part extremely parallel helps with smooth transitioning if the tessellation rate is changed. In my PC I only see an extremely tiny bit of freeze if I try to change the tessellation rate while I’m moving the camera. The freeze seemed to be just a bit more noticeable on the computers at the department, but still was tiny.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CarSIcdaK3yzMad1N2hkyQ.png" /><figcaption>Segment Sample Frequency = 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-iHD0KW3iEC6rgEd0rYgA.png" /><figcaption>Segment Sample Frequency = 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ri03bdTddo-s3gcvwoKL4g.png" /><figcaption>Segment Sample Frequency = 3</figcaption></figure><p>I also wanted to limit the segment sample frequency value to 10. This number seemed to be enough as I couldn’t see much visual change after that point. And the lowest it can get is obviously 1. The controls for decreasing and increasing the frequency are J and K keys respectively.</p><h4>Height Scaling</h4><p>Another feature is height scaling, where at the press of the U and I keys, we scale the terrain’s height down and up. This is extremely straight forward to accomplish. We keep the height values at the y coordinates of our sampled points. It is easy to just scale the y values of each point by keeping a scaling value at hand and changing the vertex y values by multiplying by that scaling value.</p><p>To keep the shading accurate after height scaling, the normals also need to be transformed correctly. The model matrix is a scale matrix with height scale applied to the Y axis. The normal matrix is then calculated as the transpose of the inverse of this model matrix: N=(M^(−1))^T, and both are sent to the shader as uniforms.</p><p>Again, I clamp the height scale to be in the range [1, 100], and each button press changes the scale +/-5. Another detail here is that the terrain seemed a little too flat at the start when I did no height scaling, so I decided to add height scaling at the start also. The terrain starts with heights scaled to 50 and changed via button presses after that point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-ZruDzoIaFIBQOXbvo8Tg.png" /><figcaption>Height Scale = 50</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1DeuDpYzDRpw4nNVPI67w.png" /><figcaption>Height Scale = 100</figcaption></figure><h3>Other Details</h3><h4>Light Direction Control</h4><p>As I mentioned before, Lambertian shading is handled using a directional light that’s directed down on the terrain with a 45 degree angle. I added a feature that rotates this direction around the Y axis at right and left arrow button presses. The controls are continuous and we can see the light looping on the terrain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vj8AucvEwoFnWgAsICXFww.png" /><figcaption>Light Direction 1 (Default at start)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3Z2DJUp1NbSAH8Bgl4wGQ.png" /><figcaption>Light Direction 2 (A different one after pressing L/R arrow keys)</figcaption></figure><h4>Wireframe Mode</h4><p>The final small feature of this task is the wireframe visualization mode. You have already seen examples of this. This mode is not related to all the shading modes, it is handled by just changing the draw command to use the wireframe mode. It can be used with each shading mode independently and can be toggled by using the L key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CarSIcdaK3yzMad1N2hkyQ.png" /><figcaption>Wireframe Mode</figcaption></figure><h3>Performance</h3><p>I evaluated the performance on my own PC which has a Ryzen 7 9800X3D CPU and an RTX 5070Ti GPU. Here are the triangle counts and FPS values for different segment sample counts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*p8hlaLN0H081LxLlkhAQ4Q.png" /><figcaption>Performance Results</figcaption></figure><p>As you can see, the FPS values are always extremely high and the application doesn’t really make the computer sweat. I also added the segment sample count of 20 which is not allowed by the code normally.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZxrGGsj5bm0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZxrGGsj5bm0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZxrGGsj5bm0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9020778bade4c55df072ee36c6999d22/href">https://medium.com/media/9020778bade4c55df072ee36c6999d22/href</a></iframe><h3>Conclusion</h3><p>This was a great project to work on! I like splines and triangulation, combined with real time stuff, it was really fun and gave impressive results. The new OpenGL template I created definitely helped in the process, and the new stuff I learnt about height maps are definitely a plus. If the next task turns out to be a follow-up to this one, I am genuinely excited. There is a lot of room to build on top of this terrain renderer and I would love to see where it goes.</p><h3>References</h3><p>Akyüz, A. O. (2025-2026). <em>CENG469 Computer Graphics II course notes</em>. Middle East Technical University, Department of Computer Engineering.</p><p>Baba, E. (2026, April 1). <em>Terrain renderer</em> [Video]. YouTube. <a href="https://www.youtube.com/watch?v=ZxrGGsj5bm0">https://www.youtube.com/watch?v=ZxrGGsj5bm0</a></p><p>de Vries, J. (n.d.). Basic lighting. In <em>LearnOpenGL</em>. Retrieved April 1, 2026, from <a href="https://learnopengl.com/Lighting/Basic-Lighting">https://learnopengl.com/Lighting/Basic-Lighting</a></p><p>Wikipedia contributors. (n.d.). Aircraft principal axes. In <em>Wikipedia</em>. Retrieved April 1, 2026, from <a href="https://en.wikipedia.org/wiki/Aircraft_principal_axes">https://en.wikipedia.org/wiki/Aircraft_principal_axes</a></p><p>Wikipedia contributors. (n.d.). Equirectangular projection. In <em>Wikipedia</em>. Retrieved April 1, 2026, from <a href="https://en.wikipedia.org/wiki/Equirectangular_projection">https://en.wikipedia.org/wiki/Equirectangular_projection</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec66491c0623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Geodesics, Farthest Point Sampling and Coons Patch]]></title>
            <link>https://medium.com/@Ksatese/geodesics-farthest-point-sampling-and-coons-patch-591040c1e646?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/591040c1e646</guid>
            <category><![CDATA[geodesic]]></category>
            <category><![CDATA[geometry-processing]]></category>
            <category><![CDATA[patching]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[sampling-methods]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 19:47:47 GMT</pubDate>
            <atom:updated>2026-05-03T19:37:24.089Z</atom:updated>
            <content:encoded><![CDATA[<p>I am back after a couple of weeks! This part will work as an introduction to geometry processing. I will start by explaining basic geodesics, then move on to the farthest point sampling method. Lastly, I will move on to a more interesting topic: patching.</p><p>This is the first blog post I will be writing about geometry processing, but I have mentioned it previously. I wrote in ‘Advanced Ray Tracing: Part 4&#39; that I might write about mesh parameterization, but I did not have the time nor the motivation to actually get hands down on it. I have implemented a lot regarding that topic and planning on turning it into a seperate project with a 3–4 part blog series. I do not know when I will do that as I have a lot on my plate as of now, but that will definitely happen some time in the future.</p><p>As always, the tests are conducted using the Apple MacBook M3 Pro chip with 5 performance cores with 4.06 GHz and 6 efficiency cores with 2.8 GHz. Let’s get into it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CogyXxl6-P7rL1lsWB073A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e3mFZAL2T1zO2VftThxm7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HIUdo-Hbc5wOBRx0S3NaJw.png" /><figcaption>Patch Examples — Segeval 323.off</figcaption></figure><h3>Environment</h3><p>I have used Coin3D for a couple of months up until this point. It is an open source version of the Open Inventor API. It seems to be a popular choice, but I could not make it work properly in my PC. I use a Mac, and I believe the documentation on the installation process was not clear enough, as there are too many variables. So the Coin3D in my PC never had the trackball or the navigation features. The programming aspects worked fine and I could color and view the mesh properly, but the navigation did not work. I had to write the code to move around using the mouse and the WASD keys. It was not a good experience.</p><p>Starting with this part, I will be using Polyscope. It is definitely way easier to setup, and use. I believe it is more intuitive and you can view any kind of structure with a couple of lines of code. It also uses ImGui which you can see in most modern projects. I like it a lot. The only downside is that sometimes it lacks the freedom Coin3D provides, but I think it is far more ignorable than the upsides. I would recommend it because of the ease of use, and will leave a link in the references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ArN_TFxWV3osa07WiSPlGQ.gif" /><figcaption>Polyscope Demo — polyscope.run</figcaption></figure><h3>Geodesics</h3><p>While traversing through the mesh, finding the shortest distance between two vertices always comes in handy. The result of taking a path on the mesh while doing this is called geodesic distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*cuEo-sRbN6ZliwpopL4IuQ.png" /><figcaption>Distances — Lecture Slides by Y. Sahillioğlu</figcaption></figure><p>The simplest way to do this is using Dijkstra’s algorithm. I do not want to explain the whole algorithm in depth as it would take a long time and it is pretty well-known. If you do not know anything about his algorithm, I believe this video by Computerphile would help you understand it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGazC3A4OQTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGazC3A4OQTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGazC3A4OQTE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b78e8ea2911e372b3a92f59cc121be0/href">https://medium.com/media/0b78e8ea2911e372b3a92f59cc121be0/href</a></iframe><p>I have implemented 3 different versions of this algortihm to compare. The first one, I used a simple array structure. Obviously this does not really work well as I search through the array to find the next closest node each time, so it is too slow.</p><p>The second one, I used a minheap. I believe this is the most generic implementation of Dijkstra’s algorithm. I just created a min-heap using the standard priority queue. This worked a lot better as it is way more efficient for this algorithm.</p><p>The third one, I used a Fibonacci heap. There is no standard library to do this so I found a header only library on GitHub called fiboheap by Emmanuel Benazera. This also worked great and I made use of decreasing the key values. I wouldn’t say there is much difference between this and the standard min-heap, but here are some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNTkmVZ0marJIGjvIVXaSQ.png" /><figcaption>man.off — Dijkstra from sample index 0</figcaption></figure><p>For this human mesh, starting from the shown sample, the Dijkstra times were:</p><blockquote>Array: 19.8937 seconds</blockquote><blockquote>Heap: 0.292647 seconds</blockquote><blockquote>Fibonacci Heap: 0.288069 seconds</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1mo5fHezFGKYc2D01vK9g.png" /><figcaption>centaur.off — Dijkstra from sample index 0</figcaption></figure><p>For this centaur mesh, starting from the shown sample, the Dijkstra times were:</p><blockquote>Array: 1.839 seconds</blockquote><blockquote>Heap: 0.088206 seconds</blockquote><blockquote>Fibonacci heap: 0.08675 seconds</blockquote><p>The array approach has a complexity of <strong>O(V^2)</strong> and heap should have something like <strong>O((V + E) log V). </strong>The times I ended up with closely align with these complexities.</p><p>As you can also see, the Fibonacci heap looks to be just marginally better than the normal heap, but this difference would accumulate into a larger difference when we run Dijkstra’s algorithm a lot of times. So using this is much better!</p><p>At this point, we can also create a path from this starting vertex to the farthest vertex we can find from it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSeYU78kPrZ_GbMATjesvA.png" /><figcaption>man.off — Farthest point path from vertex 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g41i4_ONcffAj3AQGTNiuw.png" /><figcaption>centaur.off — Farthest point path from vertex 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYrHnWWcYJ-8CQeyt7lNZw.png" /><figcaption>centaur.off — Farthest point path from vertex 0</figcaption></figure><p>So having done this, we can move on to farthest point sampling.</p><h3>Farthest Point Sampling</h3><p>Farthest point sampling is a fairly easy sampling method to grasp. First, we pick an arbitrary vertex on the mesh. Then, we run the Dijkstra’s algorithm using that vertex as our start. We get the farthest away point and add it to our samples. Now, we just forget about the original arbitrary vertex we picked, and run Dijkstra’s on the farthest away one. Again, we add the 2nd farthest away vertex to our list of samples.</p><p>So right now we have 2 vertices (a and b) that are the farthest away from each other. Next, we partition the rest of the vertices to find out which ones are closer to a, and which ones are closer to b. Then, we check their distances to whichever original vertex a or b they are closer to. Out of all these vertices, we add the one with the max distance to the original vertex it is closer to, to our list of samples.</p><p>This continues until we have the required amount of samples. For example in the next step, we would have 3 existing samples and we would partition the mesh into 3 parts.</p><p>This gives us a fairly good sample set as the samples are far away from each other and represent the whole mesh:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5OaR_8T_y5qZa3c6dMrQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJLpQEpa7uN-n3Dn8-rRHw.png" /><figcaption>man.off — 6 FPS Samples</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQxrZE5LiVrpcjkkSmgupg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OV6LNtfEXWve74bAWCx9ZQ.png" /><figcaption>centaur.off — 9 FPS Samples</figcaption></figure><p>As you can see, the FPS sampling looks to be working as expected.</p><h3>Patching</h3><p>This part was quite tricky as it was more experimental. We had no actual deformed mesh particularly made for patching purposes. I needed to produce the area to patch myself.</p><h4>Producing the Patch Area</h4><p>The supposed way to get the area to patch in this part was to get the intersections of 4 geodesics between our FPS samples. To do this, first I needed to form these paths.</p><p>I needed to get each unique geodesic path between each sample. As we always end up with path with minimum length, the path would not change if I start from sample a, instead of sample b of a path. So this is quite easy to do, and it is like a primary school problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ts_TgmguXH7R2ba4RH96XQ.jpeg" /><figcaption>Paths Between Farthest Point Samples Representation</figcaption></figure><p>The results look like this after I form all paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0n09QVp_w4_4QnEDNYnCQ.png" /><figcaption>man.off — Geodesic Paths Between 6 Samples</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPS6QcbmoGKFxg7EqfepQA.png" /><figcaption>man.off — Geodesic Paths Between 6 Samples</figcaption></figure><p>The same as in the drawing I made, if I have 6 samples, I should have 15 paths. This is the exact case in this man mesh. You can also observe that each sample is connected to 5 paths.</p><p>Here is what the centaur looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsR0aIO5EMbT1Cbeg9yfPw.png" /><figcaption>centaur.off — Geodesic Paths Between 9 Samples</figcaption></figure><p>Then, I needed to find path quadruples that intersect in 4 different vertices, each of them twice. This would cause them to roughly form a rectangular area (as youwill see later the area boundaries are not actually rectangular but this gives us a way to meaningfully patch that area).</p><p>This quadruple aproach provides us with sufficient areas if we use a large FPS count, however most of them are not that meaningful. Most of the areas are at really weird places and they turn and bend. They are also too large. When the FPS sample count is too high, the number of areas jumps up to hundreds. So there is not an easy way to find an actual good case to use patching, but I found some and will share the results with you. Nevertheless, I wanted the patching algorithm to work with any bending or turning boundary, and to fit that boundary’s vertices one-to-one, so that if there was an actual patch, it would fit in perfectly. The next step is the preparation for this.</p><h4>Patch Boundary Heuristic</h4><p>After finding the 4 boundary lines of the area I will patch, I wanted pick the ones facing each other in a meaningful way. I called them start column, and the other one facing it the end column. I did the same with the rows.</p><p>While patching, I did not want the area to have a lower triangle resolution. To achieve this, I decided that I would pick the start column and the start row to have the lower number of vertices of the corresponding end columns and rows. Another thing is that start and end columns are reversed if they do not start from the start row. So I guess you now have a clear view of how we align everything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phYlf1CkC3GY8ixQ8xL5Jw.jpeg" /></figure><p>So, let’s say that I have 4 boundaries: a, b, c and d. a and c face each other, the same for b and d. If c has smaller number of vertices than a, c is the start row, and a is the end row. Then I would pick the same number of start row vertices of uniform samples in the end row. So I would have the same number of samples in the rows and in the columns. This approach would be beneficial in easing the interpolation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaohd5ya7YzZ69FcjXwgxw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6m9w50cBBXGN6Vwg30GCg.jpeg" /></figure><p>But this will not fit the original patch area perfectly, as we just picked some samples in the end row and columns. They do not represent the whole boundary. To do this, there will be a last longer column, longer row process. I will patch until the last row and column. Then at the last one, I will forget about the uniform samples I picked on the longer boundaries, and just match all of the vertices in those boundaries with the last patch vertices I have produced. Here is a representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aqsi3a-7UAXxirWcOxrGdw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPX_aPYmtKXLqRL4Dvr5hw.jpeg" /></figure><p>But how do we actually generate the vertices (the blue ones) in between these 4 boundaries with the same number of samples facing each other?</p><h4>Subpar Patching Approaches</h4><p>This part was especially gruesome. I tried 4–5 ways to do this before settling on one. First, I decided to get the weighted average of the row and column vertices seperately, and then take their average. This did not work well. Then I decided to go row by row, and just uniformly create new vertices in that row to see if it roughly worked. It worked as expected, but obviously did not produce optimal results. Another thing I did was to shift the newly created vertices by taking the weighted average of the corresponding column edge vectors in the start and end rows. This worked a little better but did not change things much.</p><p>I also tried to get the weighted average of the corresponding start and end row vectors and adjust its magnitude so that the samples end roughly at where they should. This caused them to go out of bounds of the patch area.</p><p>Do not get me wrong, these approaches worked for small and roughly planar surface, like how you would imagine. But for patches that have high curvature turns and twists or just a small bend to it, they just did not work well. I needed a different approach.</p><h4>Coons Patch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtuoPxvh59gh-S6YeQ5l5w.png" /><figcaption>Coons Patch — Wojciech Mula, Wikipedia</figcaption></figure><p>Coons patch is a patching strategy that uses the 4 curves and the 4 corner points similar to our use case to patch the inner. You can pretty much get the idea from the Wikipedia page, but I will try to explain it here as much as I can.</p><p>To be honest, here I was over my head and did not get the concepts that clearly, just tried to make some sense and implement. But what I got is, like my original approach, we get the weighted average of the curves that are facing each other, like the start and end row and columns I have created before. Appearently this is kind of similar to one of my first approaches, but I did not know that at the time. This produces two ruled surfaces, there are straight lines between the curves facing each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*J85P5Rxi1wb2548eISZb1Q.png" /><figcaption>Linear Interpolation in Start — End Rows and Columns — Wikipedia</figcaption></figure><p>Then, we calculate the bilinear interpolation of the four corner points:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*Lpfbwcgz6R_nykfk8fEg4g.png" /><figcaption>Bilinear Interpolation of Corner Vertices— Wikipedia</figcaption></figure><p>Then a bilinearly blended Coons patch is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*IraLUSUgpG71rJPr16ctUw.png" /><figcaption>Bilinear Blend — Wikipedia</figcaption></figure><p>But I did not have actual curves to calculate this, I just had some geodesic paths on a 3D mesh. I needed to evaluate splines somehow.</p><h4>Catmull-Rom Spline</h4><p>This issue bothered me and I wanted to somehow create splines to apply the Coons patch formula. I stumbled upon Catmull-Rom splines while looking for a way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*vfKjsulbLypEbvOpDZZOpg.gif" /><figcaption>Catmull-Rom Spline Representation — MVPS</figcaption></figure><p>It is appearently one of the easier splines to work with and in this site, there is a clear description of how to form a basic one with 4 control points written by Robert Dunlop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*sTwxTmxhRXCZqy4cysDH1w.png" /><figcaption>Catmull-Rom Spline Formula — MVPS</figcaption></figure><p>As you can see, we have 4 control points. The input <em>t </em>is where we want to get between the main samples P1 and P2. P0 and P3 seem to work as controllers for smoothing out the spline more. These specific constants in the formula are also important. Appearently for these specific numbers, these properties hold:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udcX7uK1Do9ZS-HAWgQh_g.png" /><figcaption>Catmull-Rom Spline Example Characteristics — MVPS</figcaption></figure><p>These characteristics should be sufficient for our use case, so I used these exact numbers to calculate my splines.</p><p>As I said before, the original Coons patch just consists of four space curves which meet at four corners, but we only have boundaries of vertices. I could not evaluate a spline through all of that boundary and do calculations like that as it would definitely go out of bounds. What could be done was use the boundary corners for bilinear blending as same as the original formula, but calculate local 4 vertex splines for each row we calculate locally. So instead of working on 4 huge splines, I needed to evaluate 2 splines for each row, and then 2 for each vertex in that row for the corresponding column. This worked surprisingly well and I actually got some good results. This is still not ideal. As I go through row by row, the patches look ‘steppy’, but nevertheless work for every area.</p><h4>Patch Generation</h4><p>After finding all of the inner vertex coordinates, I went row by row through them starting from the row with the smaller vertex count (start row) and ended just before the end column and the end rows. I then created triangles in the last row and column by checking which patch vertex these original vertices are closer to. This does not work that well as it produces some really thin and wide triangles. To be better it might need some post processing or a different approach that would actually smoothly blend triangles in the patch, but this is the best I could do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aqsi3a-7UAXxirWcOxrGdw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPX_aPYmtKXLqRL4Dvr5hw.jpeg" /></figure><p>At the end, I had a fairly smooth patch that fit exactly in the corresponding boundary of the mesh. Each boundary vertex is at the same point at every test I have run. So I would call this a success.</p><p>Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R76brFat0rtwnDvji6lr-Q.png" /><figcaption>Centaur Patch 10 — Matching Vertices</figcaption></figure><p>As you can see the vertices match. This is the case also for the bigger areas, but it is harder to show that in just an image.</p><p>We can also observe the curve of the patch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38hKYJ5xXW7kRRdJnn6HsA.png" /><figcaption>Centaur Patch 10 — Patch Curve</figcaption></figure><h3>Application</h3><p>To make this more interesting, I added a feature to the Polyscope GUI. I wanted to be able to see all of the geodesic path quadruple patches created on the mesh with a specific farthest point sample count. I decided to create all of these patches in a multi-threaded manner. In the GUI, the user can see any one of these patches they want. By changing the patch, the boundary around the patch also changes accordingly.</p><p>You might think right now that the first multi-threaded step of finding all of the patches might take a long time, but it does not. Even in the example in the demo video took around 2–3 seconds to create all of the 156 patches in the mesh. So this algorithm actually works really fast!</p><p>I have recorded 2 demo videos of the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaO0O1Zah-ac%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaO0O1Zah-ac&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaO0O1Zah-ac%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8631245ed4a45afd1f2a9b94f9c3390/href">https://medium.com/media/c8631245ed4a45afd1f2a9b94f9c3390/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-vzolp_x7mE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-vzolp_x7mE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-vzolp_x7mE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3431f8365d8067a4c7459848fae244b0/href">https://medium.com/media/3431f8365d8067a4c7459848fae244b0/href</a></iframe><p>As you can see, sadly in most path quadruples, the area is way too big, so the algorithm can not form a reasonable patch for the mesh.</p><h3>Downsides</h3><p>I believe one of the downsides is that in some edge cases, or when the boundaries are weirdly connected, it folds into itself and intersects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvqfvzTKwdNiNZP0q_YNAw.png" /><figcaption>Problematic Vase Patch</figcaption></figure><p>I believe the problem stems from the green and pink boundaries forming a corner with each other at a point where it neither fits the geometry nor our Coons patch structure.</p><p>Another smaller one is that this was an experimental project and I did not actually have meshes to patch, but created them using the geodesic paths between farthest point samples. And as I mentioned just now, this created areas that were too big or too twisted to be actual use cases for a patching algorithm. I found some that are smaller to showcase. Nevertheless, the algorithm works on all of them so I do not know if this is really a downside.</p><p>A bigger one is that I found out while testing that my algorithm for turning the created vertices into a mesh patch does not work when one of my area boundaries has 2 vertices, or 1 edge. The vertex count cannot be 1 for a boundary as it would not be a boundary in that case. But when the boundary length, edge count-wise, minimum, it does not work, and I remove those cases in the code.</p><h3>Conclusion</h3><p>The refreshment of coding a mesh class from scratch was great! I also love working on algorithms so working on 3 different Dijkstra approaches and analyzing them was also a blast. The farthest point sampling part was fairly easy to implement as it is a quite simple concept. All of these were done in 2 days of a couple of hours of work.</p><p>The patching part is what was difficult. The amount of thought and research I have given to it took probably as much time as the geodesics and FPS parts combined. My previous approaches to patching are still left there in the code. So all of this setup, thinking and researching aside, I wrote more than 2000 lines of code in a week. This is not me complaining, I just wanted get good results. And at the end, I think it all paid off!</p><p>You can find the GitHub repository of this project in my profile: <a href="https://github.com/distortedfuzz">https://github.com/distortedfuzz</a>.</p><p>I do not know what comes in the next part of this geometry processing series, but stay tuned. I think it will be fun.</p><h3>References</h3><p>Chen, X., Golovinskiy, A., &amp; Funkhouser, T. (2009). <em>A Benchmark for 3D Mesh Segmentation. </em>Retrieved March 8, 2025, from: <a href="https://segeval.cs.princeton.edu/">https://segeval.cs.princeton.edu/</a></p><p>Computerphile. (2017, January 4). <em>Dijkstra’s Algorithm - Computerphile </em>[Video]. YouTube. <a href="https://www.youtube.com/watch?v=GazC3A4OQTE">https://www.youtube.com/watch?v=GazC3A4OQTE</a></p><p>Coons patch. (n.d.). In <em>Wikipedia</em>. Retrieved March 15, 2025, from: <a href="https://en.wikipedia.org/wiki/Coons_patch">https://en.wikipedia.org/wiki/Coons_patch</a></p><p>Dunlop, R. (n.d). Introduction to Catmull-Rom Splines. <em>MVPS</em>. Retrieved March 15, 2025, from: <a href="https://www.mvps.org/directx/articles/catmull/">https://www.mvps.org/directx/articles/catmull/</a></p><p>Mula, W. (n.d.). [Photograph]. Wikimedia Commons. <a href="https://commons.wikimedia.org/w/index.php?curid=28945837">https://commons.wikimedia.org/w/index.php?curid=28945837</a></p><p>Sahillioğlu, Y. (n.d.). <em>CENG789 — Digital Geometry Processing: 05-Mesh Comparison [Lecture Slides]</em>. Retrieved March 15, 2025, from: <a href="https://user.ceng.metu.edu.tr/~ys/ceng789-dgp/05-comparison.ppt">https://user.ceng.metu.edu.tr/~ys/ceng789-dgp/05-comparison.ppt</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591040c1e646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Ray Tracer: Part 7]]></title>
            <link>https://medium.com/@Ksatese/advanced-ray-tracer-part-7-5fe95cd69a1a?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe95cd69a1a</guid>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 16:33:43 GMT</pubDate>
            <atom:updated>2025-01-23T17:02:10.533Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part I tried to implement volume rendering with ray marching. I could only achieve a fraction of what I planned to do but will still explain the general idea and the concepts up to that point. Volume rendering is extremely complicated and I had little time to spend on it due to poor time management. But let’s get to it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGLIi9Pbxqq8cZPJj5N5Jg.png" /><figcaption>Dragon Cloud</figcaption></figure><p>Volume Rendering</p><p>Up until now we have only rendered the surfaces of the objects, but to render volumes we need to also take their densities into account. The full volume rendering equation looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krCKkaVt587aj2StnVCEPQ.png" /><figcaption>Volume Rendering Equation — Cem Yüksel’s Volume Rendering Video</figcaption></figure><p>Let’s take a look at the main part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYfJ4UXEv4Aru9Ym6FGyRQ.png" /><figcaption>Main Equation — Cem Yüksel’s Volume Rendering Video</figcaption></figure><p>The part on the left represents the light coming from the object behind the volume, multiplied by the transmission function. The transmission function is basically how much light is lost while traveling through the volume. So that part is pretty basic. The right side is more complicated. In the integral, z is a point inside the volume on the ray we sent from the camera. T is again the transmission function, Lm is the light that reaches that point from light sources and sigma_t is the extinction coefficient. So let’s go through these one by one to understand what they mean.</p><p>The sigma terms are:</p><blockquote>sigma_a , absorption coefficient = k_a * d(x)</blockquote><blockquote>sigma_s , scattering coefficient = k_s * d(x)</blockquote><blockquote>sigma_t , extinction coefficient = sigma_a + sigma_s</blockquote><blockquote>The absorption coefficient represents how much of the light gets absorbed by the volume.</blockquote><blockquote>The scattering coefficient is used to represent how much of the light scatters which we will go more in depth later.</blockquote><blockquote>The extinction coefficient is like the total light energy that interacts with the volume.</blockquote><p>I set k_a and k_s constants in the scene file. d(x) is the density function of the volume. We get the density value of the point we are sampling with this. This could be a constant or a procedural noise function for stuff like clouds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*kdLkFuVB60F8Vq28L0pB8A.png" /><figcaption>Transmission Function — Cem Yüksel’s Volume Rendering Video</figcaption></figure><p>The transmission function is similar to exponential decay we used back in part 1 while rendering dielectrics. As you can see we also have the extinction coefficient in the power here, but it is still mainly the same.</p><p>Beer’s law is pretty commonly known in physics and rendering stuff like this and this is the version from part 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*VjZXZ30EfSdbPB8JRChgnQ.png" /><figcaption>Beer’s Law — Course Notes by AO Akyüz</figcaption></figure><p>What is different here is if we want to render stuff like clouds, the transmission inside the object won’t be the same at every point, remember the density function. If we look at this whole operation as an integral representing how much energy we lose inside the object, we can not calculate it directly like this. We need to do ray marching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*BZW3lXkPEFNp4zwDp5d7Ng.png" /><figcaption>Riemann Sum — math.net</figcaption></figure><p>As we can’t directly take the integral, we can step through the volume, take the value there and sum all of it up as we go to represent the total opacity up until that point through the ray we sent. This concept of ray marching is pretty similar to the Riemann sum from basic calculus. This operation will help us calculate the total transmission at a point.</p><p>Another crucial point is that volumes like clouds don’t only stop light from going through them, but they look like surfaces themselves and reflect color to the viewer. This is represented by the Lm value in the main formula and this is how it’s calculated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVrOA0TNrDDUyPb4CwXvUA.png" /><figcaption>Light coming from a point in the media — Cem Yüksel’s Volume Rendering Video</figcaption></figure><p>The left side accounts for any emission that could happen in the volume. This, we would use in stuff like fire and explosions and it is pretty complicated and a big area in itself, so I will not focus on that now. The right side is what we want to focus on, which accounts for scattering.</p><p>Within stuff like glass similar to those in part 1, we assume the light scatters isotropically in them. Within stuff like clouds or smoke, that is not the case and light tends to out or in-scatter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*4vTWvQaoCSJ790mjY9V0kg.png" /><figcaption>Scattering — Scratchapixel</figcaption></figure><p>We represent this phenomenon with the phase function which is represented with p. The most widely used phase function I could find is the Henyey-Greenstein phase function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*JafvX6sjglZzBNQHVP13Bw.png" /><figcaption>Henyey Greenstein Phase Function</figcaption></figure><p>g is the asymmetry parameter and theta is the angle between the light ray and the viewing ray. g &gt; 0 represents in-scattering and g &lt; 0 represents out. And the last thing is the L inside the integral which is the light that reaches the point inside the volume. As you might guess, light coming from the light source also travels through the volume and loses energy. To calculate that we also ray march to the light source. So at the end we ray march through the viewing ray and for every point we sample, we also ray march to the light source. We should do this for every light source. And also multiply with the ratio of scattering to extinction to get how much scattering affects the calculation.</p><p>There is a problem left here. In this calculation, we assumed light scatters only once through the volume but that is not the case in reality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*UzL2vT082jQwdgxVwHR-Vg.png" /><figcaption>Single vs Multi-Scattering — Scratchapixel</figcaption></figure><p>I do not want to focus on how to approximate this multi-scattering phenomena as I did not implement it, but just know that this is the case.</p><p>We have still not talked about what density function we can use. In part 4, we have implemented multi-octave Perlin noise and that is used in some cases. A better option would be Worley noise mixed with Perlin noise. Worley noise gives us the billows that clouds usually have which we can’t have with Perlin noise.</p><p>So my whole plan was to implement the ray marching algorithm first, as without it I cannot render volumes at all, then I would implement Perlin-Worley noise and lastly multiscattering approximation to get more realistic results. The sad reality is I could only implement the first step which is actually the whole volume rendering equation I explained. The issue is the constants and coefficients did not exactly act like I expected them to, so something is definitely up with the implementation of the ray marching algorithm, but it is the full implementation the formula. Here are some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGLIi9Pbxqq8cZPJj5N5Jg.png" /><figcaption>Dragon Cloud — 25 Samples — 0.1 step size — 263.86 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLDanDiIDGTy_-idCLKNTw.png" /><figcaption>Dragon Smoke — 25 Samples — 0.1 step size— 263.75 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8l0UlAItmYTVOs1l3nw8PQ.png" /><figcaption>Dragon Dark Smoke — 25 Samples — 0.1 step size —263.79 seconds</figcaption></figure><p>I do not want to share the scattering constant, absorption constant and asymmetry parameters as I highly doubt they work properly.</p><p>So as you can see I could render volumes in this scene with ray marching as the attenuation and transparency are pretty apparent (check below the stand the dragon is on and the wings), but they do not look good as I did not have the time to play with different settings and noises. Also the ray marching algorithm has problems itself that I already know of, it currently only works with point lights and I could not prepare any other scenes with different coefficients (I thought this would look cool but the thin wings look kind of weird at the end). But at this point I decided it won’t get much better as I had too little time and feared I would break something else. So I just gave up and decided to write this blog post.</p><h3>Conclusion</h3><p>The volume rendering looks pretty bad right now and I did not do a good job. A big chunk of what I have planned on doing, I could not make happen. Perhaps I will continue working on this subject in the following weeks but this feels like a disappointing break to the series. But thanks again to AO Akyuz and classmates as this is the definite end to the course. This was a great experience. Thank you!</p><h3>References</h3><p>Akyüz, A.O. <em>Lecture Slides from CENG795 Advanced Ray Tracing</em>. Middle East Technical University</p><p>Scratchapixel. (n.d.). <em>Volume rendering for developers</em>. Retrieved December 31, 2024, from <a href="https://www.scratchapixel.com/lessons/3d-basic-rendering/">https://www.scratchapixel.com/lessons/3d-basic-rendering/</a>volume-rendering-for-developers/intro-volume-rendering.html</p><p>Smith, J. A. (2023). Riemann Sum. Math.net. <a href="https://www.math.net/riemann-sum">https://www.math.net/riemann-sum</a></p><p>Yüksel, C. (2022, April 13). <em>Interactive Graphics 25 — Volume Rendering</em> [Video]. YouTube. <a href="https://www.youtube.com/watch?v=y4KdxaMC69w&amp;t=3591s">https://www.youtube.com/watch?v=y4KdxaMC69w&amp;t=3591s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe95cd69a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Ray Tracer: Part 6]]></title>
            <link>https://medium.com/@Ksatese/advanced-ray-tracer-part-6-f7978842081f?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7978842081f</guid>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[brdf]]></category>
            <category><![CDATA[path-tracing]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 15:51:20 GMT</pubDate>
            <atom:updated>2025-01-21T15:51:20.278Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part I will talk about BRDFs, object lights, path tracing and different ways and configurations of all of these. There is a lot of stuff I will cover, and I will go in the order I just mentioned. Although I would say that I have implemented everything required, there are some small issues I couldn’t solve because of time constraints. I wanted to get the most out of this part, so I decided to spend more of my time on this part rather than the next one which I will have to upload by a couple of days. Anyways, I think I did a good job given that it was a crucial time of finals, last homeworks and I also had some important stuff to do for another project.</p><p>Although we will get to its specifics in the 3rd section of this post, I guess this part could be described as ‘path tracing’ as a whole. The first to sections, BRDFs and object lights are basically requirements and will give us the tools to implement some path tracing concepts. At least proper path tracing was my end goal for this part.</p><p>As always, all images seen in the post are rendered by my raytracer. The tests are conducted using the Apple MacBook M3 Pro chip with 5 performance cores with 4.06 GHz and 6 efficiency cores with 2.8 GHz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PwUxNq2Wmm6ffyMPSdHKrA.png" /><figcaption>Diffuse Importance NEE Prism Light — 2500 samples</figcaption></figure><h3>BRDFs</h3><p>BRDF is short for bidirectional reflectance distribution function. I know it can sound daunting at first, but it basically defines how light is reflected off an opaque surface. To understand this better in our concept, we can take a look back at the rendering equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*GlnXxTm635LlTn3lVMnXtg.png" /><figcaption>The Rendering Equation — Lecture Notes by A.O. Akyüz</figcaption></figure><p>As you can see, the BRDF is the f(x, wo, wi) term, which we handle together with the incoming light to the point. This is basically the shading term we used in part 1 where we split it into diffuse and specular terms. That was Blinn-Phong shading, but that is not the only BRDF we can implement. In most cases the diffuse component is the same for pretty much all except the different normalizations we apply. So we can expect the differences to be mainly in the specular term. Let’s go over them one by one.</p><h4>Blinn-Phong</h4><p>This is mostly the same with what we did in part 1. We calculate an half vector and use that to calculate the specular component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vD5Q23pUtAKsQhxyRFE_Yw.png" /><figcaption>Original Blinn-Phong — Lecture Notes by A.O. Akyüz</figcaption></figure><p>As you can see, we get kd as is and we do the same operation as we did before with the half vector for the specular. This should give the same result as the original shading we did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YCW5VtFbLpzeE1QGrrHcoA.png" /><figcaption>Original Blinn-Phong</figcaption></figure><p>Another thing we can do is a simple modification where we erase the cos(theta_i) from the denominator. As I understand, this operation will simplify the BRDF and later allow us to easily make it energy conserving by scaling it with a normalization factor. We will get to this in the next step, but right now the modified formula and result look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5ZWD5yeTYguEXPR3D0Ftw.png" /><figcaption>Modified Blinn-Phong — Lecture Notes by A.O. Akyüz</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*TmqGhwAIzQpqe5NG95dN6A.png" /><figcaption>Modified Blinn-Phong</figcaption></figure><p>Now let’s get to the normalized modified Blinn-Phong. To understand normalization, we also need to understand this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rU-7StHA7fytTK2I9JxktQ.png" /><figcaption>Energy Conservation Law — Lecture Notes by A.O. Akyüz</figcaption></figure><p>This is the energy conservation law. It is important if we want actual physically based rendering. In the formula, f is again the BRDF, there is the cos term as always and we regard the entire hemisphere again. It is basically trying to say that the reflected energy from the object does not exceed the incoming energy. To achieve this, we add a normalization term and our formula becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ymuUr6oqcPHyqH6nufrDQ.png" /><figcaption>Modified Normalized Blinn-Phong — Lecture Notes by A.O. Akyüz</figcaption></figure><p>As you can see we also normalize the diffuse term. After doing this, the results change a lot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JM57ZF1YUYj0MrCZrLCf5w.png" /><figcaption>Modified Normalized Blinn-Phong</figcaption></figure><p>So we are done with Blinn-Phong, there is also a cool Killeroo scene utilizing the original Blinn-Phong:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wd2fMzVo8aVz0fQ3ItaI1A.png" /><figcaption>Killeroo Blinn-Phong — 9.23 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*F0MmU89EHvIcrRBL3UxFog.png" /><figcaption>Killeroo Blinn-Phong Close-up — 11.61 seconds</figcaption></figure><p>These look pretty good too if we look past the fact that there is no smooth shading.</p><h4>Phong</h4><p>This is appearently the predecessor to tbe Blinn-Phong reflection model. It was developed by Bui Tuong Phong in 1975. The Phong reflection model was improved by James Blinn in 1977 and we got the Blinn-Phong shading model.</p><p>I think the main difference between the two is that one uses the half-vector to get the specular term (Blinn-Phong) while the other uses the angle between the perfect reflection direction of the incoming light ray and the viewing direction (Phong). The rest of the calculations are similar to the Blinn-Phong model. So let’s have a look at the original Phong model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEjD-Ffj2GQ7AhO3juRPjw.png" /><figcaption>Original Phong — Lecture Notes by A.O. Akyüz</figcaption></figure><p>The output for this model looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6i_2HOE3ac2W_Zw4lB40NQ.png" /><figcaption>Original Phong</figcaption></figure><p>Again for the modified version to be normalized, the thing we do is the same, just eliminate the cos(theta_i) denominator so it can be normalized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EwL-U8BfoGm4VtiO4hZhQ.png" /><figcaption>Modified Phong — Lecture Notes by A.O. Akyüz</figcaption></figure><p>And the results of the modified Phong:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DhCQybTcUYUXQOc_n18LxQ.png" /><figcaption>Modified Phong</figcaption></figure><p>Now we can normalize it to make it energy conserving:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebUCkqlgunb81HlGfcgNJQ.png" /><figcaption>Modified Normalized Phong — Lecture Notes by A.O. Akyüz</figcaption></figure><p>Beware that the normalization factor for the specular term normalization factor is different from the Blinn-Phong one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Khdi03C8ueOhlW1dUrG9qQ.png" /><figcaption>Modified Normalized Phong</figcaption></figure><p>So we are done with the Phong model. We can get to the most interesting one.</p><h4>Torrance-Sparrow</h4><p>This model is more ‘physically based’ than the previous ones as it incorporates a micro-facet model. The model thinks of object surfaces as having little bumps like in real life, not perfect and rough. I found some lecture notes from CMU, they have great notes in pretty much every subject so check them out. Here is how the model is imagined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*8VOCW4VeUi02tIrLGqp-gQ.png" /><figcaption>Microfacet Model — CMU Lecture Notes</figcaption></figure><p>The whole formula looks something like this for the angle configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGkX248ms8ZqoAlqdZ9pOg.png" /><figcaption>Torrance-Sparrow Model — Lecture Notes by A.O. Akyüz</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjPa5_FcDCpOTjLDd176nA.png" /><figcaption>Torrance Sparrow Formula — Lecture Notes by A.O. Akyüz</figcaption></figure><p>As you can see the specular term looks quite scary. The functions inside are kind of complicated to explain, so we can check these notes out again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQ1Y0IQ4QorvHudE6VTSbA.png" /><figcaption>Torrance-Sparrow Terms — Lecture Notes by A.O. Akyüz</figcaption></figure><p>As you can see there is a difference. The Fresnel term from the CMU notes take theta_i as the angle input. It mentions wavelength dependency and I believe that is because we use the refraction index while approximating the Fresnel term. Regardless, I tried both and there was not much difference. Perhaps both could be used, but I am not sure. Looking further into this is required.</p><p>As you can see in the formula, we get a pretty good coverage of the behaviour of light after interacting with the surface. So how do we calculate these terms? Let’s start with the microfacet distribution function. Blinn’s distribution function is used and it is also normalized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*E5Ygx5y6Js2NJApkECMt0A.png" /><figcaption>Distribution Function — Lecture Notes by A.O. Akyüz</figcaption></figure><p>The normalization factor is found by integrating the projected solid angles inside very small parts of the area to actually get that part. I will not talk much about that here, as it would take too much time.</p><p>The geometry term helps us approximate a lot of things. Light can do some weird stuff in the microfacet model that will affect our result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYVa0i2xs008R9pRpnOnqA.png" /><figcaption>Microfacet Light Phenomena — CMU Lecture Notes</figcaption></figure><p>Shadowing is when the incoming light is blocked by another microfacet, preventing it from reaching some areas. Masking is when the outgoing ray is blocked by annother microfacet so it can’t leave the surface. Interreflection happens when light bounces between microfacets and we get the result of a point we otherwise would not see. So the geometry term helps with these, especially with shadowing and masking. The formula looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQyBV6zTOhdzh5gpQiEgCA.png" /><figcaption>Geometry Term — Lecture Notes by A.O. Akyüz</figcaption></figure><p>This incorporates microfacet orientations to the surface normal (n . h), the angle between the halfway vector and the outgoing ray direction (wo . wh) and the angles between the outgoing ray — normal, incoming ray — normal pairs both. So I believe the geometry term gives us an idea of how much light is lost because of these phenomena that happen in the microfacet model.</p><p>The Fresnel reflectance term depends on material properties. It is calculated using Schlick’s approximation in this case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*3cXpM1EWm1loPceWu6gWlw.png" /><figcaption>Fresnel Term — Lecture Notes by A.O. Akyüz</figcaption></figure><p>Where R0 is the reflectance of the surface for an incoming light ray that is parallel to the surface normal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*nujFjl-eeHUyRCrYHlcKUw.png" /><figcaption>R0 Calculation — Lecture Notes by A.O. Akyüz</figcaption></figure><p>The eta letter here represents the refractive index. After doing all this we should be pretty much done with the specular part. Another thing is that the Fresnel term can also be implemented into the normalized diffuse term. We can calculate it as:</p><blockquote>Fresnel k_d = (1-F) * k_d / <strong><em>π</em></strong></blockquote><p>So now we should see some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_c4PvzMDVMxz9uvQvb5G5Q.png" /><figcaption>Torrance Sparrow</figcaption></figure><p>My results for the Torrance-Sparrow model do not look exactly the same as the sample outputs. The highlights look smoother in the sphere scene, which was expected but not as much as this. We also have a Killeroo scene for this model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*uGUrUAkhcghM0BEybLwVdA.png" /><figcaption>Killeroo Torrance-Sparrow — 9.55 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MRGU1XsEPnagHrpXTmaXcw.png" /><figcaption>Killeroo Blinn-Phong Close-up — 11.8 seconds</figcaption></figure><p>As you can see, the results look darker than it was in Blinn-Phong shading which was expected. But there is that they are brighter than the sample outputs. I searched for an error for hours but could not find any, I believe I implemented the formulas correctly. Perhaps there could be problems about some edge conditions or floating point number problems. Or perhaps I am missing something. I am not exactly sure so I would appreciate any suggestions.</p><p>So being done with the BRDFs, we can move onto object lights!</p><h3>Object Lights</h3><p>Upto now, we have used different types of lights: point, area, directional, spot and environment. Most of these will not work with path tracing. While doing path tracing, we will follow the path the sent ray takes and it will need to hit a light object to recieve any light. We cannot do this with some other lights as rays can’t hit them. Here, we will use some different ways to sample from object lights.</p><h4>Mesh Lights</h4><p>To sample from mesh lights, we can use CDFs (cumulative distribution function) to do inversion sampling of mesh triangles according to their area and pick a triangle. Then we can pick a random point on that triangle. Let’s go step by step.</p><p>Before calculating a cumulative distribution function, we need to form a probability density function first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*T9oztxlqICxqwddhbq3Bmg.png" /><figcaption>PDF — Lecture Notes by A.O. Akyüz</figcaption></figure><p>In our case (and I think this could be good way to explain this concept), x0 and x1 are two triangles and a and b are their areas respectively. To get a CDF, I guess I could say distribute the probability values cumulatively according to triangle areas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*gyTHSEnGZ2PbLOeYY_7zJQ.png" /><figcaption>CDF — Lecture Notes by A.O. Akyüz</figcaption></figure><p>As you can see, x0’s area was a and x1’s was b. So x0’s value is a / (a + b). As we go cumulatively, x1’s value is (a + b) / (a + b) = 1. Now if we think of sending lines horizontally to these columns, which is the same as picking a random number between 0 and 1, it would hit x0 with a / (a + b) and x1 with b / (a + b) probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*5ENAUZtx9gmcwiqMA4c_fA.png" /><figcaption>Inverse CDF — Lecture Notes by A.O. Akyüz</figcaption></figure><p>So if we apply this to the triangles in a mesh and create a CDF, we just need to pick a random number in the range [0, 1) and find which triangle it hits in this CDF. So now we have our triangle, we can pick a random point in it using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qo6BejzcgMnK3WGvghVIAw.png" /><figcaption>Random Point in Triangle — Lecture Notes by A.O. Akyüz</figcaption></figure><p>Where r1 and r2 are again two random numbers in the range [0, 1). So we have our point and we can get some light. Here are some mesh light results, compared to the point light results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_MTb-LjvecZFKaTc6g5Mqw.png" /><figcaption>Cornellbox Jaroslav Diffuse — Point Light — Modified Phong — 100 Samples — 12.2 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RpqURxRck-CB7nAJsQoPZg.png" /><figcaption>Cornellbox Jaroslav Diffuse — Area Light — Modified Phong — 100 Samples — 9.5 seconds</figcaption></figure><p>I do not know why but there is 1 burnt out pixel in the point light scene. Here are some cool results with glossy spheres:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*UiuTLcNmUbCU2UQNhPA7fQ.png" /><figcaption>Cornellbox Jaroslav Glossy Area — Area Light — Modified Phong — 100 Samples — 9.48 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*1cGIHk8AawGRrO6nqvdmwA.png" /><figcaption>Cornellbox Jaroslav Glossy Area — Small Area Light — Modified Phong —100 Samples — 10.85 seconds</figcaption></figure><p>These results look cool, but again there is a burnt out pixel in the same place which is irritating.</p><p>So mesh lights look fine right now. Let’s move onto sphere lights!</p><h4>Sphere Lights</h4><p>While sampling sphere lights, the steps are different. We will basically sample a point from the sphere’s side that the point can see. The setup will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*1IiENTNdGc9spnqXEhATiw.png" /><figcaption>Sphere Light Sampling Setup— Lecture Notes by A.O. Akyüz</figcaption></figure><p>So theta_max is the maximum angle we can sample from. Then we would have:</p><blockquote>sin(theta_max) = r / d</blockquote><blockquote>cos(theta_max) = sqrt( 1 - ( sin ( theta_max ) ) ^ 2 )</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*_hOM2ICrDdgCuZMsaUqfFg.png" /><figcaption>Sphere Light Sampling ONB — Lecture Notes by A.O. Akyüz</figcaption></figure><p>Then we will create an orthonormal basis with w being the direction of the point to the sphere center. We can do this as before by making the smallest element of the w vector in an absolute sense equal to 1. Then take its cross product with w, and we would have the u vector. After taking u and w’s cross product, we would get the v vector and we have our final ONB.</p><p>Now what we want to do is offset the sample we would get with w with different weights of u, v and w combined. To do that, we need PDFs again. I will not go into a lot of depth here as it would take too much time. We do the sampling with spherical angles and in this case, the probability of getting a phi is 1 / (2 * PI) and theta is sin(theta) / (1-cos(theta_max)). Then we again do inversion sampling and get:</p><blockquote>theta = acos( 1-rand1+(rand1 * cos(theta_max)))</blockquote><blockquote>phi = 2 * PI * rand2</blockquote><p>Here rand1 and rand2 are random number from 0 to 1 again. These actually look similar to basic uniform upper hemisphere sampling as they are kind of similar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*dVISDJNnbvWx9x5Q5yz21w.png" /><figcaption>Uniform Upper Hemisphere Sampling — Lecture Notes by A.O. Akyüz</figcaption></figure><p>But anyways let’s not drift. After finding phi and theta, we can finally calculate our sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*4-y_afnX1yZ0QAOLD7NzlQ.png" /><figcaption>ONB Sample Calculation — Lecture Notes by A.O. Akyüz</figcaption></figure><p><strong>Beware: v here is the vector aligned with the normal. In our case, w and v switch places.</strong></p><p>After that, we should be done with basic sphere sampling. Here is a result with a sphere light and spheres with glossy surfaces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*yaSm2Ta06HYB5uSw8Wtp0g.png" /><figcaption>Cornellbox Jaroslav Glossy Area — Sphere Area Light — Modified Phong — 100 Samples — 9.93 seconds</figcaption></figure><p>Also here, we can transform the sphere and get cool results. I did this by first inverse transforming the intersected point and using the untransformed sphere center for the sample calculation, then transformed the sample back and it worked:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*kpwnr9VWfgiBEnMGREOtHA.png" /><figcaption>Cornellbox Jaroslav Glossy Area — Ellipsoid Area Light — Modified Phong — 100 Samples — 9.97 seconds</figcaption></figure><p>So object lights worked at this point and it was time to get to the most exciting part.</p><h3>Path Tracing</h3><p>Up until this point, we only focused on direct illumination. But we have seen the rendering equation time and time again, and it would include all light coming from all directions, not just one direction from the light to the point. We all know that light doesn’t only reach a point directly from the source, but also bounces from other objects and ends up in that point indirectly.</p><p>To achieve this, our BRDFs must have been normalized as energy conservation is crucial. Otherwise light would bounce off from a point and the energy would not simulate the actual laws of physics properly. We also needed object lights for the paths we follow to hit. So at this point, all the requirements for path tracing are done.</p><p>To understand the path tracing process we will do, we also need to understand Monte Carlo integration.</p><h4>Monte Carlo Integration</h4><p>So the thing is that we can’t actually take all light rays hitting a point into consideration, it is impossible. We somehow need to approximate this hemisphere integral we always see in the rendering equation. Monte Carlo methods help us do that, and it is simple to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*ri7PuhjYe9Y65yc4nuPkxA.png" /><figcaption>Monte Carlo Integration — Lecture Notes by A.O. Akyüz</figcaption></figure><p>The idea is, we can estimate an integral by incorporating the probability of getting a sample. Let’s take N number of samples and evaluate them. If we divide the evaluated value by the probability of getting that value and get the average of all these samples, we get a pretty good estimate of the overall integral. This is kind of like integration anyways, the important thing is that at the end, we take samples with lower probability of sampling more into account and even the low probability out. This is extremely cool and having covered this, let’s get to the most basic case.</p><h4>Uniform Sampling</h4><p>Uniform sampling the upper hemisphere is quite easy and tons of sources could be found that would explain this better than me. We calculate an orthonormal basis around a point’s normal again. This is pretty basic, the orthonormal basis formula is the same, and I have briefly mentioned uniform sampling before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*dVISDJNnbvWx9x5Q5yz21w.png" /><figcaption>Uniform Sampling — Lecture Notes by A.O. Akyüz</figcaption></figure><p>If we put these in their places in the orthonormal basis formula, we can get the light direction vector easily:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*4-y_afnX1yZ0QAOLD7NzlQ.png" /><figcaption>ONB Sample Calculation — Lecture Notes by A.O. Akyüz</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*8eCvLEMi6R332Y6P5wgGlg.png" /><figcaption>Uniform Sample Calculation — Lecture Notes by A.O. Akyüz</figcaption></figure><p>So we can get the direction vector, and need to recursively path trace through that until we hit a light source. The important thing is that we have to divide the result we get by the probability of sampling this direction, which is 1 / 2PI for uniform sampling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*wqMLXnUssugGWfOdCx5mxQ.png" /><figcaption>Path Diffuse Uniform — 400 Samples — 75.28 seconds</figcaption></figure><p>So we have our first path traced image. As you can see the cornellbox seems well lit and we can see red and green walls contribude to the color of the floor and much more.</p><h4>Cosine Importance Sampling</h4><p>Cosine importance sampling is particularly cool as we will not sample uniformly, but try to sample from the more important directions more. In most cases, the light that contributes most to a surface’s illumination comes from a direction close to the surface normal. Again I will not derive this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*nOJGPCd14uxe-AqPd7fycg.png" /><figcaption>Cosine Importance Sampling — Lecture Notes by A.O. Akyüz</figcaption></figure><p>Again, we put them in the appropriate place in the ONB direction function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*6RMC9Wdp8JQsPW5gjRXvnQ.png" /><figcaption>Cosine Importance Sample Calculation — Lecture Notes by A.O. Akyüz</figcaption></figure><p>So we have a direction and can calculate the incoming light from that direction, but what is our probability of sampling that? In this case:</p><blockquote>Probability = cos(theta) / PI</blockquote><p>So we should divide the incoming value by this. As you can see, smaller the theta, higher the probability in this case which is what we wanted as theta is the angle between the surface normal and the light direction. Our results improve with importance sampling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*kgCl9Ju0ULL0Z1B4eOGTZw.png" /><figcaption>Path Diffuse Importance — 400 Samples — 70.5 seconds</figcaption></figure><p>Let’s take a look at them side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*wqMLXnUssugGWfOdCx5mxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*kgCl9Ju0ULL0Z1B4eOGTZw.png" /><figcaption>-Left- Path Diffuse Uniform — 400 Samples — 75.28 seconds , -Right-Path Diffuse Importance — 400 Samples — 70.5 seconds</figcaption></figure><p>So our image looks better with no extra duration. But there are other ways we can make this happen too.</p><h4>Splitting</h4><p>The idea of splitting is pretty straightforward. As you can see, the path traced images have a lot of noise. This is called Monte Carlo noise. The most brute force way that helps decrease this noise, not that efficiently, is increasing the number of samples. We can do this by increasing the number of main samples that we also use for anti aliasing, but that would not be that effective as in most cases, we do not need thousands of samples for anti aliasing.</p><p>In this case we can apply splitting. Let’s think of a sitation where the recursion depth is 2 and we send 1600 samples per pixel. For each pixel, we will process 1600 rays initially, 1600 for the first bound and 1600 again for the second, summing up to a total of 4800 rays. But if we have 400 samples per pixel and pick 5 samples at first bounce (splitting factor = 5), we will process 2000 rays for the first bounce and another 2000 for the second. We do not split after the first bounce. This sums up to a total of 4400 rays processed. This is lower than the first case and we process more illumination for a point which is great. So in theory it should work really well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2HFbIqMRV1QeEXXTGj3Bkw.png" /><figcaption>Diffuse Splitting — 400 Samples — Splitting Factor = 5–114.2 seconds</figcaption></figure><p>Here is a comparison with the exact same numbers I mentioned above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ZNkDOwEqUzghrziUqbEksA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*2HFbIqMRV1QeEXXTGj3Bkw.png" /><figcaption>Left-No splitting-210 seconds , Right-Splitting-114.2 seconds</figcaption></figure><p>I think there could be an issue here with splitting. Sure the noise decreased and the time it takes to render decreased a lot also because I did not have to create all those initial rays at the beginning and also at the end while anti-aliasing and also the total ray calculations I had to do in the main recursive algorithm was around 10% less. But if you look more carefully the shading looks almost like regular ray tracing with object lights. I do not know why this happens, maybe it is supposed to but I don’t think so. I realized this too late and looked into it a little but couldn’t find the issue. I guessed maybe it does something that I am only supposed to do with NEE but it does not. Any suggestions would be welcome. But I guess it works in reducing the Monte Carlo noise in less time. So let’s move onto the next part.</p><h4>Russian Roulette</h4><p>So right now, we send paths and try to make the path hit a light object to shade our point. If the path does not hit any light source, we just do not shade it but also go until we hit the maximum recursion depth. This could be unnecessary as we already use an energy conserving BRDF and if we already hit high recursion depths, the energy will be mostly lost so there is little use in going after it further.</p><p>To make our path tracing slightly more efficient we can use the Russian roulette tactic. We can start with a throughput value of 1.0 and at each bounce, subtract the BRDF magnitude from this. The main idea is at each bounce, we can generate a random value between 0 and 1 and if it is larger than the current throughput value, we stop the algorithm. So if the energy is already so low, we have a high probability of destroying the path. Another thing we add here is a minimum recursion depth element. If we coincidentally happened to stop the algortihm prematurely, it would look really bad. To stop that from happening, we do not do the check to stop the algorithm until we bounce the same number of times as the minimum recursion depth. Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Tyy_2hF2-ZO_-XOToHfa6w.png" /><figcaption>Diffuse Russian Roulette — 400 Samples — 44 seconds</figcaption></figure><p>Let’s compare with and without:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*fh6ZiQiH-GFV7s18gQnrnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Tyy_2hF2-ZO_-XOToHfa6w.png" /><figcaption>-Left- Diffuse Importance No Russian Roulette-400 Samples-67.9 seconds , -Right- Diffuse Importance Russian Roulette-400 Samples-44 seconds</figcaption></figure><p>As you can see we have more noise, but it takes much less time to render the scene.</p><h4>Next Event Estimation</h4><p>Next event estimation is probably the most exciting out of the previous ways and provides better results. So the issue still is that we might not properly sample the light realistically. So we just sample the object light explicitly in combination of the path. If the path does not hit a light at all, we can just use the value we get from this direct light sample. If the path hits the light at some point later, we can just add them up as the path will give us some of the indirect light we would otherwise miss. If they both hit at the same time, we can just get their average.</p><p>Again for this direct sample ray, we need to divide the value we get by the probability of getting that sample. For meshes, that would be:</p><blockquote>p(w) = r^2 / (A * cos(theta))</blockquote><p>For spheres that would be:</p><blockquote>p(w) = 1 / (2 * PI * (1 — cos(theta_max)))</blockquote><p>But these did not work exactly like as I expected, my results got better yet the noise was still a lot. Perhaps I have done something wrong in the sampling part. I needed to change these probabilities a little by not using 1 term per each and also multiplying by a constant for the sphere case. The results should be close to the actual probability but I am basically using slightly mutant versions of the physically correct formulas. But the results look good and there was a huge improvement. Let’s take a look at some of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*5fSR0n0MIpIbsy_cxJfuhw.png" /><figcaption>Diffuse Importance NEE Prism Light — 100 samples — 68.9 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ugGMDXHR2BZaZtQMRzc22g.png" /><figcaption>Diffuse Uniform NEE Prism Light — 100 samples — 69.2 seconds</figcaption></figure><p>Let’s compare both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_x6RWfMqPULCllTKpoliyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*5fSR0n0MIpIbsy_cxJfuhw.png" /><figcaption>-Left -Diffuse Importance Prism Light — 100 Samples — 14.21 seconds, -Right-Diffuse Importance NEE Prism Light — 100 samples — 68.9 seconds</figcaption></figure><p>As you can see NEE makes a huge difference. Let’s take a look at a scene with sphere lights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_dlY_HcURrfdNUATN3EHcg.png" /><figcaption>Diffuse Importance NEE Sphere Light — 100 Samples — 62.81 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*4R03TANstcT1kgKE9vitiQ.png" /><figcaption>Diffuse Uniform NEE Sphere Light — 100 Samples — 66.2 seconds</figcaption></figure><p>Now let’s compare with and without NEE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*a49cytscQlPcs7v5wbOhTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_dlY_HcURrfdNUATN3EHcg.png" /><figcaption>-Left- Diffuse Importance Sphere Light — 100 Samples — 14.73 seconds, -Right- Diffuse Importance NEE Sphere Light — 100 Samples —62.81 seconds</figcaption></figure><p>Again it makes adifference in this scene. Let’s look at a scene with a flat light now. I want to mention that the light was slightly offset from the ceiling so I pushed it back to the same z coordinate. Before doing that it illuminated the ceiling more than it does in the sample outputs. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*hBx7nbHjRZM-cK2jbMLWig.png" /><figcaption>Diffuse Importance NEE Flat Light — 100 samples — 71.91 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*fYxbD1JQauwAX77dt3aWGQ.png" /><figcaption>Diffuse Uniform NEE Flat Light — 100 samples — 74.39 seconds</figcaption></figure><p>As you can see in this case there appears to be more fireflies than the prism scene which was unexpected. Here is the comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ybG_fYJZc0xG72d1lwHJ7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*hBx7nbHjRZM-cK2jbMLWig.png" /><figcaption>-Left- Diffuse Importance Flat Light — 100 samples — 14.58 seconds , -Right- Diffuse Importance NEE Flat Light — 100 samples — 71.91 seconds</figcaption></figure><p>We can also see a huge difference in this scene. Another thing is that path tracing usually handles refractions as is but with NEE, we need to handle stuff differently. At the end they should converge to the same result, so here are 2 scenes, one with NEE and one without:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ks3cWFad7R6lBtvpxH-8HQ.png" /><figcaption>Glass Sphere — 400 Samples — 176.5 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*eU9_utKxCLbYhK8hvZ6Ytw.png" /><figcaption>NEE Glass Sphere — 400 Samples — 679.6 seconds</figcaption></figure><p>As you can see the NEE refractions look fine. I also wanted to render a scene with high sample count to see how it would look. I did not go extreme here just NEE and 2500 samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*PwUxNq2Wmm6ffyMPSdHKrA.png" /><figcaption>Diffuse Importance NEE Prism Light — 2500 samples — 30 minutes</figcaption></figure><p>Noise caused by NEE which are also called fire flies are quite hard to get rid of completely. So as you can see although I increased the sample count a lot, there is still a considerable amount of noise.</p><p>Here is another scene with NEE and Russian roulette:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Mk1JkGxW-ll9F3apC1PZYQ.png" /><figcaption>Diffuse Importance NEE Russian Roulette — 100 Samples — 38.6 seconds</figcaption></figure><p>And here is another which incorporates all techniques we have covered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*zehMD_ilN58XIcBR7p8fPw.png" /><figcaption>Diffuse Importance NEE Russian Roulette — 25 Samples — Splitting Factor = 5 — 30.5 seconds</figcaption></figure><p>I think this looks weird because of the splitting factor. But I wanted to render and display all.</p><h3>Other Scenes</h3><p>So we have covered each BRDF, object light and cornellbox path tracing scene. There are also the Sponza and Veach Ajar scenes. One of those require us to parse .bin files and the other uses area light in path tracing. Both of which I do not have the time to implement at this point. I have spent a lot of time on the implementation and also the blog post of this part and I have to work on the next part. Perhaps I might post a 6.2 like I did with texture mapping.</p><h3>Conclusion</h3><p>I guess this part could be considered a success regarding how busy I was during the past couple of weeks. There are a couple of smaller issues: the Torrance-Sparrow Model being lighter, splitting producing a more pastel colors and lastly, weird NEE PDF behaviour even if I get okay looking results. I plan on getting into it again later and clear everything up. This part was extremely enjoyable and I have learnt a lot.</p><p>This is also the last part which is a main part of CENG795: Advanced Ray Tracing. This was a great learning experience and the lectures were a lot of fun. So I want to thank AO Akyuz and also the classmates for their contributions to the course. In this next part, I will try to implement volume rendering, but given the time frame I do not expect to achieve good results as I devoted most of my time to path tracing. But anyways, see you in the next part!</p><h3>References</h3><p>Akyüz, A.O. <em>Lecture Slides from CENG795 Advanced Ray Tracing</em>. Middle East Technical University</p><p>Carnegie Mellon University. n.d. <em>Computer graphics: Texture mapping [Lecture slides]</em>. Retrieved from <a href="https://www.cs.cmu.edu/afs/cs/academic/class/16823-s16/www/pdfs/appearance-modeling-4.pdf">https://www.cs.cmu.edu/afs/cs/academic/class/16823-s16/www/pdfs/appearance-modeling-4.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7978842081f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Ray Tracer: Part 5]]></title>
            <link>https://medium.com/@Ksatese/advanced-ray-tracer-part-5-0b4e6d14ea8c?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b4e6d14ea8c</guid>
            <category><![CDATA[hdr]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[tone-mapping]]></category>
            <category><![CDATA[high-dynamic-range]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 01:35:22 GMT</pubDate>
            <atom:updated>2024-12-28T02:17:25.646Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part, I implemented some new type of lights and HDR tonemapping. I think this part really stepped up what the ray tracer can do and the outputs look really cool.</p><p>First, we will dive into HDR tone mapping to not stop the flow of the post as some lights require this feature. Then we will go through directional, spot and environment lights in this order.</p><p>All images seen in the post are rendered by my raytracer. The tests are conducted using the Apple MacBook M3 Pro chip with 5 performance cores with 4.06 GHz and 6 efficiency cores with 2.8 GHz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*S40FrACH2V5sP72IUUfFYA.png" /><figcaption>Glass Sphere Environment Light</figcaption></figure><h3>HDR Tonemapping</h3><p>Up until this point in our color calculations, we clamped the end result to fit the [0, 255] RGB color limits. This is obviously not a good thing to do as it means that we give a lot of color complexity away, especially in the brightest and darkest parts. You can think of this such that up until now, in every scene we rendered, we did not get light visuals as bright as in real life and proper contrast between colors. What we can do is handle this clamping operation better so it follows the real color calculations more realistically.</p><p>HDR is the acronym for ‘High Dynamic Range’. For our outputs, it is basically the proper unclamped version of our computations. The [0, 255] range is called LDR: ‘Low Dynamic Range’. We can actually create images that utilize HDR and also read stuff like textures from them. We used .exr files for the rendering of .exr scenes. But we would also want to create LDR images in the format of .png as it is more lightweight, easier to use and extremely wide spread.</p><p>The process of conversion from HDR to LDR is like draining the liquid of a stew we have cooked for hours, so we can carry it places and eat it easier. But in the process we lose all of that good herbs, spices and fat that would give our stew that extra flavor. Up until this point we just drained all the liquid and ended up with just dry meat, but now we will try to keep that extra spice and juiciness that was already created, but ignored.</p><p>Before going forward I want to mention that I used the tinyexr library to handle the read and write operations of .exr files. It is pretty easy to use and lightweight, I recommend it to anyone who wants do something similar.</p><h4>Background</h4><p>There are different approaches to tone mapping. The basic classification is global and local tone mapping operators. With global tone mapping operators, we apply the same transformation to every single pixel based on its luminance and global data like the average luminance. This is simpler to do, faster and supposed to be pretty consistent. But as we approach it globally, we might miss local contrasts and miss some detail in the extreme values. Local tone mapping operators on the other hand apply different transformations to different regions based on local data. This approach might seem better overall but there can be some problems:</p><blockquote>Those algorithms are more complicated than the global ones; they can show artifacts (e.g. halo effect and ringing); and the output can look unrealistic, but they can (if used correctly) provide the best performance, since human vision is mainly sensitive to local contrast. — (Wikipedia, n.d.)</blockquote><p>In this part, we will use the photographic tone mapping algorithm intruduced by Reinhard et. al. in 2002 with the paper Photographic Tone Reproduction for Digital Images which is a global tone mapping algorithm. This method is inspired by Ansel Adams’s Zone System:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Nil7hFSaOnE7Tg2VzSMGsg.png" /><figcaption>Scene Zones — (Reinhard, Stark, Shirley, &amp; Ferwerda, 2002)</figcaption></figure><blockquote>The mapping from scene zones to print zones. Scene zones at either extreme will map to pure black (zone 0) or white (zone X) if the dynamic range of the scene is eleven zones or more. — Reinhard, Stark, Shirley, &amp; Ferwerda, 2002</blockquote><p>I believe there are some related terms we should get out of the way before I start explaining the whole process:</p><blockquote><strong>Middle gray: </strong>subjective middle brightness of the scene. Typically mapped to Zone V.</blockquote><blockquote><strong>Dynamic range: </strong>difference between the highest and lowest zones to which a scene will be mapped</blockquote><blockquote><strong>Key: </strong>the overall subjective brightness of the scene</blockquote><blockquote><strong>Dodging-and burning: </strong>locally inhibiting or administering light to a certain region of the print</blockquote><blockquote>—( Course Notes by AO Akyüz)</blockquote><p>So having these in mind, let’s look at the actual steps to tone map a scene.</p><h4>Photographic Tone Mapping</h4><p>In the <strong>1st</strong> step, we will get an initial luminance value by multiplying the color value’s RGB components with some constants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irOpg_2CQo-LcAC17KIGTA.png" /><figcaption>Luminance Calculation — Course Notes by AO Akyüz</figcaption></figure><p>The coefficients are decided based on the human visual system. This topic is closely related to how we actually percieve light. So these coefficients are decided based on the receptor sensitivity to light in our eyes.</p><p>Now for the <strong>2nd </strong>step, we need to calculate the log-average luminance to scale our initially calculate luminance into a zone. This is the middle-gray mentioned just a little while ago, and it is estimated as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*1In1gxgU6_-1CMAsTi0MZg.png" /><figcaption>Log-average Luminance Estimation — Course Notes by AO Akyüz</figcaption></figure><p>According to the book Fundamentals of Computer Graphics 5th Edition, in the Tone Reproduction part actually written by Erik Reinhard, there is a simple note about why we add an epsilon(written as delta in the formula but acts as a very small constant like we usually represent with epsilon) value:</p><blockquote>… a small constant δ is introduced to prevent the average to become zero in the presence of black pixels. — (Marschner &amp; Shirley, 2022, p. 580)</blockquote><p>So this value matters in the calculation of the average estimation when our scene has a lot of black pixels.</p><p>In the <strong>3rd</strong> step, we will also be given a key value for each scene to determine how aggresively this compression is done and divide this by the average approximation. The aggressiveness refers to how strongly the tone mapping operator reduces high luminance values. A higher key value would do a less aggressive change, so the higher luminance values would remain and the image would be britghter. If it is lower, it would be more aggressively compressed and it would be darker. So here the key value determines how bright the scene is and we generally want to map the middle grey to %18 reflectance so we set the key to be 0.18. This value comes from the Zone System as Zone V has approximately 18% reflectance also, which is the middle ground. This would give us the most optimal results in terms of realism in general. Lastly, we can multiply with the luminance value to get the new ‘scaled’ luminance, and we are done with this part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*ddX-I-TUwhqkQy4lyu3CCw.png" /><figcaption>Key Mapping — Course Notes by AO Akyüz</figcaption></figure><p>After calculating this, in the <strong>4th</strong> step, we can apply the main tone mapping operator(TMO):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*KHOovx0ZJzh7XMqX2CuuCQ.png" /><figcaption>Reinhard TMO — (Reinhard, Stark, Shirley, &amp; Ferwerda, 2002)</figcaption></figure><p>This part is extremely simple, but it is where we actually compress high luminances. This is called sigmodial compression. This piece of basic math is very useful, and also explained in the paper:</p><blockquote>Note that high luminances are scaled by approximately 1/L, while low luminances are scaled by 1. The denominator causes a graceful blend between these two scalings. This formulation is guaranteed to bring all luminances within displayable range. However, as mentioned in the previous section, this is not always desirable. — (Reinhard, Stark, Shirley, &amp; Ferwerda, 2002)</blockquote><p>Here the result is guaranteed to be in the [0,1] range and we can easily gamma correct and scale to our usual display range easily.</p><p>The ‘not always desirable’ case is when we want to directly burn out high luminance pixels for artistic purposes and visual aesthetic. In that case we will be given a percentage on how much from the top we will luminate the maximum amount when we sort all the luminance values. With this, our TMO formula also changes a bit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*ciUFeY_ju8Ahmg8Fd-Fo1Q.png" /><figcaption>Reinhard TMO Burnout — (Reinhard, Stark, Shirley, &amp; Ferwerda, 2002)</figcaption></figure><p>As we are finished with the TMO, we can move onto the <strong>4th</strong> step which will be calculating the new RGB values using a saturation parameter. This is the saturation you can see in games or if you have done anything about photography, video or image editing etc. you might be familiar with it. The <em>s</em> is the saturation parameter. If it is lower, we will get a duller result that will look more greyish. If it is higher, we will get an image with more vivid colors, but they might look unrealistic. So the key is to determine <em>s</em> by keeping the artistic choice and or realism in mind.</p><p>We can achieve this effect by dividing the inital RGB values by the luminance values we found in the first step and take its power to <em>s</em>. Then we can multiply this with the result of the tonemapping function. I am not extremely clear on why we use this exact way to do this but it makes sense:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEQtlRZt5JDXxdX_KG1seg.png" /><figcaption>Saturation — Course Notes by AO Akyüz</figcaption></figure><p>After this, we can move onto the <strong>5th</strong> and the final step where we will do gamma correction. After the saturation step, we will have a linear color-space. We will encounter a problem about this with the state of modern monitors. I found this hard to explain myself, but I found out that learnopengl.com did it pretty nicely:</p><blockquote>From learnopengl.com:</blockquote><blockquote>Because the human eyes prefer to see brightness colors according to the top scale, monitors (still today) use a power relationship for displaying output colors so that the original physical brightness colors are mapped to the non-linear brightness colors in the top scale.</blockquote><blockquote>This non-linear mapping of monitors does output more pleasing brightness results for our eyes, but when it comes to rendering graphics there is one issue: all the color and brightness options we configure in our applications are based on what we perceive from the monitor and thus all the options are actually non-linear brightness/color options. Take a look at the graph below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*NNcxs9pKB8YTG61D7hGD2g.png" /><figcaption>Gamma Curves — (learnopengl.com, n.d.)</figcaption></figure><p>Here the 2.2 gamma curve aligns closely with humen eye sensitivity. But we want to somewhat preserve our generated color values to best of our ability. Applying gamma correction hereensures that the image’s actual color and the display’s response results in an image that we as humans can see the colors of better.</p><p>You can just think of it such that we have color values on the line at the middle, but our monitor will display it by transforming it by taking its power by some value <em>g</em>. We will try to even that out by taking the power of the color values by <em>1/g </em>beforehand so the color values we end up with in the display fall closer to the line, preserving the actual values. Another good explanation for this I found was in a photography webpage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*ouCKqKc4QQ0UGnYltpAg1Q.png" /><figcaption>Gamma Correction — (Cambridge in Colour, n.d.)</figcaption></figure><p>The difference of applying gamma correction vs. not doing so is extremely appearent in rendered scenes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3UYepB-4i2mLRMOe3wX2w.jpeg" /><figcaption>Without vs With Gamma Correction — (Rosen, 2010)</figcaption></figure><p>As you can see the gamma corrected scene on the right looks way more realistic than the not applied case on the left.</p><p>So after applying gamma correction, we can display the scenes in .png format by rounding to the nearest integer. Here are some basic results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*M02HhbqSRaL89AtokHjUAw.png" /><figcaption>Cube Point Light — 0.184074 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9nsYu11o8QVHGgwuperHZw.png" /><figcaption>Cube Point Light HDR Tonemapping — Key = 0.18–0.225341 seconds</figcaption></figure><p>As you can see the image with HDR tonemapping looks properly luminated and we can clearly see darker and brighter sides and differentiate between them. I also wanted show how the image changes with different key and saturation values.</p><p>Changing the key value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*W3aiVRW9AwXhQ7K5ZIPpVg.png" /><figcaption>Cube Point Light HDR Tonemapping — Key = 0.01, Saturation = 1.0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9nsYu11o8QVHGgwuperHZw.png" /><figcaption>Cube Point Light HDR Tonemapping — Key = 0.18, Saturation = 1.0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*d10dCuMIN41zbpuabdC2vw.png" /><figcaption>Cube Point Light HDR Tonemapping — Key = 0.72, Saturation = 1.0</figcaption></figure><p>As you can see, as we increase the key value, the image gets brighter which is expected and is the point of this parameter.</p><p>Changing the saturation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZjDaY1nXyE4LaDkjqnHxMA.png" /><figcaption>Cube Point Light HDR Tonemapping — Saturation = 0.5, Key = 0.18</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9nsYu11o8QVHGgwuperHZw.png" /><figcaption>Cube Point Light HDR Tonemapping — Saturation = 1.0, Key = 0.18</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*M-R0tdzvKu0EG6M2OV7owQ.png" /><figcaption>Cube Point Light HDR Tonemapping — Saturation = 3.0, Key = 0.18</figcaption></figure><p>All of these outputs are expected and although 0.18 should be the best for realism in most cases, it is an artistic choice.</p><p>We can also read .exr files and use them as textures for our objects and get outputs as we can now apply tone mapping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xMB0DcYEBfpte64OZRE9ng.png" /><figcaption>Sphere Point HDR Texture — 0.29178 seconds</figcaption></figure><p>Beware that each image in the environment lighting part were rendered in .exr format and also tonemapped to fit the .png format. I can not upload .exr files to the blog so each scene you will see from now excluding the directional and spot lights are the tonemapped versions as we read .exr files which are high dynamic range.</p><p>Having this done, let’s move onto lighting!</p><h3>Directional Light</h3><p>This was probably the easiest thing to implement in this homework. With directional lights, we assume that our point light is moved to infinity at a direction with a radiance value that does not decrease as objects are further away. So it lights every point the same amount, and it always comes from a specific direction universally for the scene.</p><p>So what we can just use the inverse of this direction vector to check if a point is in shadow, and otherwise give it the default radiance value of the light. It is dead simple. Here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-VVmAzvNPvQwejV3X8hxgA.png" /><figcaption>Cube Directional Light — 0.178197 seconds</figcaption></figure><h3>Spot Light</h3><p>Spot lights are much more interesting. In this case, we are given all components of a point light plus a coverage and a fall-off angle. The coverage angle is the angle the light luminates with most angular difference from its direction. The fall-off angle is the angle difference from the light direction which we will start to attenuate the intensity based on the angle difference. Here is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*vm4tv7Xb-cwpO4iG54p6Qg.png" /><figcaption>Spot Light — Course Notes by AO Akyüz</figcaption></figure><p>So the angle difference lower than the fall-off angle will be lighted with the given intensity. Between the fall-off angle and the coverage angle, we will lower the intensity as we go further away from the light direction so the outer parts of the spotlight will be smooth. We need to multiply the value by a factor we can calculate like this to attenuate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*LFIbaWnPvucyFwblEnZk_w.png" /><figcaption>Spot Light Attenuation — Course Notes by AO Akyüz</figcaption></figure><p>Here, alpha is the angle between the light direction and the point we are doing this calculation for shading. Lastly, outside of the coverage angle, the light will not affect any point.</p><p>Here are some cool results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jB97KnmxiUtsWMokjKkiqA.png" /><figcaption>Dragon Spot Light — 100 samples— 24.2889 seconds</figcaption></figure><p>We can also give these lights color by using different intensity values and create some cool scenes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-hgrIHG7MDiUZOCHl7QYg.png" /><figcaption>Dragon New with Spot Lights — 4.04563 seconds</figcaption></figure><h3>Environment Light</h3><p>Environment lights are also called spherical directional lights. They are basically similar to directional lights but the difference is that for every single direction we want to sample light from, there is a different value. We achieve this by thinking that the whole scene is in a sphere with an infinite radius that will act as our directional light for each small point.</p><p>I think environment lights were the trickiest to implement in this part. We use .exr files to store environment maps and should sample from them properly with u, v values like we did in texture mapping. There are 2 different types of environment map formats we used: equirectangular (lat-long) and spherical(probe).</p><p>I want to clarify how we see the actual image in the background of our scenes first. As these images surround the whole scene, if our rays do not hit any objects, we can directly give the radiance value we get by sampling the environment using the ray direction. So we see the environment map even when there is no object in the scene.</p><h4>Equirectangular</h4><p>Obviously the first thing we should do is find the u and v values. With equirectangular maps, we have the image domain of u = [0,2] and v = [0,1]. We will try to get a sample from the image with these.</p><p>At this point, we use the direction vector we have in these formulas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*1DhhvpNC_ovp_TbDCyFS3A.png" /><figcaption>Equirectangular Map Texture Coordinates — Course Notes by AO Akyüz</figcaption></figure><p>x, y and z represent the components of the direction vector. After getting these u and v values, we need to convert them to image pixel values. As I said before, we get the u value to be in the range [0,2]. While getting actual sampling pixel coordinate, we need to also divide the u value by 2, then multiply u by the image width and v by the image height. After doing all this and sampling like we did in texture mapping, we get some cool results. Here is a scene with no object so there is no intersection and we just give the environment map samples as output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*jom0byW_sPFxXfbJTijIjA.png" /><figcaption>Empty Environment Light Latitude-Longitude — 0.052338 seconds</figcaption></figure><p>To get a better idea of equirectangular maps and some examples, you can check out USC’s vision and graphics lab page: <a href="https://vgl.ict.usc.edu/Data/HighResProbes/">https://vgl.ict.usc.edu/Data/HighResProbes/</a></p><h4>Spherical</h4><p>The spherical format is also very simple to implement. In this case, we will actually do the mapping like we are stepping inside a sphere. The operation is extremely easy. We need to beware that we get u and v values both in the range [-1,1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*aEH5mPvRPQ0DK8zJ38RS8A.png" /><figcaption>Spherical Environment Map — Course Notes by AO Akyüz</figcaption></figure><p>So we calculate r and multiply with the x and y components of the direction vector(negate for v as we go down). Then we map it in the range [0,1] by adding 1 and dividing by 2. Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*aRxhuhV7Riqy-_iiEX0AGg.png" /><figcaption>Empty Environment Light Probe — 0.04819 seconds</figcaption></figure><p>You can check out Paul Debevec’s page about this to get a better idea: <a href="https://www.pauldebevec.com/Probes/">https://www.pauldebevec.com/Probes/</a></p><h4>Lighting Objects</h4><p>So we know how to get samples when there is no intersection, but have not talked about shading actual objects yet. The thing to consider here is to decide which direction to sample from to shade a point. We did not calculate this ourselves before, we just knew where the lights were and calculated the direction between the point and the lights. Here we can not do that as there is light in every direction, but we can sample a direction randomly in a way that will give us proper results.</p><h4>Random Rejection Sampling</h4><p>The main idea of random rejection sampling is extremely simple. We have a condition in which we accept the sample, and until this condition is satisfied, we generate random samples and do the condition check. In our case for shading, we want our sample to be in the upper hemisphere of the surface where the point we are shading resides in.</p><p>We can just create samples by generating 3 values for x, y and z in the range [-1, 1]. To check if the sample is in the upper hemisphere, we can just get the dot product of the randomly generated sample and the surface normal. We can then normalize and use this vector to sample from the environment map. Finally, we must not forget to multiply the radiance we find by 2PI. The thing is that we just sampled from the 1 out of 2PI possible divided parts of the hemisphere, so we need to even things out. We will divide the radiance we get by the probability of sampling this specific vector, which is equal to multiplying it with 2PI. I forgot to do this for a while and it caused the objects to look darker. Need to keep this in mind as it is an important step.</p><p>Here, the samples will still be random and it will be noisy with low sample counts. If we increase the image pixel sample count, the whole shading will even out nicely and we will get the whole environment lighting really well. You can see this especially in the Audi TT results. Here are the outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*S40FrACH2V5sP72IUUfFYA.png" /><figcaption>Glass Sphere Environment Light — 0.285928 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rlub4BOFG9hJZKg2V9Obrw.png" /><figcaption>Mirror Sphere Environment Light — 0.190534 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*hwv2l-nxXnx9OndJmXqBjA.png" /><figcaption>Sphere Environment Light — 900 samples — 65.3405 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ax5DlZSM0LOkV90RlSW60Q.png" /><figcaption>Audi TT Glacier Environment Lİght — 16 samples — 27.039 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlKG8-xyjMZHJtNV4s_wrw.png" /><figcaption>Audi TT Pisa Environment Lİght — 16 samples — 26.6108 seconds</figcaption></figure><p>As you can see there is too much noise in the Audi TT images. I decided to increase the sample count to get sharper ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1zY1YXXbz081LQENzvxmHw.png" /><figcaption>Audi TT Glacier Environment Lİght — 400 samples — 678.536 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9VsaCpucOyZAtbN6A860Q.png" /><figcaption>Audi TT Pisa Environment Lİght — 400 samples — 675.624 seconds</figcaption></figure><p>These are still noisier that the ground truth images but still look pretty good.</p><p>I also decided to visit the webpages I previously talked about for equilateral maps and found some new maps. Here are cool results with another one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*t-x0uvtKfOY0z3Oz_842Kw.png" /><figcaption>Glass Sphere Environment Light — Different Map — 0.51765 seconds</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tntZPoV2W3B2_iV2CpYWyQ.png" /><figcaption>Mirror Sphere Environment Light — Different Map — 0.414982 seconds</figcaption></figure><p>The thing I do not like about this mirror image is that light comes in from the background and the mirror sphere’s side we see looks seperated from all the light coming inside. Perhaps the steps we will take in the next part would be better for a scene similar to this.</p><h3>Encountered Problems</h3><p>I encountered a problem with the head environment light scene. At first I did not see the head at all. So I decided to translate it further back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GoQX9PMGoRcLTc5r7eAJyA.png" /><figcaption>Head Environment Light — Problematic Test</figcaption></figure><p>This looked kind of scary, but I later realized that all head intersections happened between the camera and the near plane. In the ‘motion blur boxes’ scene from part 3, taking these as proper intersections caused issues. The near distance was 10.01 and there was a wall at z = 10.00. If that was count as an intersection, we only saw a wall. I think this opposes that scene. If I count these as proper intersections in the head environment light scene, it works. I decided to handle this by adding an IgnoreNp option to the camera in the input .xml file. I give it a 0 or 1 value to check if I want to get the intersections between the camera and the near plane. This works properly, but I added 1 line to the head environment light scene. Here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*TfZdzvVICBl-K2XHgPYozw.png" /><figcaption>Head Environment Light — 900 samples — 107.476 seconds</figcaption></figure><p>The bad thing here is I still did not implement smooth shading and the absence of it is jarringly appearent in this scene. The other thing is there was a comment on the top of the .xml file and that caused a problem for some reason and it was fixed when I deleted the comment. I would not call this a problem or anything but wanted to mention this subtle change.</p><h3>Conclusion</h3><p>This part was extremely enjoyable. The scenes look extremely cool and the new features added a whole new level of realism to our images. Also, this part was easy to understand and implement, especially as there are no problems in the previous parts (this would be harder if I had to debug texture sampling).</p><p>The thing here is, I suspect that the next part will be way more difficult but also pretty cool again as we will dive into BRDF’s and path tracing. See you in the next part!</p><h3>References</h3><p>Akyüz, A.O. <em>Lecture Slides from CENG795 Advanced Ray Tracing</em>. Middle East Technical University</p><p>Cambridge in Colour. (n.d.). <em>Gamma correction</em>. Retrieved December 28, 2024, from <a href="https://www.cambridgeincolour.com/tutorials/gamma-correction.htm">https://www.cambridgeincolour.com/tutorials/gamma-correction.htm</a></p><p>LearnOpenGL. (n.d.). <em>Gamma correction</em>. Retrieved December 28, 2024, from <a href="https://learnopengl.com/Advanced-Lighting/Gamma-Correction">https://learnopengl.com/Advanced-Lighting/Gamma-Correction</a></p><p>Marschner, S., Shirley, P., Ashikhmin, M., Gleicher, M., Hoffman, N., Johnson, G., Munster, T., Reinhard, E., Thompson, W.B., Willemsen, P., &amp; Wyvill, B. (2021). <em>Fundamentals of computer graphics</em> (5th ed.). A K Peters/CRC Press.</p><p>Reinhard, E., Stark, M., Shirley, P., &amp; Ferwerda, J. (2002). <em>Photographic tone reproduction for digital images</em>. ACM SIGGRAPH. <a href="https://doi.org/10.1145/566654.566575">https://doi.org/10.1145/566654.566575</a></p><p>Rosen, D. (2010, February 17). <em>Gamma-correct lighting</em>. Wolfire Blog. Retrieved December 28, 2024, from <a href="http://blog.wolfire.com/2010/02/Gamma-correct-lighting">http://blog.wolfire.com/2010/02/Gamma-correct-lighting</a></p><p>Wikipedia contributors. (n.d.). <em>Tone mapping</em>. In <em>Wikipedia</em>. Retrieved December 28, 2024, from <a href="https://en.wikipedia.org/wiki/Tone_mapping">https://en.wikipedia.org/wiki/Tone_mapping</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b4e6d14ea8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Ray Tracer: Part 4.2]]></title>
            <link>https://medium.com/@Ksatese/advanced-ray-tracer-part-4-2-f783379e89de?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f783379e89de</guid>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[texture-mapping]]></category>
            <category><![CDATA[bump-mapping]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 02:04:35 GMT</pubDate>
            <atom:updated>2024-12-18T02:08:15.138Z</atom:updated>
            <content:encoded><![CDATA[<p>In this update I will talk about the fixes and changes I did after part 4.</p><p>All images seen in the post are rendered by my raytracer. The tests are conducted using the Apple MacBook M3 Pro chip with 5 performance cores with 4.06 GHz and 6 efficiency cores with 2.8 GHz.</p><h3>Problems and Fixes</h3><p>As you might remember, I could not render the VeachAjar and mytap scenes. I suspected the issue to be about the parsing part and so it was. In the mytap scene, I did not read the texture coordinates correctly and that was way more appearent than what was going on in the VeachAjar scene.</p><p>Turns out while parsing texture coordinates from .ply files, I added an unnecessary +1 to get the indexing right for the tex_coords I hold, but I was wrong to do so. That fixed the mytap scene:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a29DICIYSjalOrbK0Yz-vQ.png" /><figcaption>My Tap — 791.8 seconds — 256 samples — 0.01 bump factor</figcaption></figure><p>In this case, the bumps on the wall are less appearent of that in the sample output. You can see bumps when you zoom in or see the image in full size. I decided to increase the bump factor to make them more visible. I did not want to wait for another 13 minutes so decided to run with 4 samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JDrQS0wwlH7kq7bWhmyU6A.png" /><figcaption>My Tap — 11.7 seconds — 4 samples — 0.1 bump factor</figcaption></figure><p>We can see the bumps way more clearly this way. I mentioned this issue where the visible bumps are not exactly the same with the sample outputs and I multiplied with some constants to match closely with the samples. In this case, the bumps stayed less appearent than my other results so this bump factor change was a need.</p><p>After handling this, I moved onto the VeachAjar scene. It turns out that I had a problem with mesh and mesh_instance ids. In part 2, mesh_instances could take other mesh_instances as a base mesh. I handled that by looking at the ids. In part 2, the meshes and mesh instances were indexed in the same list like:</p><blockquote>mesh — id = 1</blockquote><blockquote>mesh — id = 2</blockquote><blockquote>mesh_instance — id = 3</blockquote><blockquote>mesh — id = 4</blockquote><blockquote>mesh_instance — id = 5</blockquote><p>But the VeachAjar scene equivalent is:</p><blockquote>mesh — id = 1</blockquote><blockquote>mesh — id = 2</blockquote><blockquote>mesh_instance — id = 1</blockquote><blockquote>mesh — id = 4</blockquote><blockquote>mesh_instance — id = 2</blockquote><p>This was a problem for me and I did not know how to work the using a mesh_instance as a base mesh for another mesh_instance part. I could not find a way to differ which is it: mesh id or mesh instance id. I could change the code to be correct for this part but I would in return sacrifice some scenes from part 2 which I do not want to. So I changed ids in the VeachAjar scene a little by approaching mesh instances in the same list as meshes. This provided some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxg8j76wdJRKbZwnZP5f4g.png" /><figcaption>Veach Ajar — Problematic</figcaption></figure><p>The issue was about the objects that have composite transformations. This was the first scene that had composite transformations and turns out the issue here was that I parsed the composite transformation matrix elements as integers. After fixing that I had this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvQ3N9FzooAAKgxXN0Re2g.png" /><figcaption>Veach Ajar — 26.9 seconds — 16 samples</figcaption></figure><h3>Conclusion</h3><p>This looks all correct to me so all outputs from part 4 are now fine. Although I did not try every single scene from the prior parts right now, there seems to be no faulty render in the big scenes from the first 4 parts.</p><p>I finished these fixes 5 days after the deadline, which is 2 days after the blogpost deadline and writing this post that night so this does not really matter grade-wise. I just wanted to render every scene. I also want to keep this blog as my whole journey, so I was tempted to write about it.</p><p>Again, see you in part 5!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f783379e89de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Ray Tracer: Part 4]]></title>
            <link>https://medium.com/@Ksatese/advanced-ray-tracer-part-4-87d1c98eecff?source=rss-e39be7749aab------2</link>
            <guid isPermaLink="false">https://medium.com/p/87d1c98eecff</guid>
            <category><![CDATA[bump-mapping]]></category>
            <category><![CDATA[texture-mapping]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <category><![CDATA[normal-map]]></category>
            <dc:creator><![CDATA[emre_baba66]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 17:53:27 GMT</pubDate>
            <atom:updated>2024-12-13T22:21:49.337Z</atom:updated>
            <content:encoded><![CDATA[<p>In this part, I implemented texture mapping, Perlin noise, normal mapping, bump mapping. I also added bump mapping with the generated Perlin noise and a cool procedural checkerboard texture. All of these features help us add more realism and help us create more versatile scenes. I expected this part to be easier than the first three as it required less algorithmic complexity (kind of ignored the given hint about the part) which was my mistake. This was probably the most challenging part for me but I think I managed.</p><p>All images seen in the post are rendered by my raytracer. In this post, I will try to go from the simpler concepts to the more advanced ones while also explaining the ideas in depth. This time, I did not run time tests as the images generally have low sample counts. So let’s begin!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KVnOLmHgOG_5VzzbHDiwg.png" /><figcaption>Galactica Static — Texture Mapping, Bump Mapping</figcaption></figure><h3>Texture Mapping</h3><p>Texture mapping is the concept of putting a previously creates image on an object. This might be something like putting a wood texture on a wooden table or putting a painting texture on a paper. The ideas are limitless here. You can even use only textures to determine the shading coefficients of objects, although this would be inefficient and quite weird. So we generally use this technique to broaden the stuff we can do with our ray tracer and render images with anything displayed or written on them that would be extremely difficult or impossible to generate by our own.</p><h4>Background</h4><p>I believe the first thing I should get out of the way is the preliminary of this whole process of mapping something onto a mesh or sphere. The main thing to consider first is the range we use as our texture coordinates. We usually map our textures in the [0, 1] range. The textures are 2D images so we use a 2D coordinate system denotex by (u, v).</p><p>Our textures are given to us in some kind of image format that we read. The issue here is finding out where to look when a ray hits an object and that object has a texture assigned to it. The spherical case is quite simple as we usually use angles to parameterize the mesh and get (u, v) values (each between 0 and 1) to find out where to look in the given texture. In most cases, we would consider out texture’s corners to be (0, 0), (0, 1), (1, 0) and (1, 1) so our (u, v) values fit them.</p><p>But how can we find such a mapping when we have a complex object with a texture like the spaceship in the galactica scene above? In our case, every vertex that came with the object also includes a texture coordinate associated with it. ın the simplest case, these textures coordinates will be between 0 and 1 as I mentioned earlier. And the texture we use for the spaceship looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_poTMtID4g3CTrIciPLjxQ.jpeg" /><figcaption>Galactica Spaceship — Texture atlas</figcaption></figure><p>This is called a texture atlas. So combining these we can deduce that someone actually parameterized this mesh for us beforehand and painted the textures for it knowing this parameterization. Mesh parameterization is actually a huge area in and of itself. I am currently working on a project related to this topic and planning on blogging it too. You can check it out in the blog page in the following weeks.</p><p>The main idea you should keep in mind right now is:</p><ul><li>Only we parameterize the spherical objects</li><li>Someone previously parameterized and gave us the coordinates of where the vertices of the mesh lie on the texture</li><li>The texture values we want to read might not exactly need to be where the vertices are. Only vertices’ parameterizations are known. We need to come up with a way to handle when a ray hits on the inside of a triangle</li></ul><p>So having the idea of what we get as input.</p><h4>Texture Mapping Spheres</h4><p>The spherical case requires us to think of two angles: <em>theta</em> and <em>phi</em>. These represent the angles the point we want to get the parameterization of makes according to the sphere. If you think of a 3 dimensional space with a sphere centered at the origin, the <em>phi</em> angle could be the angle between the point’s projection on the x, z plane and the <em>theta</em> angle could be the angle between the point’s projection on the y, z plane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*n8OC2vEGaejQZgiQ9Fp4LA.png" /><figcaption>Sphere Texture Mapping — Lecture Notes by AO Akyüz</figcaption></figure><p>We already know where the ray hit so we know the x, y and z coordinates. So we get the <em>theta</em> and <em>phi</em> angles in radians, but the ranges for them are different. You can see from the image above that the <em>phi</em> angle spans a whole circle from both sides, while <em>theta</em> spans only one side: one spans form [- pi , pi] and the other [0, pi].</p><p>Mapping these onto the [0, 1] range is actually quite easy. We can just add pi to -phi and divide it by 2pi to get the u coordinate. We can also just divide theta by pi to get the v coordinate. I think the reason we use -phi is about the orientation we want to utilize the texture and later the normal orientation we use: right handed or left handed.</p><p>So we get the u and v coordinates with in between our desired range.</p><h4>Texture Mapping Triangles</h4><p>Texture mapping triangles is easier. We are already (but only) given the (u, v) values of the vertices. But when a ray hits a triangle, we need to get its (u, v) by using these values. We can use barycentric coordinates to achieve this. You might remember this from the first part of the series. We can get a weighted average of the texture coordinates of the vertices by using this. Let’s recall:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Pryb0ODcP0z8rKnkeTjmsQ.png" /><figcaption>Barycentric Coordinates — Lecture Notes by AO Akyüz</figcaption></figure><p>Here we would normally find the intersected point’s coordinates by using this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*3479CDtq5R6_13L_MRPPKg.png" /><figcaption>Barycentric Coordinates — Lecture Notes by AO Akyüz</figcaption></figure><p>In this case, we will use this for the texture coordinates and all will be done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*5WaHO51tEOFpNzPT0OExnQ.png" /><figcaption>Texture Mapping Barycentric Coordinates — Lecture Notes by AO Akyüz</figcaption></figure><p>So having these u and v values, we can move onto actually reading data from the textures. But there might be a middle step here that we need to stop by.</p><h4>Tiling</h4><p>For larger surfaces we would like to add textures to, we might refrain from only 1 texture that goes through the whole surface. This would cause distortions in the texture’s look. Instead, we would want to repeat the texture on the surface as big as is. Some texture coordinates are given to us in the scenes in larger values than 1. This is the case where tiling happens. If our found u and v values are bigger than 1, we take the integer floor and subtract it from the u and v values. For example if the u value is 3.30, subtracting the floor would be: 3.30–3.00 = 0.30. The same could be done with the v values. This is like a mod function and it helps us repeat the texture over the surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*baJJM7vdmMbKfrQ1-h8z6A.png" /><figcaption>Tiling — Lecture Notes by AO Akyüz</figcaption></figure><p>The problem here might be that the repetition look clearly in some cases, but this is not something we need to focus on right now.</p><h4>Interpolation Strategies</h4><p>Having the u and v values, we can convert them to image space coordinates ranging from [0, image width] and [0, image height]. We can do this simply by multiplying the u with the image width and the v with the image height. Let’s call these values i and j.</p><p>The issue here is that our textures are in image format and we can not directly access texel(‘texture element’, data in a simple texture image pixel) values using floating point numbers, only integers. Our point likely lies in between several integer values and therefore pixels we could read from. We can follow multiple paths here.</p><h4>Nearest Neighbor</h4><p>The first thing we could do is, we could just round the i and j values and get the nearest integers to them. Then we can read from the image using these. This would obviously be really fast, but not give the smoothest results as we only round and do not interpolate.</p><h4>Bilinear Interpolation</h4><p>Bilinear interpolation is a better way. We just get the average of the four closest neighbors. You can think of a pixel falling in between 4 texel center points anyways so this is pretty easy to visualize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*G_YoHtomtemwJjbizRS2KQ.png" /><figcaption>Bilinear Interpolation — Lecture Notes by AO Akyüz</figcaption></figure><h4>Trilinear Interpolation</h4><p>Trilinear interpolation is much more complicated than the first 2 ways. It was first talked about by Lance Williams in his 1983 paper ‘Pyramidial Parametrics’. I read the paper and tried to understand the concept more in depth by doing some extra research.</p><p>This approach requires mipmaps to function. Mipmaps are progressively smaller versions of a texture. An example from the paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*TN28pB8i_WIwPjprzFi70A.png" /><figcaption>Mip map of the flexible NYIT Test Frog — Williams, L. (1983). <em>Pyramidal Parametrics.</em></figcaption></figure><p>Why the paper’s name include pyramidial is that, Williams thought about layering these mipmap levels on top of each other and sampled from the neighboring two at the same time. You can see a representation of this here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4Pu0x5LOjc4pvdMIS_d0A.png" /><figcaption>Mipmap and Mip hierarchy representation — CMU Computer Graphics Lecture Notes</figcaption></figure><p>When researching more, one of the clearest definitions was this from a blog post:</p><blockquote>The visible transition between the MIP maps can finally be countered with <em>trilinear </em>interpolation. Where bilinear interpolation interpolated in two dimensions by blending four pixels, trilinear interpolates in three dimensions. The extra dimension is a blend between two MIP maps. The number of memory operations is now eight: four pixels in each of the two MIP maps that we interpolate between. — Bikker, J. <a href="https://jacco.ompf2.com/2020/04/10/optimizing-trilinear-interpolation/">Optimizing Trilinear Interpolation</a>.</blockquote><p>I will not talk about it much more as I did not implement this. I actually never planned to, just wanted to gain insight and give some to the reader. You can check out the sources I will add at the end.</p><h4>Utilizing Read Data</h4><p>So we are close to the end of our process. We read RGB values from the textures at this point and can utilize them in our shading process to give our objects some extra color. There are a couple of things we can directly do. We can put these RGB values in the [0, 1] range and use them as our diffuse reflectance coefficient, specular reflectance coefficient or blend them with each other.</p><p>Finally, time to see some cool rendering results that you can compare approaches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Q54GhF5_0xI8LxQBfon66Q.png" /><figcaption>Plane Nearest Neighbor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pRblBBhjql42lc9fq28VhA.png" /><figcaption>Plane Bilinear</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*h5bTQHdh702ITeEgbQ2m_w.png" /><figcaption>Sphere Nearest Bilinear</figcaption></figure><p>As you can see, my results also show that bilinear interpolation works much better than the nearest neighbor approach. It would be cool to also compare with trilinear interpolation…</p><p>Here are other examples with a more ‘real world’ use case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jD2uLLwOMLg6i4zW625pXg.png" /><figcaption>Cube Wall— Replacing kd</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8Tey51nzY_pNGJ6_Hwiv-A.png" /><figcaption>Wood Box — Replacing kd and ks</figcaption></figure><p>In the Wood Box case, we also replace the specular reflectance coefficient reading a texture to dampen the excessive reflection of light on the wooden surface. Here is how it looks without replacing ks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*veacUr0w2QwjuNwdNuMCPw.png" /><figcaption>Wood Box No Specular — Only replacing kd</figcaption></figure><p>The texture we use here to replace the specular reflectance coefficient looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*arl77L61oBjhj3gox03hUA.png" /><figcaption>Wood Box Specular Texture</figcaption></figure><p>What is cool with this is that it removes specular reflectance from the wooden part while keeping it in the metal areas. I think this is a cool trick. There is another really cool trick we can do to add some background.</p><h3>Background Textures</h3><p>You can guess what we will do here quite easily. Our near plane that we send rays through is also a rectangular surface and we can associate a texture to it and approach it like a plane with z = infinity. If our rays do not hit any object, we normally return the background color, in this case, we will return the color of the texture, according to the point the ray goes from in the near plane. This is how we get the space background in the galactica scenes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KVnOLmHgOG_5VzzbHDiwg.png" /><figcaption>Galactica Static — Background Texture</figcaption></figure><p>So we are done with the main texture mapping part. The procedures I mentioned here will also be used for normal and bump mapping. The difference will be what we will do with the values we read.</p><p>But first, let’s talk about procedural textures. Procedural textures are ones that are generated on the fly without using texture images. We will look at the approaches I implemented in this part and their use cases.</p><h3>Perlin Noise</h3><p>Procedural textures can be generated in many ways. The simplest ones might be the ones that are generated using trigonometric functions or checkerboard which we will talk about later. What these textures lack is they do not look natural at all. To make procedural textures look more natural, we need to add some randomness, but too much would also look quite unnatural as it will turn into extreme noise. One idea could be to hold random values for each integer (x, y, z) coordinate in our space and interpolate between these points with trilinear interpolation to get the controlled random value. But this would occupy too much memory as we would need a 3D lattice that is bigger than the whole scene. Ken Perlin created a solution for this problem in his paper ‘An Image Synthesizer’, published in 1985. Here are the steps to his solution in 3D:</p><ul><li>Associate 8 random gradient vectors at grid corners</li><li>Compute the vectors from the corners to the desired point</li><li>Compute the dot product of each vector with the corresponding gradient vector</li><li>Compute the contribution of each corner based on the distance of the point to the corners</li><li>Finally: 2 ways to visualize</li></ul><p>I believe this is easy to follow except the last 2 parts. To compute the contribution of each corner, we use this function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*5s3_ehYAjTYjytImCJkBpw.png" /><figcaption>Perlin Noise Interpolation — Lecture Notes by AO Akyüz</figcaption></figure><p>Then we can calculate weights by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*x8Zyd4xFkvmJmT92irKXIQ.png" /><figcaption>Perlin Noise Weights —Lecture Notes by AO Akyüz</figcaption></figure><p>These weights are for 2D here, need to add 4 more and all of them should also have the z values.</p><p>Before moving onto the final visualization part, I want to touch on the first part: associating 8 random gradient vectors at grid corners.</p><h4>Random Gradient Vectors</h4><p>As I mentioned, the crucial part of this algorithm is that we do not have to store a 3D grid as large as the scene itself. What we do instead is, we pseudorandomly choose gradient vectors using a hash function. In this case, when we want to calculate the noise for a point, no matter how many times we do it, we will get the same gradient vectors for each point.</p><p>Here, a pseudo-random permutation table and pseudo-random unit-length gradient vectors are used in the hash function. We can see more about the implementation and how it was improved by Perlin in his paper ‘Improving Noise’ published in 2002:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*cBBk6tNQeQLv5L8ICewlbw.png" /><figcaption>Deficincies in Original Algorithm — Perlin, K. Improving Noise. 2002.</figcaption></figure><p>As you can see, they first used another function for the interpolation. In this paper, Perlin proposed a new one (similar to ours):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*fKDNSo8WIL27IP41lCBuEg.png" /><figcaption>New Interpolation Function — Perlin, K. Improving Noise. 2002.</figcaption></figure><p>He also mentioned a problem about there being directional bias here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*4D6pvs0ALnp7u48bKlgfcw.png" /><figcaption>Directional Bias Problem — Perlin, K. Improving Noise. 2002.</figcaption></figure><p>He proposed a new set of gradient vectors to keep to solve this problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*n60Hfj7bqM6CEkE_TpY0tA.png" /><figcaption>Unit Length Gradient Vectors— Perlin, K. Improving Noise. 2002.</figcaption></figure><p>So he concluded that the permutation table produced enough randomness and decided to go with a set of clearly defined unit vectors. I am not quite sure why the other approach would cause problems. Here is the last thing he does:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*lvWR0vkWTh_bCkdniorW6A.png" /><figcaption>Padding to 16 — Perlin, K. Improving Noise. 2002.</figcaption></figure><p>I am not quite clear on why he does this either but this whole paper resembles AO Akyüz’s approach.</p><h4>My Implementation</h4><p>I read this paper after implmenting Perlin noise myself. I just wrote a simple hash function and my approach was really basic, I just multiplied the x, y and z values by some large numbers and added them up, then did a bitwise shift and XOR. I also used these 12 vectors and ones with the same magnitude, but only in the x, y and z directions. So I had 18 vectors, I just ran the hash function, took mod 18 and got the gradient vector. Then continued with the following steps. My approach worked just fine so I did not want to change it.</p><p>Having covered this part, we can move onto the visualization.</p><h4>Final Noise</h4><p>Upto the final part, our noise value is typically in the range of [-1, 1]. We can do 2 things here. We can just add 1 and divide by 2, this would be a typical way to put it between 0 and 1. We can also take the absolute value of the noise which would increase contrast.</p><p>Here are my results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*FrUgGjgaYKqYYX-1mKFLIQ.png" /><figcaption>Cube Perlin</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*H3VszYmM7ujNnf5Bgn2Mng.png" /><figcaption>Sphere Perlin</figcaption></figure><p>We can also change the scale of our Perlin noise texture, which would make it fuller:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*zAPCgnBVnpWG-EkFzuQeTQ.png" /><figcaption>Sphere Perlin Scale</figcaption></figure><h4>Multi-Octave Perlin Noise</h4><p>One last thing we can do is introduce a multiple octave Perlin noise. Here is the formula we can follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*JWWu3pRM6asG2dVrIJoqHA.png" /><figcaption>Multi-Octave Perlin Noise — Part 4 Notes by AO Akyüz</figcaption></figure><p>In this formula, <em>K</em> is the number of octaves. By default this value is 1 as n is our noise function and we only run it as is only once. If the number of octaves is bigger than one, the frequency is doubled and the weight is halved. <em>s</em> is the total accumulated noise.</p><p>This is actually easy to visualize. Higher frequency would mean finely detailed or repeated noise, lower would be much broader. Here, we go from lower to higher frequency while decreasing the weight. This means that the broader noise octaves we get will be much more appearent and we will add the high frequency noise with little weight so it will be less distinct. We can get marble, smoke and cloud-like results with this approach.</p><p>Here is an example using multiple octaves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UoaafQEQDUIwk-IN3MhwQ.png" /><figcaption>Dragon — 7 octaves — by Ramazan Tokay</figcaption></figure><p>This looks great in my opinion and is the coolest scene I have rendered so far. Many thanks to Ramazan!</p><p>So being done with Perlin noise, we can move onto the second procedural texture.</p><h3>Checkerboard Pattern</h3><p>This was by far the easiest part. I do not want to stay on this for a long time at it is extremely simple. I just followed this pseudocode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*NNJEux8sNk1BQbrGwPpfbQ.png" /><figcaption>Checkerboard Pseudocode — Part 4 Notes by AO Akyüz</figcaption></figure><p>And tried the texture with one of the box scenes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*amDBLK0gAvRo3wGKJAz-Ew.png" /><figcaption>Cube Wall Checkerboard — Problematic</figcaption></figure><p>There was a lot of noise so I added small epsilon values to the function and all was fine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wIOgwZfnQs0iCqvZTEN0Tw.png" /><figcaption>Cube Wall Checkerboard</figcaption></figure><p>There are 2 small white dots near the corner but I think that is just okay at this point. Let’s move onto the next part!</p><h3>Normal Mapping</h3><p>Now we move onto another territory where we will try to make it look like the object’s geometry changes. What would be best for this is displacement mapping. With normal and bump mapping we will not get self shadows. On the other hand displacement mapping provides a more realistic look including self shadows by actually changing the geometry. In this part we will only change the normals that we use in shading to make it look like objects have some geometric features when they really do not.</p><p>Normal mapping is where we read the texture value and use that value as our new normal. We need to figure out how to represent normals in the range [-1, 1] using the 0–255 values we read from the image. To map them to 3D directions, the following formula can be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*-loojw4-j9VlvcSoWbiP7g.png" /><figcaption>Reading Normal Values — Lecture Notes by AO Akyüz</figcaption></figure><p>Then we need to normalize. Getting this done, we should move on to the most crucial point.</p><h4>Triangle Normal Mapping</h4><p>Normals in these textures are defined in the canonical tangent space of the surface. What you might think of is, the texture has its own space, and its own 3 orthogonal vectors, we need them to fit the surface’s corresponding vectors, so we need to transform them. We know in the texture space we have U and V, now we also have W as the normal. In the real tangent space of the surface we have (T, B, N) which are tangent, bitangent and normal vectors which correspond to U, V and W. Explaining all the steps to find the transformation matrix would take too long, so I will give some formulas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nouB6le59AXVzfccbSqCZA.png" /><figcaption>Finding Tangent and Bitangent Vectors — Lecture Notes by AO Akyüz</figcaption></figure><p>In this equation, T and B are the tangent and bitangent vectors and that is what we want to find. E1 and E2 are two edges that share a point on the triangle we hit. delta u and delta v are the differences in the u and v vectors of E1 and E2. After getting the tangent and bitangent vectors, we need to normalize them. Then we can calculate (bitangent x tangent) to get the new normal.</p><h4>Sphere Normal Mapping</h4><p>With spheres, we will get our (u, v) values exactly the same way we did in texture mapping. Then we will plug the u and v values back into the x, y and z values as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*aubwIZ0VOCMWZXAN2xZ47Q.png" /><figcaption>Plugging (u, v) into x,y and z — Lecture Notes by AO Akyüz</figcaption></figure><p>So here we denote x, y and z in terms of u and v. Right now, we can take x, y and z’s partial derivatives with respect to u and v. This would give us how much the point’s coordinate changes as u and v change. And this operation would exactly give us the tangent and bitangent vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*Dn6o4NOwYiLIKSd_x9pGZA.png" /><figcaption>Partial Derivatives to find T and B — Lecture Notes by AO Akyüz</figcaption></figure><p>This operation results in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*XR0oi_FzwvdpT8WDQQyNSw.png" /><figcaption>Partial Derivatives to find T and B — Lecture Notes by AO Akyüz</figcaption></figure><p>After finding the T and B again, we can normalize them and take their cross product to find a new N.</p><p>So at this point, we have T, B and N vectors for the triangular and the spherical cases. How can we make use of them?</p><h4>Final Steps</h4><p>As we have the T, B and N vectors, we can now find our final new normal by turning this into a transformation matrix and transforming our initially found and normalized (x, y, z) normal vector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*5GZ9qzdXbTVMd4O0IP-XOw.png" /><figcaption>Finding the new normal — Lecture Notes by AO Akyüz</figcaption></figure><p>So at this point, everything should be done. Here are some cool results with normal mapping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*siuZER-I56XTMraADbHt6Q.png" /><figcaption>Cube Cushion with Normal Mapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SYeQIiWn0tExcso-JJ1u5Q.png" /><figcaption>Cube Waves</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*x93HS1xiRiSBD1Ovxkl-bw.png" /><figcaption>Cube Wall with Normal Mapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*upMWbYc7sdkL3MGydbdRCQ.png" /><figcaption>Brick Wall with Normal Mapping</figcaption></figure><p>To illustrate this further, I can remove the coloring in the last 2 textures to only display the normal mapping part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wP8x9zQphuoN2g5Lu6LtNg.png" /><figcaption>Cube Wall with Only Normal Mapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6b2kfL-3Eo9svqJKzPEu4w.png" /><figcaption>Brick Wall with Only Normal Mapping</figcaption></figure><p>So this part looked like a success. Although I had some issues regarding implementing the formula. I wrote some stuff wrong and I captured one of the wrong inputs beforehand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vVUkaZElPavI8jQXJO40YA.png" /><figcaption>Cube Waves Problematic</figcaption></figure><p>This was fixed quite easily as I found a mistake in one of the formulas.</p><p>Having this done, we can move onto bump mapping.</p><h3>Bump Mapping</h3><p>Unlike normal mapping, bump mapping does not completely change the normals of the surface. It only perturbs the existing normals using a height function it reads from the texture. I think this was the trickiest part. We will rely more on partial derivatives here and it is kind of math heavy.</p><p>First of all, we will define our bumped surface as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*MPYBsNEElvxqDiETh9bZiA.png" /><figcaption>Bumped Surface — Lecture Notes by AO Akyüz</figcaption></figure><p>Here p is the point, h is the height function and n is the normal. Then we can find our new normal as we did with the bitangent and tangent vectors: by taking the cross product of partial derivatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*NpFuNImDruP8IBG0V050Dw.png" /><figcaption>New normal — Lecture Notes by AO Akyüz</figcaption></figure><p>So we need to find the partial derivatives first. By using the chain rule, we can find:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ZYFR4bi70o53iYHjOS0DqA.png" /><figcaption>Bumped Surface Partial Derivatives — Lecture Notes by AO Akyüz</figcaption></figure><p>Again the whole idea here is that we want to find the bumped surface’s function and how it changes as u and v changes. Then we can get the cross product of the changes in these 2 directions and get our new normal.</p><p>As you might remember, the red circled parts are the tangent and bitangent vectors respectively. And the green circled are the partial derivatives of the height function. We can define a height function roughly by putting the read RGB values into the [0, 1] range and then adding them up. We can also divide by 3 to also put it in the [0, 1] range to add normality. We can find the derivatives of the height function by using the method of forward differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*3gzFmdBumbMM3CS2s2X5Jw.png" /><figcaption>Forward Differences — Lecture Notes by AO Akyüz</figcaption></figure><p>delta u and delta v can be picked as 1 / image_width and 1 / image_height. But I think this roughly corresponds to stepping into the next texel in each direction so getting the next texel directly could work. Then we will multiply this with our normal and add up with the tangent and bitangent vectors for each case.</p><p>The computation of the last uncircled part of our surface equation is really complex and adds little to the overall surface so we will ignore it. I wanted to illustrate the idea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIw1s3BwmChmswFEB_CzNw.jpeg" /></figure><p>Here is our main setup. We will only look at the difference in the direction of the u vector as drawing also with v would be difficult.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WG2pIPaSCZVTM159JfEebw.jpeg" /></figure><p>I think this is a good and clear way of getting the basic idea.</p><p>Finally, I want to briefly summarize what we do here:</p><ul><li>Get the tangent and bitangent vectors that correspond to the u and v vectors in the texture the same as in normal mapping.</li><li>Read from the texture and put the read RGB values in a determined height function.</li><li>Take the height function’s partial derivatives which corresponds to how much height changes when we continue in the u and v directions and multiply that with the normal.</li><li>Sum up the tangent vector which represents the change in the real surface when we go in the u direction with the multiplication of the normal and the change in the height function when we go in the u direction. And same with the bitangent vector and the v direction.</li><li>This whole process will perturb our tangent and bitangent vectors in the direction of the surface normal according to the height function(which would be varying according to the texture).</li><li>We will take the cross product of these perturbed vectors to get our final perturbed normal.</li></ul><p>After doing all of this, I saw bumps but they were not that correct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WEvIu9KkdxxHMLauZHHwKA.png" /><figcaption>Sphere Bump Test — Problematic</figcaption></figure><p>Turns out I forgot to multiply with pi in one of the formulas. This was extremely irritating as it took me long hours to find. Again the perturbations were not that appearent in my case so I multiplied with a constant to exeggerate them. I think the problem might be that I missed some normalization somewhere. But the results look pretty cool right now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KhCbN9vN6sh3izEUxPd8GQ.png" /><figcaption>Wood Box All — Only Bump Mapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iqwZVQkX-ek-vePdQLahPQ.png" /><figcaption>Wood Box All</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*u2avqFhox7-jLRvsD2Ggxg.png" /><figcaption>Sphere No Bump — Bump</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aMyIwKKI-T_BZ8fyfoGjfw.png" /><figcaption>Sphere No Bump — Just Bump</figcaption></figure><p>Bump mapping also works with transformations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wiP9KjFiuFdC8Y3pUVMcug.png" /><figcaption>Bump Mapping Transformed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*27geaX3ZCPiA3AqG7yljog.png" /><figcaption>Bump Mapping Transformed — Only Bump Mapping</figcaption></figure><p>I actually had a problem with these scene before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ANRojgqjG1lGTdAzMfP20A.png" /><figcaption>Bump Mapping Transformed — Problem</figcaption></figure><p>This was due to the very small scaling of a plane. I just increased the bounding box epsilons a little bit than before and it was solved.</p><p>Here is the previous galactica scene and a showcase of how we can combine with the features from the last part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KVnOLmHgOG_5VzzbHDiwg.png" /><figcaption>Galactica Static — Uses Bump Mapping</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dAA8RYA3U4shb7T71zvETw.png" /><figcaption>Galactica Dynamic — Bump Mapping and Motion Blur</figcaption></figure><p>This was another extremely cool scene. Here is another one where the surface texture coordinates are not in the range of 0 to 1 but 0 to 4. In this case we just tile the existing texture, something I mentioned at the beginning of the post:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9dAJFgyfm1_yYpfseM41Ow.png" /><figcaption>Killeroo Bump Walls</figcaption></figure><p>Here is another scene with transformations that showcases the features we have implemented upto this point (it’s a texture modified version of the ellipsoids scene from part 2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GzpVm0-ByCNXRJ3AWVpxkA.png" /><figcaption>Ellipsoids Texture</figcaption></figure><p>But there remains one last thing we will do which is bump mapping with Perlin noise.</p><h3>Bump Mapping with Perlin Noise</h3><p>In this case we also follow the same main route as the original bump mapping case. We follow the same formula to get qv and qu and take the cross product. After simplifying the equation, we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*0c6s15kokB961jMhDOlUOQ.png" /><figcaption>New Normal in Bump Mapping with Perlin Noise — Lecture Notes by AO Akyüz</figcaption></figure><p>The component we subtract from the normal is called the surface gradient. In our case, Perlin noise is a scalar field and its gradient is the vector that points along the greatest change of this scalar field. The surface gradient is this vector’s projection on the tangent plane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*TWBbfikxngqPFHxjpznw4A.png" /><figcaption>Getting Surface Gradient — Lecture Notes by AO Akyüz</figcaption></figure><p>We can find the surface gradient after calculating the gradient vector as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*f_Q0nsH-N_0l2SBZ98Ggkw.png" /><figcaption>Calculating the Gradient Vector — Lecture Notes by AO Akyüz</figcaption></figure><p>All of these ideas utilizing partial derivatives and gradient vectors could be hard for you to understand if you have not used them for a while. I suggest you watch this 5 minute video to get an idea and read the whole process from the beginning.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGkB4vW16QHI%3Fstart%3D169%26feature%3Doembed%26start%3D169&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGkB4vW16QHI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGkB4vW16QHI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6721074cf1edb638bceab15290458bd8/href">https://medium.com/media/6721074cf1edb638bceab15290458bd8/href</a></iframe><p>After implementing all of this, I had these results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*K69AX2podh9CkQhdD0QIYw.png" /><figcaption>Sphere Perlin Bump</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sJ8BBX9NdTEbH132xiVetg.png" /><figcaption>Cube Perlin Bump</figcaption></figure><p>As you can see, for the linear and absolute value approaches of Perlin noise, we get different results as expected here. The linear approach creates a tennis ball-like result in the spherical case. The absolute value approach looks more brainy.</p><p>These look great but I have some remaining issues in this part.</p><h3>Problems</h3><p>I have problems in 2 scenes in this part so the streak of going faultlessly has kind of ended. I added all of the features I should have but I believe I have the same problem of parsing the mytap and veach_ajar scenes. These scenes have .ply files that include the (u, v) coordinates next to the (x, y, z). I think I have a problem with reading these u and v values as the mytap scene’s texture looks skewed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8SqtnwCb95YAU1O92zq3Vg.png" /><figcaption>My Tap — 4 Samples — Problematic</figcaption></figure><p>I also can not render the veach_ajar scene as I can not do the first parsing of the scene, it does not continue to the rendering stage. I was not sure on why it would not work so decided to check the scenes from the prior parts to see if I broke something, but scenes from part 2 and part 3 were all okay. I will try to find the source of this issue.</p><p>I can’t decide if having these types of problems like parsing is better or worse than the actual subject related issues, nevertheless this infuriated me. I tried to solve it at the last day for a couple of hours but could not find the root. I did not want to break anything further as only 2 hours were left and decided to stop there.</p><h3>Some Notes</h3><p>I also stumbled upon something called parallax mapping in the book Real Time Rendering, written by Akenine-Möller and his collegues. In the book, what parallax mapping is good for and what it adds is written very clearly. Here it why it is used.</p><blockquote>A problem wiwth bump and normal mapping is that the bumps never shift location with the view angle, nor ever block each other. If you look along a real brick wall, for example, at some angle you will not see the mortar between the bricks. A bump map of the wall will never show this type of occlusion, as it merely varies the normal. It would be better to gave bumps actually affect which location on the surface is rendered at each pixel. — Akenine-Möller et. al. 2018. pp. 214- 215.</blockquote><p>I would want to look more into this and explain it here but I do not have much time at this point and this post will almost get past 5000 words. Nevertheless it seems to be a cool approach.</p><h3>Conclusion</h3><p>This part did not have algorithmic complexity, but it was quite hard and the workload was higher than usual. Some concepts were really interesting and I spent hours trying to learn more stuff in depth. I woultd consider this part a success not from the success of the rendered scenes but broadening my perspective on the world of computer graphics so I am quite happy with it. In the next part we will work on new light source types and HDR tonemapping. See you then!</p><h3>References</h3><p>Akenine-Möller, T., Haines, E., Hoffman, N., Pesce, A., Iwanicki, M., &amp; Hillaire S. (2018). <em>Real-time rendering</em> (4th ed.). A K Peters/CRC Press.</p><p>Akyüz, A.O. <em>Lecture Slides from CENG795 Advanced Ray Tracing</em>. Middle East Technical University</p><p>Bikker, J. (2020). Optimizing trilinear interpolation. <em>Jacco’s Blog</em>. Retrieved from <a href="https://jacco.ompf2.com/2020/04/10/optimizing-trilinear-interpolation/">https://jacco.ompf2.com/2020/04/10/optimizing-trilinear-interpolation/</a></p><p>Carnegie Mellon University. (2016). <em>Computer graphics: Texture mapping [Lecture slides]</em>. Retrieved from <a href="https://www.cs.cmu.edu/afs/cs/academic/class/15462-s16/www/lec_slides/07_texture.pdf">https://www.cs.cmu.edu/afs/cs/academic/class/15462-s16/www/lec_slides/07_texture.pdf</a></p><p>Perlin, K. (1985). An image synthesizer. <em>ACM SIGGRAPH 1985 Conference Proceedings</em>, 19(3), 287–296. ACM. <a href="https://doi.org/10.1145/325165.325247">https://doi.org/10.1145/325165.325247</a></p><p>Perlin, K. (2002). Improving noise. <em>ACM SIGGRAPH 2002 Conference Proceedings</em>, 681–682. ACM. <a href="https://doi.org/10.1145/566570.566636">https://doi.org/10.1145/566570.566636</a></p><p>Physics Videos by Eugene Khutoryansky. (2016, January 9). Gradients and Partial Derivatives [Video]. YouTube. <a href="https://www.youtube.com/watch?v=GkB4vW16QHI">https://www.youtube.com/watch?v=GkB4vW16QHI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87d1c98eecff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>