<?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 Amine Rehioui on Medium]]></title>
        <description><![CDATA[Stories by Amine Rehioui on Medium]]></description>
        <link>https://medium.com/@aminere?source=rss-170ddaac886e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H0Y964N6saVfTO38prLA0A.jpeg</url>
            <title>Stories by Amine Rehioui on Medium</title>
            <link>https://medium.com/@aminere?source=rss-170ddaac886e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:31:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aminere/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[Software Rendering from Scratch]]></title>
            <link>https://medium.com/@aminere/software-rendering-from-scratch-f60127a7cd58?source=rss-170ddaac886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f60127a7cd58</guid>
            <dc:creator><![CDATA[Amine Rehioui]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 07:56:14 GMT</pubDate>
            <atom:updated>2021-12-14T17:42:33.604Z</atom:updated>
            <content:encoded><![CDATA[<p>Graphic cards are now ubiquitous. Their main task is accelerating calculations needed by 3D graphical applications. There are many APIs used to interface with them, such as DirectX and OpenGL. But how did programmers do it, before the widespread adoption of graphic cards? The short answer is they developed the calculations necessary for 3D graphics by hand and ran them on the CPU. This is what is meant by <strong><em>Software Rendering</em></strong> and this is what this article is about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*9NT00dGt4wOpqmx5Xz5IcA.png" /><figcaption>Rendering using software rasterization on the CPU</figcaption></figure><h3>Source Code</h3><blockquote>Check out <a href="https://github.com/aminere/platz">Platz on Github</a>, a 3D Software Renderer written in C++ and illustrating the concepts in this article.</blockquote><h3>Techniques</h3><p>There are a few techniques for producing 3D graphics on the CPU. <strong><em>Ray-tracing</em></strong> is the most physically accurate, but the most expensive to calculate. It is more appropriate for offline rendering. <strong><em>Rasterization</em></strong> is more approximative but more suitable for real-time rendering.</p><h4>Ray-tracing</h4><p>Ray-tracing consists in visualizing the world by simulating the interactions between “light” and “matter”. It is done by sending rays of light from light sources onto the world and calculating their trajectory based on the nature and orientation of surfaces that are crossed by the rays. Then, for each ray that “makes it” to the viewer, color is determined at the corresponding screen location, based on the history of the ray. For more details on this technique, check out <a href="https://medium.com/@aminere/introduction-to-ray-tracing-390a986692ed">Introduction to Raytracing.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HuslVNzQtViPxbSOb4AJDw.gif" /></figure><h4>Rasterization</h4><p>Rasterization consists in converting an arbitrary 3D representation into a discrete 2D representation, sometimes called a “raster” image. This is based on two main approximations. First, the world is approximated as a list of geometric primitives, usually triangles. Second, each triangle is projected onto the screen and filled based on an approximation of the conditions at each point in the triangle. We will discuss this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*8_kxfEMGobyA13ZlFJ_pew.gif" /></figure><h3>Rasterization</h3><h4>3D representation</h4><p>Triangles are ideal candidates for representing 3D geometry. Grouping triangles can represent complex shapes, to a varying degree of detail. On the other hand, their structure is so basic that splitting a triangle can only yield 2 triangles. We will represent the world as a list of triangles.</p><h4>Conversion to 2D Screen Space</h4><p>In order to draw 3D triangles on a 2D screen, we must first set a convention, that defines how the origin of the 3D space and the origin of the 2D space are related to each other. This is arbitrary. So we will use a fairly common convention: The origin of the screen is at the top left corner, with the X and Y axes pointing Right and Down respectively. For the 3D origin, the X, Y, and Z axes will point Right, Up, and Forward. This is known as a <strong><em>Left Handed Coordinate System</em></strong> and is illustrated below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_9csXtrUF5LqjC56CpEEag.png" /></figure><p>This convention means that a 3D point at the origin (0, 0, 0) will end up in the center of the screen. But where should a point be located to end up on one of the edges of the screen? As a convention, we can consider 3D coordinates ranging from -1 to 1 to span the whole screen. This makes it simpler later to discard elements that are outside of the screen. Given this convention, a triangle at the origin would appear like in the following illustration, assuming the screen has a square resolution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*kRjx_wDEfTuDBqjafMsgHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*31Wg-gUw41kVc7pWGSGFzw.png" /></figure><p>If the screen is rectangular, the triangle will look distorted in the horizontal X dimension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MomTfQ5odC1t4nqb8PfXNw.png" /><figcaption>Distorted unit triangle on a non-square screen</figcaption></figure><p>To fix it, we must take the screen aspect ratio into account. This is done simply by dividing the X coordinate by the screen’s aspect ratio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*eTFx0wIuAxyPpEE49_iHlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*nXocZW2gO51qn5uwCQ5lJw.png" /></figure><p>This is the core idea behind converting triangles to screen space. Since we ignored the Z coordinate so far, this can be referred to as <strong><em>Orthographic Projection</em></strong>. There are different kinds of projections, and to support them in a generic way, we can use linear algebra: This consists in transforming the vertices using a projection matrix, before converting them to screen space. Here is a reference of the whole process, starting with a <strong><em>Perspective Projection</em></strong> matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Prf86gxebH0D_r-ELwKlmQ.png" /></figure><ul><li><strong>fov</strong>: The field of view in Radians</li><li><strong>aspectRatio</strong>: The screen width over the screen height</li><li><strong>zNear</strong>: The distance from the viewer where clipz / clipw= -1</li><li><strong>zFar</strong>: The distance from the viewer where clipz / clipw = 1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*-bCKZgXOFQJ3EyGTREgs6g.png" /><figcaption>Conversion from clip space to Normalized Device Coordinates (using perspective division)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*1fiLuVdfwp8BAdxBNx1N7w.png" /><figcaption>Conversion from NDC to screen space</figcaption></figure><h4>Filling Triangles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*KOGPfMFOkhDIUyBx7lh_cg.gif" /><figcaption>Testing if a Point is inside a Triangle using Barycentric Coordinates</figcaption></figure><p>Once the triangle is on screen, we need to figure out which pixels are part of it, and then determine their respective colors. A useful way to do it is to use <strong><em>Barycentric Coordinates</em></strong>. They are related to how a point is positioned relative to the triangle corners. If a point is inside a triangle, its barycentric coordinates are all positive and add up to 1. Otherwise, the point is outside the triangle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94d693c078ad5cfaa34b628f21d7bc33/href">https://medium.com/media/94d693c078ad5cfaa34b628f21d7bc33/href</a></iframe><p>A naïve implementation would be to check the barycentric coordinates of all pixels on screen. A common optimization is to first calculate a bounding rectangle around the triangle, then only traverse pixels within it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*N6FUvGD0jRqB3vjDliADag.gif" /></figure><h4>Coloring</h4><p>The simplest way of coloring a triangle is to use one color everywhere. This is fine but not very exciting… A more sophisticated way is to use 3 colors: one for each vertex. Then, we color the triangle based on a mix of the 3 colors. And very fittingly, we can recycle the barycentric coordinates that we used in the “pixel inside triangle” test. They are perfect as factors in the color mix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*H4i3MKV_CunEZyKiWl1HDA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80e5c647a01459b709ee4235a7ce0e1e/href">https://medium.com/media/80e5c647a01459b709ee4235a7ce0e1e/href</a></iframe><h4>Texturing</h4><p>In order to apply a texture to a triangle, we should first define which part of the texture to apply. Then, for each screen pixel, we determine a corresponding pixel on the texture and borrow its color. In computer graphics terminology, texture pixels are referred to as <strong><em>Texels</em></strong>.</p><p>Defining the part of the texture to use is done by assigning texture coordinates to each vertex. The idea is simple, texture coordinate range from [0, 0] to [1, 1], which corresponds by convention to the top left texel and the bottom right texel, respectively. Like we did for coloring, we determine an interpolated texture coordinate for each pixel, based on its barycentric coordinates, and use it to look up the corresponding texel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b657af50a2eb85ab4db4fba2d185997/href">https://medium.com/media/1b657af50a2eb85ab4db4fba2d185997/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*FzCtps3DgeCLk1MV0RKVNA.png" /></figure><h4>Perspective correct interpolation</h4><p>There is a slight problem with the approach above - When the geometry is at an angle with respect to the view, we notice a strange warping in the texture mapping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*1-SmIYjR4_if-pSG_uGOCg.png" /><figcaption>Interpolated texture coordinates are not in the correct perspective</figcaption></figure><p>This is a classic mistake in software rendering: Interpolating 3D vertex information using barycentric coordinates of a 2D triangle doesn’t take perspective projection into account. Since we project a 3D triangle onto a 2D screen, we should take into account the Z coordinates of the vertices when interpolating vertex information, because farther features are supposed to look smaller. This correction is called <strong><em>Perspective Correct Interpolation</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40cbf7e80bd36a9a0ba350abbd867fd5/href">https://medium.com/media/40cbf7e80bd36a9a0ba350abbd867fd5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*degA7ILh7RJrbQzBBl5LFg.png" /><figcaption>Perspective correct texture coordinates</figcaption></figure><h4>World Transform</h4><p>Rendering one triangle successfully is a good start, but in practice, it’s useful to render entire objects, which are made of many triangles. In addition, it’s useful to move objects around, rotate, and scale them. Although it’s possible to move an object by changing the vertex positions on all its triangles, it’s much better to manage the position, rotation, and scale information at the object level, and use linear algebra to transform the vertices at each object.</p><p>Transforming vertices needs to happen before projecting them. The same projection can be used for all objects, but each object can have its unique transform. We can represent the position <strong><em>p </em></strong>and the rotation <strong><em>r </em></strong>(in <strong><em>Quaternion </em></strong>form) of an object in a <strong><em>World Matrix</em></strong>, and use it to transform the vertices of the object. It would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*SMyOzy1XSBuMDNjDCaKeig.png" /><figcaption>Transforming a vertex using an affine transformation matrix</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b48ed712f7f5fab6a19f1668273ed1f8/href">https://medium.com/media/b48ed712f7f5fab6a19f1668273ed1f8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*E5DcFb3bP5itjL64vkm7Bw.gif" /><figcaption>Applying a transform to all vertices prior to projection</figcaption></figure><h4>Camera</h4><p>So far, we have been using a perspective projection matrix to project 3D triangles onto the screen. We have always been looking at them from the same viewpoint. What if we want to look at them from a different viewpoint? Again, we can use linear algebra.</p><p>To simulate a camera, we can imagine a virtual object that has a position and an orientation corresponding to the camera viewpoint we want. We construct a world transform based on that, and then invert it, to obtain a <strong><em>View Transform.</em></strong> Finally, we apply this view transform to the world space vertices prior to projecting them. This completes the entire 3D transformation pipeline, from local space to screen space, which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*P31diryGrtilEm0wEOusmQ.png" /><figcaption>3D Transformation Pipeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*xc3F-4HqL_naU2zCrlIv1A.gif" /><figcaption>Camera control using a View Transform</figcaption></figure><h4>Zbuffer</h4><p>If we render triangles that are overlapping from the camera point of view, we may notice the following problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*Byol_8th_jqxxwy1VCdS1Q.png" /><figcaption>Artifacts due to overlapping triangles</figcaption></figure><p>Some pixels that should be in the back are drawn on top of pixels that are in front. This is because the triangles are arbitrarily traversed for rendering, so nothing guarantees that surfaces closer to the camera will always be drawn in front. To fix this problem, we need to keep track of the distance of each pixel with respect to the camera. This consists of the Z component of the NDC position that is obtained after projection, and is referred to as <strong>depth</strong>. We ensure that pixels with a higher depth, i.e. farther from the camera are discarded if a pixel with a lower depth was already drawn at the same location.</p><p>This technique is referred to as Z-buffering. We initialize a screen-sized buffer with the maximum possible depth value, at the beginning of every rendering loop. Then, each time a pixel is processed, we check if its depth is smaller than the recorded depth. If it’s not, we discard it. Otherwise, we update the recorded depth with the pixel’s depth, and we draw it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcf6f2c2dea5708640e6ab7b1a21ffbf/href">https://medium.com/media/bcf6f2c2dea5708640e6ab7b1a21ffbf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*tyVT10Q6dzcjMZTqFMRb2g.png" /><figcaption>Rendering using a Z-Buffer</figcaption></figure><h4>Clipping</h4><p>Clipping means discarding non-visible elements. In software rendering, clipping is an important optimization, that ensures pixels on non-visible parts are not processed. Modern graphic cards perform this in a clip coordinates, which are obtained after projecting the vertices. We will implement it in world-space instead, as it&#39;s more generic and more reusable in other contexts.</p><p>First, we need to understand the concept of a <strong>Frustum</strong>: It’s the volume that is visible by the camera. It can be represented as a set of 6 planes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*iQxGALoIsyzTtE43rgQRTQ.png" /><figcaption>Testing a triangle again the view frustum</figcaption></figure><p>Second, we need to ensure that geometry that is outside or that intersects the frustum is clipped. All the triangles are tested against it. Those that fall completely outside are discarded, those entirely inside are kept, and those that intersect are clipped. Here is how to determine the 6 frustum planes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ded9558453b7acfc8b7bdcfba6f1372f/href">https://medium.com/media/ded9558453b7acfc8b7bdcfba6f1372f/href</a></iframe><p>And here is how to test a triangle against a plane, and slice it accordingly if they intersect: <a href="https://github.com/aminere/zmath/blob/master/src/clipping.cpp">Triangle/Plane clipping</a>.</p><h4>Back-face culling</h4><p>When rendering opaque triangles naively, it’s common to waste processing time on triangles that are completely obstructed, for example the triangles on the inside of an opaque cube:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Kj5Eto8XtrZLG7f5.gif" /></figure><p>To avoid this, each triangle can be considered as having 2 sides: a front-facing and a back-facing one. A convention is to render front-facing sides and discard back-facing ones. There are exceptions, especially for rendering transparent objects, because their back faces are partially visible through their front faces.</p><p>For opaque triangles, we determine which of its sides is currently facing the camera. If it’s the back one, we reject it early in the rendering process. This step is easy to do using the NDC coordinates of the triangle, because their local Z axis is exactly parallel to the view direction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0d2c106801bc3a2b3abbeed11d1bccd/href">https://medium.com/media/d0d2c106801bc3a2b3abbeed11d1bccd/href</a></iframe><h4>Model Loading</h4><p>Before implementing more interesting features such as shading and shadowing, it’s nice to use more interesting geometry than triangles and cubes. We will pick the very simple <strong>OBJ </strong>format and write a loader for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25103892b31d6cfe42d4bd3b9f835499/href">https://medium.com/media/25103892b31d6cfe42d4bd3b9f835499/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*JvCBbnryjc9OJicOjngi-g.png" /><figcaption>The infamous Stanford Bunny</figcaption></figure><h4>Lighting</h4><p>It’s time to introduce lighting! The core principle is that light originates from light sources, bounces around the world, and ends up in a viewer’s pupil. By “bouncing around”, I mean that each time light interacts with a surface, it is absorbed by an amount, and reflected in a direction, based on the properties of the surface. At a more fundamental level, light comes out with initial energy and direction, and basically loses energy and changes direction upon each contact. Ultimately, the colors we see are a representation of the remaining energy, and their intensity is modulated by the final direction.</p><p>This deserves a separate article, as computer graphics have come a long way and there are many modern techniques that deal with this realistically. For now, we will keep things simple and implement a classic method that is based on many approximations: The <strong><em>Phong Shading Model</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*SVnLQX7e9gL-lS0ixiM1dA.png" /><figcaption>Phong Shading Model</figcaption></figure><p>There are 3 main contributors to the result when using Phong shading. First, there is an <strong><em>Ambient Color</em></strong>. It represents the color on surfaces that are completely in the dark. A good practice is to set it to a very dark tone of the most preeminent color in the surroundings. For example, in an indoor environment where the walls are blue, the ambient could be a very dark tone of blue. If we are outside in a green forest, the ambient could be a very dark tone of green. The idea is that surfaces are never really completely in the dark, there is always some indirect lighting that is reflected off of the environment.</p><p>The second main contributor is the <strong><em>Albedo Color</em></strong>. It represents the inherent color of surfaces. But unlike the Ambient color, it’s combined with the amount of direct lighting that is reflected off the surface, giving a final <strong><em>Diffuse Color</em></strong>. In order to determine how much light is reflected, we consider the concept of a <strong><em>Surface Normal</em></strong>. It’s a representation of how a surface is oriented in space. The light amount reflected by the surface depends on the direction of the incoming light relative to the surface normal. It’s at a maximum if they are parallel, and is zero if they are perpendicular.</p><p>The last contributor is called <strong><em>Specular Highlighting</em></strong>. This adds a bit of realism by approximating the small highlights on shiny surfaces. It depends on the shininess of the surface, its normal, and also the viewing angle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e681169fd8553868a0a77fee2329d056/href">https://medium.com/media/e681169fd8553868a0a77fee2329d056/href</a></iframe><h4>Shadowing</h4><p>To handle shadows, we will simply darken the result of the previous lighting step, by a factor that depends on the amount of light that is received on the corresponding pixel by the surface. To determine the amount of light received at a particular pixel, we simply trace a ray towards all light sources. If a light source cannot be reached because the ray collided with a surface before reaching it, we subtract its influence and continue checking the other light sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*oZOHQJxkRmLMw_zUXfTD5Q.png" /><figcaption>Shadowing</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57a30b7b04e50d1c5d354033a9d273f1/href">https://medium.com/media/57a30b7b04e50d1c5d354033a9d273f1/href</a></iframe><h3>Source Code</h3><blockquote>Check out <a href="https://github.com/aminere/platz">Platz on Github</a>, a 3D Software Renderer written in C++ and illustrating the concepts in this article.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f60127a7cd58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Ray-tracing]]></title>
            <link>https://medium.com/@aminere/introduction-to-ray-tracing-390a986692ed?source=rss-170ddaac886e------2</link>
            <guid isPermaLink="false">https://medium.com/p/390a986692ed</guid>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[ray-tracing]]></category>
            <dc:creator><![CDATA[Amine Rehioui]]></dc:creator>
            <pubDate>Thu, 21 Mar 2019 04:53:52 GMT</pubDate>
            <atom:updated>2020-11-15T22:53:46.748Z</atom:updated>
            <content:encoded><![CDATA[<p>Ray-tracing is a graphic technique that can produce realistic images, by simulating the path of light and its interactions with the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*t_73oOnJLqP2VQsaOTIYvg.jpeg" /></figure><p>The idea is inspired by real-life: We see the world thanks to the light that originates from light sources, interacts with the environment, and ends up in our retina.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*i2DljxYrtOBq8qCs.png" /></figure><p>In practice, it’s not feasible to consider light as originating from light sources, because it would mean wasting time simulating paths that may fall outside of view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*q6vYH6zW-WpF2GJN.png" /></figure><p>A much better approach is to simulate light paths from the viewer to the light sources. This is called <strong>backward tracing. </strong>Performance-wise, it’s a win because only objects in the field of view are being processed. Visually speaking, the result can be the same since light propagation is a symmetric process, and the equations work the same in the reverse direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*v-gd4mvPz24wVCTX.png" /><figcaption>Backward tracing of light paths</figcaption></figure><p>Here is a simple implementation of this idea (in Typescript)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44c6d66e5b527c1c5e83896894696a3a/href">https://medium.com/media/44c6d66e5b527c1c5e83896894696a3a/href</a></iframe><h3>Shading</h3><p>Shading is the process of determining the color at each pixel of the resulting image. In this article, we will use a <a href="https://www.scratchapixel.com/lessons/3d-basic-rendering/introduction-to-shading/diffuse-lambertian-shading">Diffuse Shading</a> model to simulate how light is absorbed and reflected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*uXYQG8435-K-EK2p.png" /></figure><p>For each pixel, we collect the information needed for shading. Namely, the <strong>intersection</strong> <strong>point (P) </strong>between a ray projected from that pixel and the environment, the <strong>surface properties</strong> (Normal and Light direction) at that location, and the <strong>properties of light. </strong>The color is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*H85v925WPqQ-5LaE99fsfQ.png" /></figure><ul><li>d: The diffuse color at the intersection point</li><li>Li: Light intensity</li><li>Lc: Light color</li><li>θ: The angle between the Normal and the direction towards the light (Ld)</li></ul><p>Here is the resulting image, along with sample code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UIK3i_x9QCLEhPX4.jpg" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f69cb8e66f1f16cdc334a2c8aa9986bd/href">https://medium.com/media/f69cb8e66f1f16cdc334a2c8aa9986bd/href</a></iframe><h3>Reflections</h3><p>Reflections are a natural byproduct of ray-tracing. When light hits a reflective object, it changes direction and continues traveling until it either doesn’t hit anything, or the maximum amount of bounces is reached.</p><p>We refer to the reflected rays as <strong>secondary rays, </strong>in contrast with the original rays which are called <strong>primary rays</strong>. Each time a secondary ray is generated, we accumulate the color of the intersection point that created it, using the same shading equation we saw earlier. The final color at the original intersection point is simply the sum of all colors encountered while bouncing secondary rays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*DDlXz7wAxbkqjr70.png" /></figure><p>An object reflects light depending on its material properties. In this article, we define a <strong>reflectance </strong>factor on materials. Implementation-wise, the best practice is to make the ray-tracer a <strong>recursive </strong>process, so that reflected rays are processed in the exact same way as primary rays. Here is the recursive ray-tracer and the corresponding result:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8bab954ca98438f1282eaff5ef5ec5f/href">https://medium.com/media/d8bab954ca98438f1282eaff5ef5ec5f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ahpXHBQi3rDGm56.jpg" /></figure><h3>Shadows</h3><p>To support shadows, we must determine whether the intersection point at each pixel is reachable by light. If no light is accessible, it must be darkened. We introduce the concept of <strong>shadow rays. </strong>For each intersection point, we cast a ray towards each light source. If a light is not reachable, we remove its influence from the shading equation by zeroing its intensity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*v30W39yxFOItvOLU.png" /></figure><p>Here is the new implementation, taking into account shadows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23ea3ce2c6db4cd6d9be5bdc8c3af1a7/href">https://medium.com/media/23ea3ce2c6db4cd6d9be5bdc8c3af1a7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCWmBR-OQ3WKdWdd.jpg" /></figure><h3>Smooth Shadows</h3><p>Sharp shadows happened because we considered light sources as single points in space. In reality, light sources are just like any object in space, with a shape and a volume, they just happen to emit light. When shading, we must test how much of the light source is visible from each pixel of interest, and shade accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/0*f9QU0t6WUNGJELjo.png" /><figcaption>Some light samples not reachable, the point is partially shaded</figcaption></figure><p>We give light sources a non-zero volume and define a number of sample points on their area that will be used for casting additional shadow rays. The implementation is exactly the same as for sharp shadows, but since we are now casting multiple shadow rays, we must keep track of the number of occluded rays. Then we adjust the light intensity variable to the inverse ratio of occluded rays vs total rays:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*tOM2EtgDVyu0hoVwfqPYmA.png" /></figure><p>Here is the result with smooth shadows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dRNOS_h-6Fq-vxRv.jpg" /></figure><h3>Optimizations</h3><p>Most of the time spent by a ray-tracer is in computing ray-object collisions. They need to be done multiple times, for each pixel on the screen, which can be very expensive. A form of <strong>Spatial partitioning</strong> is needed to ray-trace most worlds in a decent amount of time. This deserves its own article and I will cover it in a future post!</p><p>Check out the playable demo based on this blog on <a href="https://www.spiderengine.io/project/8906059d-ae9f-4e15-aaf0-04c2c50ed1af">spiderengine.io.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=390a986692ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>