<?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 Elmehdielgarouaz on Medium]]></title>
        <description><![CDATA[Stories by Elmehdielgarouaz on Medium]]></description>
        <link>https://medium.com/@elmehdielgarouaz?source=rss-cf711372d6fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zZQM7Tvqg0-fyW6x</url>
            <title>Stories by Elmehdielgarouaz on Medium</title>
            <link>https://medium.com/@elmehdielgarouaz?source=rss-cf711372d6fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:04:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elmehdielgarouaz/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[From Flat to Fantastic: How cub3D’s Ray Casting Engine Transforms 2D into 3D]]></title>
            <link>https://medium.com/@elmehdielgarouaz/from-flat-to-fantastic-how-cub3ds-ray-casting-engine-transforms-2d-into-3d-647ff2f7fd4f?source=rss-cf711372d6fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/647ff2f7fd4f</guid>
            <dc:creator><![CDATA[Elmehdielgarouaz]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 11:24:16 GMT</pubDate>
            <atom:updated>2025-09-06T11:24:16.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lz5RlYp_1NuCNOFSasX7SA.jpeg" /></figure><p>Ray casting is one of the most elegant algorithms in computer graphics, transforming a simple 2D map into an immersive 3D world. In this article, I’ll walk you through my implementation of a ray casting engine for the cub3D project at 42 School, focusing specifically on the rendering pipeline that brings flat maps to life.</p><p>The cub3D project challenges students to create a “Wolfenstein 3D-like” game engine, and while my teammate handled the parsing components, I took ownership of the entire ray casting and rendering system. This implementation demonstrates core computer graphics concepts including geometric calculations, texture mapping, and real-time rendering optimization.</p><p>Before diving into the ray casting algorithm, let’s understand the key structures that drive our rendering engine:</p><pre>typedef struct s_game<br>{<br>    void        *mlx;<br>    void        *win;<br>    t_map       map;<br>    t_assets    asset_data;<br>    t_img       img;<br>    t_ray       rays[WINDOW_WIDTH];<br>    t_player    player;<br>}               t_game;</pre><p>The engine processes <strong>1280 rays per frame</strong> (one for each screen column), with each ray carrying essential information about wall intersections, distances, and texture coordinates.</p><h3>Understanding the Fundamentals</h3><p>Ray casting works by projecting rays from the player’s position at regular angular intervals across their field of view. Each ray travels until it hits a wall, and the distance determines the wall’s apparent height on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ZqHvBkDCTHXqXc_AU0gADQ.png" /></figure><p>Core Ray Structure</p><pre>typedef struct s_ray<br>{<br>    float   ray_angle;<br>    float   wall_hit_x;<br>    float   wall_hit_y;<br>    float   distance;<br>    bool    is_ray_facing_up;<br>    bool    is_ray_facing_down;<br>    bool    is_ray_facing_left;<br>    bool    is_ray_facing_right;<br>    bool    was_hit_vertical;<br>}           t_ray;</pre><h3>Ray Direction Determination</h3><p>The first step in casting a ray is determining its direction quadrant:</p><pre>void initiatize_rayfacing(t_game *game, float ray_angle, int i)<br>{<br>    game-&gt;rays[i].is_ray_facing_down = ray_angle &gt; 0 &amp;&amp; ray_angle &lt; PI;<br>    game-&gt;rays[i].is_ray_facing_up = !game-&gt;rays[i].is_ray_facing_down;<br>    game-&gt;rays[i].is_ray_facing_left = ray_angle &gt; (PI / 2) <br>        &amp;&amp; ray_angle &lt; (1.5 * PI);<br>    game-&gt;rays[i].is_ray_facing_right = !game-&gt;rays[i].is_ray_facing_left;<br>}</pre><p>his directional information is crucial for:</p><ul><li>Determining which grid boundaries to check</li><li>Calculating step directions</li><li>Applying proper texture coordinates</li></ul><h3>The DDA Algorithm Implementation</h3><p>The heart of our ray casting uses a <strong>Digital Differential Analyzer (DDA)</strong> approach, checking both horizontal and vertical grid line intersections separately.</p><h3>Horizontal Line Intersections</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRiMgD2MEntd5BE6lZkl0g.png" /></figure><pre>static void init_horizontal_dda(t_game *game, t_dda *dda, int i)<br>{<br>    dda-&gt;y_intercept = floor(game-&gt;player.y / TILE_SIZE) * TILE_SIZE;<br>    if (game-&gt;rays[i].is_ray_facing_down)<br>        dda-&gt;y_intercept += TILE_SIZE;<br>    <br>    dda-&gt;x_intercept = game-&gt;player.x<br>        + (dda-&gt;y_intercept - game-&gt;player.y) / tan(game-&gt;rays[i].ray_angle);<br>    <br>    dda-&gt;y_step = TILE_SIZE;<br>    if (game-&gt;rays[i].is_ray_facing_up)<br>        dda-&gt;y_step *= -1;<br>    <br>    dda-&gt;x_step = TILE_SIZE / tan(game-&gt;rays[i].ray_angle);<br>    if (game-&gt;rays[i].is_ray_facing_left &amp;&amp; dda-&gt;x_step &gt; 0)<br>        dda-&gt;x_step *= -1;<br>    if (game-&gt;rays[i].is_ray_facing_right &amp;&amp; dda-&gt;x_step &lt; 0)<br>        dda-&gt;x_step *= -1;<br>}</pre><p>Vertical Line Intersections</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSGDHj_1cCc5lFafXh3ltw.png" /></figure><pre>static void init_vertical_dda(t_game *game, t_dda *dda, int i)<br>{<br>    dda-&gt;x_intercept = floor(game-&gt;player.x / TILE_SIZE) * TILE_SIZE;<br>    if (game-&gt;rays[i].is_ray_facing_right)<br>        dda-&gt;x_intercept += TILE_SIZE;<br>    <br>    dda-&gt;y_intercept = game-&gt;player.y<br>        + (dda-&gt;x_intercept - game-&gt;player.x) * tan(game-&gt;rays[i].ray_angle);<br>    <br>    dda-&gt;x_step = TILE_SIZE;<br>    if (game-&gt;rays[i].is_ray_facing_left)<br>        dda-&gt;x_step *= -1;<br>    <br>    dda-&gt;y_step = TILE_SIZE * tan(game-&gt;rays[i].ray_angle);<br>    if (game-&gt;rays[i].is_ray_facing_up &amp;&amp; dda-&gt;y_step &gt; 0)<br>        dda-&gt;y_step *= -1;<br>    if (game-&gt;rays[i].is_ray_facing_down &amp;&amp; dda-&gt;y_step &lt; 0)<br>        dda-&gt;y_step *= -1;<br>}</pre><h3>Wall Detection and Distance Calculation</h3><p>The algorithm steps through the grid until it encounters a wall:</p><pre>static bool find_horizontal_intersection(t_game *game, int i)<br>{<br>    t_dda   dda;<br>    float   y_to_check;<br><br>    init_horizontal_dda(game, &amp;dda, i);<br>    while (dda.next_x &gt;= 0 &amp;&amp; dda.next_x &lt;= (game-&gt;map.width * TILE_SIZE)<br>        &amp;&amp; dda.next_y &gt;= 0 &amp;&amp; dda.next_y &lt;= (game-&gt;map.height * TILE_SIZE))<br>    {<br>        y_to_check = dda.next_y;<br>        if (game-&gt;rays[i].is_ray_facing_up)<br>            y_to_check -= 1;<br>        <br>        if (hit_wall(game, dda.next_x, y_to_check))<br>        {<br>            game-&gt;rays[i].horzhit_x = dda.next_x;<br>            game-&gt;rays[i].horzhit_y = dda.next_y;<br>            return (true);<br>        }<br>        dda.next_x += dda.x_step;<br>        dda.next_y += dda.y_step;<br>    }<br>    return (false);<br>}</pre><h3>3D Projection and Rendering</h3><h3>From Ray Distance to Wall Height</h3><p>Once we have the shortest ray distance, we project it onto the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owWh8Zl95nrs5jMewJqcLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-flpwIJK4AQaXJS_mBUalw.png" /></figure><pre>void render_3d_projaction(t_game *game)<br>{<br>    t_3d    t;<br>    int     i;<br><br>    t.dist_to_proj_plane = (WINDOW_WIDTH / 2) / tan(FOV / 2);<br>    i = 0;<br>    while (i &lt; WINDOW_WIDTH)<br>    {<br>        // Correct for fisheye distortion<br>        t.corrected_dist = game-&gt;rays[i].distance<br>            * cos(game-&gt;rays[i].ray_angle - game-&gt;player.rotation_angle);<br>        <br>        // Calculate projected wall height<br>        t.projected_wall_height = (TILE_SIZE / t.corrected_dist)<br>            * t.dist_to_proj_plane;<br>        <br>        // Determine wall boundaries on screen<br>        t.wall_top_pixel = (WINDOW_HEIGHT / 2) - (t.projected_wall_height / 2);<br>        t.wall_bottom_pixel = (WINDOW_HEIGHT / 2) + (t.projected_wall_height / 2);<br>        <br>        // Clamp to screen boundaries<br>        if (t.wall_top_pixel &lt; 0) t.wall_top_pixel = 0;<br>        if (t.wall_bottom_pixel &gt; WINDOW_HEIGHT) <br>            t.wall_bottom_pixel = WINDOW_HEIGHT;<br>        <br>        render_3d(game, &amp;t, i);<br>        i++;<br>    }<br>}</pre><h3>Fisheye Distortion Correction</h3><p>A critical aspect of ray casting is correcting the <strong>fisheye effect</strong>. Without correction, walls appear curved because rays at the edges of the FOV travel longer distances. The correction formula:</p><pre>t.corrected_dist = game-&gt;rays[i].distance <br>    * cos(game-&gt;rays[i].ray_angle - game-&gt;player.rotation_angle);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1CfnRPBFYoCg6CJ7mlmnQ.png" /></figure><h3>Texture Mapping Implementation</h3><h3>Texture Selection Logic</h3><p>The engine determines which texture to apply based on the wall face that was hit:</p><pre>static t_texture *get_wall_texture(t_game *game, int i)<br>{<br>    t_ray *ray = &amp;game-&gt;rays[i];<br>    <br>    if (ray-&gt;was_hit_vertical)<br>    {<br>        if (ray-&gt;is_ray_facing_right)<br>            return (&amp;game-&gt;asset_data.textures[WEST]);<br>        else<br>            return (&amp;game-&gt;asset_data.textures[EAST]);<br>    }<br>    else<br>    {<br>        if (ray-&gt;is_ray_facing_down)<br>            return (&amp;game-&gt;asset_data.textures[NORTH]);<br>        else<br>            return (&amp;game-&gt;asset_data.textures[SOUTH]);<br>    }<br>}</pre><p>Texture Coordinate Calculation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xK3mQY9qm1L5uPiyuxo2sw.jpeg" /></figure><pre>if (game-&gt;rays[i].was_hit_vertical)<br>    ws-&gt;tex_x = fmod(game-&gt;rays[i].wall_hit_y, TILE_SIZE);<br>else<br>    ws-&gt;tex_x = fmod(game-&gt;rays[i].wall_hit_x, TILE_SIZE);    <br>ws-&gt;tex_x = ws-&gt;tex_x * ((float)tex-&gt;width / TILE_SIZE);</pre><h3>Vertical Texture Sampling</h3><p>For each column of pixels, we sample the texture vertically:</p><pre>static void draw_wall_stripe(t_game *game, t_3d *t, int i)<br>{<br>    t_texture   *tex;<br>    t_ws        ws;<br>    int         y;<br><br>    tex = get_wall_texture(game, i);<br>    init_strip_cord(game, &amp;ws, i, tex);<br>    <br>    ws.y_step = (float)tex-&gt;height / t-&gt;projected_wall_height;<br>    ws.tex_pos = 0;<br>    <br>    // Handle walls taller than screen<br>    if (t-&gt;projected_wall_height &gt; WINDOW_HEIGHT)<br>        ws.tex_pos = ((t-&gt;projected_wall_height - WINDOW_HEIGHT) / 2.0) <br>            * ws.y_step;<br>    <br>    y = t-&gt;wall_top_pixel;<br>    while (y &lt; t-&gt;wall_bottom_pixel)<br>    {<br>        ws.tex_y = (int)ws.tex_pos;<br>        boundaries(&amp;ws, tex);<br>        <br>        ws.color = *(unsigned int *)(tex-&gt;addr + (ws.tex_y * tex-&gt;line_len<br>                    + ws.tex_x * (tex-&gt;bpp / 8)));<br>        <br>        my_mlx_pixel_put(game, i, y, ws.color);<br>        ws.tex_pos += ws.y_step;<br>        y++;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gmbvXeqmWX2seobIPwxv3Q.gif" /></figure><h3>Player Movement and Real-Time Updates</h3><h3>Movement System</h3><p>The player can move forward/backward and strafe left/right:</p><pre>void update_player(t_game *game)<br>{<br>    // Rotation<br>    game-&gt;player.rotation_angle += game-&gt;player.turn_direction<br>        * game-&gt;player.rotation_speed;<br>    game-&gt;player.rotation_angle = normalize_angle(game-&gt;player.rotation_angle);<br>    <br>    // Forward/backward movement<br>    float move_step = game-&gt;player.walk_direction * game-&gt;player.move_speed;<br>    float move_x = cos(game-&gt;player.rotation_angle) * move_step;<br>    float move_y = sin(game-&gt;player.rotation_angle) * move_step;<br>    <br>    // Strafing movement<br>    float strafe_angle = game-&gt;player.rotation_angle + (PI / 2);<br>    float strafe_step = game-&gt;player.strafe_direction * game-&gt;player.move_speed;<br>    float strafe_x = cos(strafe_angle) * strafe_step;<br>    float strafe_y = sin(strafe_angle) * strafe_step;<br>    <br>    // Collision detection<br>    float new_x = game-&gt;player.x + move_x + strafe_x;<br>    if (!hit_wall(game, new_x, game-&gt;player.y))<br>        game-&gt;player.x = new_x;<br>    <br>    float new_y = game-&gt;player.y + move_y + strafe_y;<br>    if (!hit_wall(game, game-&gt;player.x, new_y))<br>        game-&gt;player.y = new_y;<br>}</pre><p>Collision Detection</p><pre>bool hit_wall(t_game *game, float x, float y)<br>{<br>    int map_x, map_y;<br><br>    // Boundary checks<br>    if (x &lt; 0 || x &gt;= (game-&gt;map.width * TILE_SIZE)<br>        || y &lt; 0 || y &gt;= (game-&gt;map.height * TILE_SIZE))<br>        return (true);<br>    <br>    // Convert to grid coordinates<br>    map_x = floor(x / TILE_SIZE);<br>    map_y = floor(y / TILE_SIZE);<br>    <br>    if (map_x &lt; 0 || map_x &gt;= game-&gt;map.width<br>        || map_y &lt; 0 || map_y &gt;= game-&gt;map.height)<br>        return (true);<br>    <br>    return (game-&gt;map.grid[map_y][map_x] == &#39;1&#39;);<br>}</pre><h3>Performance Optimization Techniques</h3><h3>1. Efficient Ray Casting Loop</h3><p>Instead of casting rays individually, our main loop processes all rays in a single pass:</p><pre>void cast_rays(t_game *game)<br>{<br>    float ray_angle = game-&gt;player.rotation_angle - (FOV / 2);<br>    int num_rays = WINDOW_WIDTH;<br>    <br>    for (int i = 0; i &lt; num_rays; i++)<br>    {<br>        game-&gt;rays[i].ray_angle = ray_angle;<br>        cast_one_ray(game, i);<br>        ray_angle += FOV / num_rays;<br>    }<br>}</pre><h3>2. Boundary Clamping</h3><p>Texture coordinates are clamped to prevent memory access violations:</p><pre>static void boundaries(t_ws *ws, t_texture *tex)<br>{<br>    if (ws-&gt;tex_x &lt; 0) ws-&gt;tex_x = 0;<br>    if (ws-&gt;tex_x &gt;= tex-&gt;width) ws-&gt;tex_x = tex-&gt;width - 1;<br>    if (ws-&gt;tex_y &lt; 0) ws-&gt;tex_y = 0;<br>    if (ws-&gt;tex_y &gt;= tex-&gt;height) ws-&gt;tex_y = tex-&gt;height - 1;<br>}</pre><h3>3. Early Distance Comparison</h3><p>We use large sentinel values for missed intersections to simplify distance comparison logic:</p><pre>float horz_hit_distance = 1e30;<br>float vert_hit_distance = 1e30;</pre><h3>Rendering Pipeline Integration</h3><h3>The Complete Frame Rendering Process</h3><pre>void ft_render(t_game *game)<br>{<br>    mlx_clear_window(game-&gt;mlx, game-&gt;win);<br>    update_player(game);           // Handle input and movement<br>    cast_rays(game);              // Calculate all ray intersections<br>    render_3d_projaction(game);   // Project and draw 3D view<br>    mlx_put_image_to_window(game-&gt;mlx, game-&gt;win, game-&gt;img.img_ptr, 0, 0);<br>}</pre><p>Technical Challenges and Solutions</p><p>Challenge 1: Angle Normalization</p><p>Problem: Ray angles can exceed 2π or become negative, causing incorrect calculations.</p><p>Solution: Implement robust angle normalization:</p><pre>float normalize_angle(float angle)<br>{<br>    angle = fmod(angle, (2 * PI));<br>    if (angle &lt; 0)<br>        angle = angle + (2 * PI);<br>    return (angle);<br>}</pre><p>Challenge 2: Wall Gap Detection</p><p>Problem: Rays might pass through wall corners due to grid sampling.</p><p>Solution: Offset checking points slightly inward:</p><pre>if (game-&gt;rays[i].is_ray_facing_up)<br>    y_to_check -= 1;<br>if (game-&gt;rays[i].is_ray_facing_left)<br>    x_to_check -= 1;</pre><h3>Key Learnings and Takeaways</h3><p>Building this ray casting engine taught me several fundamental concepts:</p><ol><li><strong>Geometric Algorithms</strong>: Understanding how mathematical concepts translate to practical rendering</li><li><strong>Performance Optimization</strong>: Balancing visual quality with real-time constraints</li><li><strong>Memory Management</strong>: Handling graphics resources efficiently</li><li><strong>Debugging Graphics</strong>: Visualizing mathematical problems in geometric space</li></ol><h3>Future Enhancements</h3><p>While the current implementation is fully functional, potential improvements include:</p><ul><li><strong>Sprite Rendering</strong>: Adding enemy and object sprites</li><li><strong>Advanced Lighting</strong>: Implementing distance-based shading</li><li><strong>Texture Filtering</strong>: Reducing pixelation with interpolation</li><li><strong>Multi-height Walls</strong>: Supporting variable wall heights</li><li><strong>Performance Profiling</strong>: Optimizing the hot paths further</li></ul><h3>Conclusion</h3><p>Ray casting remains one of the most educational graphics programming exercises because it demonstrates core principles without overwhelming complexity. This implementation processes over 76,000 rays per second while maintaining smooth 60 FPS gameplay, proving that well-optimized algorithms can achieve impressive results even with seemingly brute-force approaches.</p><p>The complete source code showcases practical application of trigonometry, coordinate system transformations, texture mapping, and real-time optimization techniques. Most importantly, it transforms abstract mathematical concepts into an interactive 3D world that players can explore.</p><p>Building cub3D’s rendering engine was both challenging and rewarding, providing deep insights into how modern game engines work under the hood, even as they’ve evolved far beyond these foundational techniques.</p><p><em>This article focuses specifically on the ray casting and rendering components of the cub3D project. The parsing and validation components were implemented by my project partner and are covered separately.</em></p><h3>References</h3><ul><li><a href="https://medium.com/@abdelhadi-salah/ray-casting-cub3d-bb5d99de742d">https://medium.com/@abdelhadi-salah/ray-casting-cub3d-bb5d99de742d</a></li><li><a href="https://lodev.org/cgtutor/raycasting.html">https://lodev.org/cgtutor/raycasting.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=647ff2f7fd4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>