<?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 Udit Karode on Medium]]></title>
        <description><![CDATA[Stories by Udit Karode on Medium]]></description>
        <link>https://medium.com/@uditkarode?source=rss-33c451913a5f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*U3cwi0O2zs4u4Af1RUGV7A.jpeg</url>
            <title>Stories by Udit Karode on Medium</title>
            <link>https://medium.com/@uditkarode?source=rss-33c451913a5f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:56:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uditkarode/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[Writing a Game Engine in Rust — I]]></title>
            <link>https://medium.com/goalist-blog/writing-a-game-engine-in-rust-i-f4f2cdeb5d71?source=rss-33c451913a5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f2cdeb5d71</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[game-engine]]></category>
            <dc:creator><![CDATA[Udit Karode]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 02:46:55 GMT</pubDate>
            <atom:updated>2023-10-02T02:46:55.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing a Game Engine in Rust — I</h3><p>Computer games have been a part of our lives since quite a while, with many of them being a crucial part of our childhood memories. Let’s try and whip up a fairly simple game engine and make our very own game — <strong><em>a bouncy ball that can be controlled with the keyboard</em></strong>!</p><p>This won’t hold so much as a candle to any of the modern game engines, but it’ll hopefully be good enough for what we’re going to be doing with it — making simple pixel games.</p><h3>Creating a Window</h3><p>The first thing a game does when you launch it is opening a window, which is what we’ll also do first. Since we’re using Rust, we can use a super handy library called <a href="https://github.com/emoon/rust_minifb">minifb</a>, which gives us a window, a way to react to keyboard events, as well as a super simple way to manipulate the contents of the window — a Vec of all the pixels that, when we assign a color value to, is reflected respectfully in the window.</p><pre>use minifb::{Key, Window, WindowOptions};<br><br>const WIDTH: usize = 640;<br>const HEIGHT: usize = 360;<br><br>fn main() {<br>    let mut buffer: Vec&lt;u32&gt; = vec![0; WIDTH * HEIGHT];<br><br>    let mut window = Window::new(<br>        &quot;Test Window Title&quot;,<br>        WIDTH,<br>        HEIGHT,<br>        WindowOptions::default(),<br>    ).unwrap();<br><br>    while window.is_open() {<br>        for i in buffer.iter_mut() {<br>            // set all pixels to black<br>            *i = 0;<br>        }<br>        <br>        for i in 20000..40000 {<br>            // set the pixels from 20000 to 40000 to red<br>            buffer[i] = 0xf44336;<br>        }<br><br>        window<br>            .update_with_buffer(&amp;buffer, WIDTH, HEIGHT)<br>            .unwrap();<br>    }<br>}</pre><p>This gives us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rDFQ2aXP4TjqciLd.png" /></figure><p>This is a great way to create a window and manipulate it’s contents because it gives us a lot of power in just a few lines of code, and interacting with it is super simple! Now that we have a window, we can move ahead.</p><h3>Laying the foundations</h3><p>Now is a great time to think about how we want the engine APIs to look like. But for that, we need a barebones engine first, so let’s implement that.</p><p>Two things we’ll need in this game are the <em>Engine</em> and <em>Game Objects</em>. The engine itself manages the window and rendering and global effects, while the game objects are ‘things’ in the game, such as the bouncy ball we want to add to our game.</p><p>The engine needs to know what game objects exist in the game, and needs have the capability to add game objects to the game. It also needs to do the following on the game objects:</p><ul><li>Apply global effects like gravity, air drag, or ground drag</li><li>Perform collision detection and decide what happens when a game object collides with another</li><li>Decide whether a game object is moving, and update it’s coordinates accordingly if it is</li></ul><pre>#[derive(Clone)]<br>pub struct WindowSize {<br>    pub height: usize,<br>    pub width: usize,<br>}<br><br>pub struct Engine {<br>    window: Option&lt;Window&gt;,<br>    buffer: Vec&lt;u32&gt;,<br>    window_size: WindowSize,<br>    objects: Vec&lt;Box&lt;dyn GameObject&gt;&gt;,<br>}</pre><p>Looks reasonable — for a game engine, we need a minifb Window <em>(so that we can perform input handling and the like)</em>, the buffer associated with that window <em>(so that we can render things)</em>, the size of the window <em>(required when rendering things, for collision detection and the like)</em>, and a vector of game objects <em>(to know what to render and how).</em></p><p>Now we have a good grasp over what the Engine is meant to be able to do. We’ll explore the implementations on it in a while, but let’s talk about game objects first.</p><pre>pub trait GameObject {<br>    fn common(&amp;mut self) -&gt; &amp;mut GameObjectCommon;<br><br>    fn weight_factor(&amp;self) -&gt; f64;<br><br>    fn bounciness(&amp;self) -&gt; f64 {<br>        DEFAULT_COLLISION_DAMPING_FACTOR<br>    }<br><br>    fn collision_shape(&amp;self) -&gt; CollisionShape;<br><br>    fn draw(&amp;self) -&gt; Vec&lt;Vec&lt;u32&gt;&gt;;<br><br>    fn handle_input(&amp;mut self, _keys: &amp;[Key]) {}<br>}</pre><p>There’s a lot going on here. Let’s go through it one by one. First of all, GameObject is a trait – this means that any struct can implement our trait to also become a GameObject. Here’s a small explanation of all the functions in this trait:</p><h4><strong>Weight Factor and Bounciness</strong></h4><p>There’s two things that are easily explainable — the weight_factor and the bounciness.</p><ul><li>weight_factor – when things fall down in real life, how quick they fall depends on their weight. An anvil will fall down much faster than a feather, for example. The weight factor is just the factor by which the fall rate will be modified, so it could be 3.0 for an anvil and 0.2 for a feather.</li><li>bounciness – when something collides with another thing, it&#39;s &#39;bounciness&#39; determines what happens <em>(there might be many factors involved in actual physics, but let&#39;s keep things ultra simple for now). </em>For example, when a ball collides with the ground, it&#39;s propelled back up with just a little bit of it&#39;s velocity lost, but when I fall to the ground,<em> </em>I <em>(unfortunately) </em>won&#39;t bounce back<em>. </em>Hence, the bounciness of a person could be 0, and that of a ball could be 0.9.</li></ul><h4>Common</h4><pre>#[derive(Clone, Default)]<br>pub struct XYPair {<br>    pub x: f64,<br>    pub y: f64,<br>}<br><br>#[derive(Default)]<br>pub struct GameObjectCommon {<br>    pub coords: XYPair,<br>    pub velocities: XYPair,<br>    pub object_info: Option&lt;ObjectInfo&gt;,<br>}</pre><p>Since each GameObject will have a couple of common properties like the coordinates of the object and the velocities of the object on either axis, we can put them in a separate struct and have an instance of that here, since we can&#39;t have fields in the trait itself.</p><h4>Object Info</h4><p>object_info here is just information about the object that the engine sets every frame. This is how it&#39;s defined:</p><pre>#[derive(Clone)]<br>pub struct ObjectInfo {<br>    // in case we want to support window resizing in the<br>    // future, the objects might want to know the size.<br>    // this is however a bad example, because it doesn&#39;t<br>    // need to be set per game object, so let&#39;s fix that in part 2<br>    pub window_size: WindowSize,<br>}</pre><h4>Draw</h4><p>This is pretty straightforward — it’s a Vec of Vec of pixel colors to denote how the GameObject is to be drawn/rendered.</p><pre>[<br>    [0,0,1,0,0],<br>    [0,1,1,1,0],<br>    [1,1,1,1,1],<br>    [0,1,1,1,0],<br>    [0,0,1,0,0],<br>]</pre><h4>Collision Shape</h4><pre>pub enum CollisionShape {<br>    Circle(f64),<br>}</pre><p>The collision shape is just the collision box — the shape that collides with the window; we’ll use this later for collision with other game objects as well. This is imperative to have in our case because we’re representing game object graphics with a Vec&lt;Vec&lt;u32&gt;&gt;, which means the only representable shape is a quadrilateral. For example, we can draw a circle for our ball, but the pixels for the area around the edges will still exist, and hence we can&#39;t use that as the basis for our collision box. This is why we need a collision shape to be defined, so custom logic can be used for collision detection.</p><p>Handle Input</p><p>This function is also pretty straightforward. Every frame, it provides to the GameObject what keys have been pressed on the keyboard, and allows it to perform any actions it wants to using that information.</p><h3>Creating our Game Object</h3><p>Now that we know what game objects look like, we can get started with creating the game object for the ball in our bouncy ball game.</p><pre>pub struct Ball {<br>    radius: f64,<br>    diameter: f64,<br>    color: u32,<br><br>    common: GameObjectCommon,<br>}<br><br>impl Ball {<br>    pub fn new(coords: XYPair, radius: f64, color_hex: &amp;str) -&gt; Self {<br>        let diameter = radius * 2.0;<br>        <br>        // convert hex color to u32, or default to white<br>        let color = from_str_radix(&amp;color_hex[1..], 16).unwrap_or(0xFFFFFF);<br><br>        let common = GameObjectCommon {<br>            coords,<br>            ..GameObjectCommon::default()<br>        };<br><br>        Self {<br>            color,<br>            radius,<br>            diameter,<br><br>            common,<br>        }<br>    }<br>}</pre><p>Nothing too special worth mentioning here; we just create the Ball struct and create a constructor for it. Let&#39;s now move forward while implementing everything we need to for the GameObject trait:</p><h4>Common</h4><p>This is extremely simple since we can just use the default function provided by the Default derived trait.</p><pre>fn common(&amp;mut self) -&gt; &amp;mut GameObjectCommon {<br>    &amp;mut self.common<br>}</pre><h4>Weight Factor and Bounciness</h4><p>Since this is a ball, it’s light and bouncy. Let’s set the weight factor and bounciness accordingly.</p><pre>fn weight_factor(&amp;self) -&gt; f64 {<br>    0.8<br>}<br><br>fn bounciness(&amp;self) -&gt; f64 {<br>    0.6<br>}</pre><h4>Collision Shape</h4><p>This is a ball, and balls are round <em>(surprise!)</em>.</p><pre>fn collision_shape(&amp;self) -&gt; CollisionShape {<br>    CollisionShape::Circle(self.radius)<br>}</pre><h4>Handle Input</h4><p>Let’s make the ball move when left or right when A or D are pressed respectively. We’ll also make the ball jump when we’re firmly seated on the ground. Moving and jumping are as simple as adding or subtracting a certain value from the velocities.</p><pre>const KB_X_BOOST: f64 = 0.2;<br>const KB_Y_BOOST: f64 = 16.0;<br><br>fn handle_input(&amp;mut self, keys: &amp;[Key]) {<br>    if keys.contains(&amp;Key::A) {<br>        self.common.velocities.x -= KB_X_BOOST;<br>    }<br><br>    if keys.contains(&amp;Key::D) {<br>        self.common.velocities.x += KB_X_BOOST;<br>    }<br><br>    // jump if we are on the ground AND have 0 or lesser y velocity<br>    if keys.contains(&amp;Key::W) {<br>        if let Some(info) = &amp;self.common.object_info {<br>            let window_height = info.window_size.height as f64;<br>            if self.common.velocities.y &lt; 0.0<br>                &amp;&amp; self.common.coords.y + self.diameter == window_height<br>            {<br>                self.common.velocities.y -= KB_Y_BOOST;<br>            }<br>        }<br>    }<br>}</pre><h4>Draw</h4><p>This is a crucial aspect of the game object.</p><pre>fn draw(&amp;self) -&gt; Vec&lt;Vec&lt;u32&gt;&gt; {<br>        let mut raster = vec![<br>         vec![<br>             0; self.diameter as usize<br>            ]; self.diameter as usize<br>        ];<br>        <br>        let h = self.radius;<br>        let k = self.radius;<br><br>        for y in 0..self.diameter as usize {<br>            for x in 0..self.diameter as usize {<br>                let dx = (x as f64 - h).abs();<br>                let dy = (y as f64 - k).abs();<br>                if (dx * dx + dy * dy).sqrt() &lt;= self.radius {<br>                    raster[y][x] = self.color;<br>                }<br>            }<br>        }<br><br>        raster<br>}</pre><p>First, we create a Vec&lt;Vec&lt;u32&gt;&gt;, which is just a vec of rows of pixels that form our GameObject. This effectively means that every GameObject must be a quadrilateral, but we can just draw the outer parts of our ball, with the black color for now, so that it effectively merges with the background.</p><p>Next, we use a bit of math. Since our rendering starts at the 0th pixel of the 0th row, the coords of the center of the circle will be (radius, radius). Next, we go over every pixel in our raster array, and calculate it&#39;s distance from the center of the circle using the Pythagoras theorem. If the distance is lesser than or equal to the radius, this pixel is to be included in the circle, and so we set it to the color we want the ball to be. Not that hard after all!</p><h3>Engine Internals</h3><p>Now that we’ve created the GameObject for our bouncy ball and know what the Engine struct looks like, let’s have a look at how the Engine functions internally. Here’s the Engine struct once again:</p><pre>pub struct Engine {<br>    window: Option&lt;Window&gt;,<br>    buffer: Vec&lt;u32&gt;,<br>    window_size: WindowSize,<br>    objects: Vec&lt;Box&lt;dyn GameObject&gt;&gt;,<br>}</pre><h4>Public functions (excluding the game loop runner)</h4><pre>// public functions<br>impl Engine {<br>    pub fn new(window_size: &amp;WindowSize) -&gt; Result&lt;Self, anyhow::Error&gt; {<br>        Ok(Self {<br>            buffer: vec![0; window_size.width * window_size.height],<br>            window: None,<br>            window_size: window_size.clone(),<br>            objects: Vec::new(),<br>        })<br>    }<br><br>    pub fn add_game_object(&amp;mut self, game_object: impl GameObject + &#39;static) {<br>        self.objects.push(Box::new(game_object))<br>    }<br>}</pre><p>We’ve got two fairly simple functions here:</p><ul><li>new – instantiates a new Engine with a black buffer, no window, a window size from the params, and an empty vec for objects.</li><li>add_game_object – simply appends the provided game_object to self.objects. Here, game_object is anything that implements the trait GameObject.</li></ul><h4>Internal functions</h4><p>There are several here, so let’s go over them one by one:</p><pre>fn calc_velocities(object: &amp;mut Box&lt;dyn GameObject&gt;) {<br>    let mut velocities = object.common().velocities.clone();<br><br>    // apply gravity<br>    let gravity = GRAVITY * object.weight_factor() * DT;<br>    velocities.y += gravity;<br><br>    // apply air drag<br>    velocities.x *= 1.0 - (AIR_RESISTANCE_FACTOR * DT);<br>    velocities.y *= 1.0 - (AIR_RESISTANCE_FACTOR * DT);<br><br>    object.common().velocities = velocities;<br>}</pre><p>This function will be run every frame. What is does is not very complex — it takes the velocities of the object, applies gravity and air drag to them. Here, we’re using DT, but it’s not very useful since DT is hardcoded. It’s meant to negate the effects of having varying fps on the physics, and we’ll probably get around to doing it properly later.</p><pre>fn apply_velocities(object: &amp;mut Box&lt;dyn GameObject&gt;) {<br>    let common = object.common();<br>    let coords = common.coords.clone();<br>    let velocities = common.velocities.clone();<br><br>    object.common().coords = XYPair {<br>        x: coords.x + velocities.x,<br>        y: coords.y + velocities.y,<br>    };<br>}</pre><p>This function is also not very complex. All it does is apply the velocities to the coordinates of the game object for that specific frame. Every object moves velocities.x in the x direction, and velocities.y in the y direction.</p><pre>fn update_object_info(window_size: &amp;WindowSize, object: &amp;mut Box&lt;dyn GameObject&gt;) {<br>    object.common().object_info = Some(ObjectInfo {<br>        window_size: window_size.clone(),<br>    });<br>}</pre><p>This function updates ObjectInfo for some game object. We&#39;ll use it to update it for all the objects, and have something meaningful in it later on.</p><pre>fn draw(buffer: &amp;mut Vec&lt;u32&gt;, window_size: &amp;WindowSize, object: &amp;mut Box&lt;dyn GameObject&gt;) {<br>    let raster_vecs = object.draw();<br><br>    let common = object.common();<br>    let coords = &amp;common.coords;<br><br>    Engine::draw_at(<br>        buffer,<br>        window_size.width,<br>        window_size.height,<br>        raster_vecs,<br>        coords,<br>    );<br>}</pre><p>This function renders a game object at it’s supposed coords. It uses the Engine::draw_at internal util, which we&#39;ll have a look at in a while.</p><pre>fn collision_checks(window_size: &amp;WindowSize, object: &amp;mut Box&lt;dyn GameObject&gt;) {<br>    match object.collision_shape() {<br>        CollisionShape::Circle(radius) =&gt; {<br>            let mut coords = object.common().coords.clone();<br>            let mut velocities = object.common().velocities.clone();<br>            let diameter = 2.0 * radius;<br><br>            let on_ground = if coords.y + diameter &gt;= window_size.height as f64 {<br>                true<br>            } else {<br>                false<br>            };<br><br>            let on_x_collision =<br>                |velocities: &amp;mut XYPair| velocities.x = -velocities.x * object.bounciness();<br><br>            let on_y_collision = |velocities: &amp;mut XYPair| {<br>                velocities.y = -velocities.y * object.bounciness();<br><br>                // if we&#39;re just rolling on the ground, apply ground drag<br>                if on_ground &amp;&amp; velocities.y.abs() &lt;= 1.0 {<br>                    velocities.x -= velocities.x * GROUND_DRAG_FACTOR<br>                }<br>            };<br><br>            // x axis window collision<br>            if coords.x &lt;= 0.0 {<br>                coords.x = 0.0;<br>                on_x_collision(&amp;mut velocities);<br>            }<br>            if coords.x + diameter &gt; window_size.width as f64 {<br>                coords.x = window_size.width as f64 - diameter;<br>                on_x_collision(&amp;mut velocities);<br>            }<br><br>            // y axis window collision<br>            if coords.y - diameter &lt; 0.0 {<br>                coords.y = diameter;<br>                on_y_collision(&amp;mut velocities);<br>            }<br>            if coords.y + diameter &gt; window_size.height as f64 {<br>                coords.y = window_size.height as f64 - diameter;<br>                on_y_collision(&amp;mut velocities);<br>            }<br><br>            object.common().coords = coords;<br>            object.common().velocities = velocities;<br>        }<br>    }<br>}</pre><p>Now this is a chonky function. It performs collision checks on a game object, and deals with what happens after a collision. Currently, we only check for collisions with the window borders, which is surprisingly simple to do.</p><p>Since collision logic is based on the shape of the game object, we add a check for object.collision_shape(), but since we only have one supported collision shape right now, that makes things simple for us.</p><p>Checking for a collision is simple:</p><ul><li>X axis — if coords.x is less than 0 <em>(the left edge of the circle is outside the left edge of the window)</em> or coords.x + diameter is greater than window_size.width <em>(the right edge of the circle is outside the right edge of the window)</em></li><li>Y axis — if coords.y - diameter is less than 0 <em>(the top edge of the circle is outside the top edge of the window)</em> or coords.y + diameter is greater than window_size.height <em>(the bottom edge of the circle is outside the bottom edge of the window)</em></li></ul><p>Once we detect a collision, we first snap the circle back to the closest edge. Then, we reverse the direction of it’s velocity, so something falling toward the ground will now have velocity in the other direction and be propelled up. Next, we multiply the velocity of the object with the object bounciness. A value of 1 or above will simply not work here, since that&#39;ll cause the ball to infinitely jump from ground to ceiling and possibly keep accelerating. However, values less than 1 apply a dampening effect, which is what we want.</p><p>In case there’s a y collision at the bottom edge and the velocity on the y axis is minimal, we also apply ground drag. This is because any object that moves while rubbing against the ground will face friction and hence be slower.</p><p>That concludes the collision detection and reaction!</p><h4>Internal Utils</h4><pre>fn draw_at(<br>    buffer: &amp;mut Vec&lt;u32&gt;,<br>    buffer_width: usize,<br>    buffer_height: usize,<br>    raster_vecs: Vec&lt;Vec&lt;u32&gt;&gt;,<br>    coords: &amp;XYPair,<br>) {<br>    let object_width = raster_vecs.iter().map(|row| row.len()).max().unwrap_or(0);<br><br>    for (dy, row) in raster_vecs.iter().enumerate() {<br>        for dx in 0..object_width {<br>            let x = (coords.x + dx as f64) as usize;<br>            let y = (coords.y + dy as f64) as usize;<br><br>            // make sure this is not out of the buffer<br>            if x &lt; buffer_width &amp;&amp; y &lt; buffer_height {<br>                let index = y * buffer_width + x;<br><br>                let maybe_pixel = row.get(dx).cloned();<br>                if let Some(pixel) = maybe_pixel {<br>                    buffer[index] = pixel;<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Let’s now have a look at the draw_at function we referenced earlier. This function draws our Vec&lt;Vec&lt;u32&gt;&gt; which we use for convenience on the singular Vec&lt;u32&gt; rust_minifb buffer.</p><p>First, we calculate the object width, which is the longest row. Now, for each pixel in raster_vecs, its corresponding position in buffer is calculated based on coords. If the resultant position does exist inside the range of the buffer, we obtain the index the pixel should be at, and set it there. This is definitely a little confusing, but reading it a few times should help.</p><h4>Game Loop Runner</h4><pre>pub fn run(&amp;mut self, window_title: &amp;str) -&gt; Result&lt;(), anyhow::Error&gt; {<br>    self.window = Some(Window::new(<br>        window_title,<br>        self.window_size.width,<br>        self.window_size.height,<br>        WindowOptions {<br>            scale_mode: ScaleMode::AspectRatioStretch,<br>            ..WindowOptions::default()<br>        },<br>    )?);<br><br>    let duration_per_frame = std::time::Duration::from_secs(1) / FPS.try_into()?;<br>    self.window<br>        .as_mut()<br>        .unwrap()<br>        .limit_update_rate(Some(duration_per_frame));<br><br>    while self.window.as_ref().unwrap().is_open()<br>        &amp;&amp; !self.window.as_ref().unwrap().is_key_down(Key::Escape)<br>    {<br>        let keys = self.window.as_ref().unwrap().get_keys();<br><br>        // clear the display buffer<br>        self.buffer.iter_mut().for_each(|p| *p = 0);<br><br>        for object in self.objects.iter_mut() {<br>            // re-calculate the velocities of the object<br>            Engine::calc_velocities(object);<br><br>            // apply the velocities to the coordinates<br>            Engine::apply_velocities(object);<br><br>            // perform collision checks with the window<br>            Engine::collision_checks(&amp;self.window_size, object);<br><br>            // update the game object&#39;s info<br>            Engine::update_object_info(&amp;self.window_size, object);<br><br>            // allow the object to react to pressed keys<br>            object.handle_input(&amp;keys);<br><br>            // draw the object on the buffer at it&#39;s coords<br>            Engine::draw(&amp;mut self.buffer, &amp;self.window_size, object);<br>        }<br><br>        // reflect the display buffer changes<br>        self.window.as_mut().unwrap().update_with_buffer(<br>            &amp;self.buffer,<br>            self.window_size.width,<br>            self.window_size.height,<br>        )?;<br>    }<br><br>    Ok(())<br>}</pre><p>This is the primary function of the engine that runs the game loop and calls our internal functions on the game objects every frame.</p><p>First, we create a window and assign it to self.window. Next, we calculate the duration we want each frame to take, and limit the window update rate using limit_update_rate.</p><p>Now begins the game loop. First we get all the keys that have been pressed this frame, and clear the buffer, setting each pixel to black.</p><p>Then, until the window is open and the escape key is not pressed, we perform a series of actions on the each game object, which I think is easy enough to understand from just the code, since we already discussed the internal functions used previously.</p><p>Finally, at the end of the game loop, we replace the window buffer with the calculated buffer after drawing all our game objects, and the loop goes on!</p><h3>Main function</h3><p>Time for the last piece of the puzzle to get our game to run — the main function. This is fairly simple.</p><pre>fn main() -&gt; Result&lt;(), anyhow::Error&gt; {<br>  let window_size = WindowSize {width: 800, height: 600};<br>  let mut engine = Engine::new(&amp;window_size)?;<br>  <br>  let radius = 24.0;<br>  let ball_coords = XYPair {<br>    x: (&amp;window_size.width / 2) as f64 - radius,<br>    y: (&amp;window_size.height / 2) as f64 - radius,<br>  };<br>  let ball = Ball::new(ball_coords, radius, &quot;#cf5353&quot;);<br><br>  engine.add_game_object(ball);<br>  engine.run(&quot;Bouncy Ball&quot;)<br>}</pre><p>All we do is create an Engine, create a Ball, add the ball to the engine, and run the engine. That gives us a very satisfying tiny &quot;game&quot; where we can control a bouncy ball on screen with our keyboard that collides with the window walls and bounces around!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*rVjqMyq2l6mPNxJ91-R9AA.gif" /><figcaption>“gameplay”! (reduced motion due to this being a gif)</figcaption></figure><p>If you want to try this yourself, feel free to have a look at the code here:</p><p><a href="https://github.com/uditkarode/rust_game_engine">GitHub - uditkarode/rust_game_engine</a></p><p>Just clone this and run cargo run --release, and assuming you have cargo installed, you’re set!</p><p>Hopefully I’ll continue improving this until it can make some bigger games; but for now, adios!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f2cdeb5d71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/writing-a-game-engine-in-rust-i-f4f2cdeb5d71">Writing a Game Engine in Rust — I</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchrony, Concurrency, and Parallelism]]></title>
            <link>https://medium.com/goalist-blog/asynchrony-concurrency-and-parallelism-309377e847bc?source=rss-33c451913a5f------2</link>
            <guid isPermaLink="false">https://medium.com/p/309377e847bc</guid>
            <category><![CDATA[parallelism]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Udit Karode]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 03:53:11 GMT</pubDate>
            <atom:updated>2023-08-02T03:53:11.402Z</atom:updated>
            <content:encoded><![CDATA[<p>With how often these words are used, async likely being the most common of the three, it&#39;s common to get confused on what their real meanings are. It&#39;s also usually unclear how async relates to multithreading, or whether it does at all, so let&#39;s talk about it!</p><h3>Prologue</h3><p>There is a pressing need to make one thing clear — threads are not a hardware concept. They exist purely in the kernel. On the hardware level, you only have CPU cores. CPU cores contain the actual chips that are able to perform calculations and run instructions, whereas threads are like an isolated set of instructions that are needed to be run (along with data from when they were last preempted/paused so that they can be safely resumed).</p><p>Although it is an oversimplification, you can think of threads like an array of instructions that need to be run, something like [&quot;const a = 5;&quot;, &quot;a += 1;&quot;, &quot;a /= 5;&quot;], but in machine code.</p><p>Threads need to be <strong>run</strong> on a CPU core for them to proceed toward completion. For simplicity, let’s think of it in terms of percentages. Each thread has a progress (like 20% complete) and state from when it was last paused. Threads can be executing instructions on the execution units, or waiting for I/O or memory fetches to complete.</p><p>Since it is possible to have more threads than the number of CPU cores, the OS needs to do some “thread management”, so to speak, in order to make sure they all progress and none of them is stuck. This is done via scheduling.</p><p>Scheduling refers to passing control around threads when required in a way such that none of the threads are starved/stuck. Let’s talk more about this later, and for now proceed to the main topics of this blog.</p><h3>Async</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbkUUZXI8-SxMOT99O3C1Q.png" /></figure><p>Async, Asynchronicity, or Asynchrony, is inherently a simple concept. All it means is that you do not necessarily have to wait for one action or line of code to complete executing before moving on to the next task/action/line.</p><p>The most common example of this, and one that we as developers likely use everyday, is waiting “asynchronously” for a network request, file read, or any other kind of I/O. This lets other things, such as rendering of the UI for example, happen while you wait for the result.</p><p>Now for the question of whether or not it is multi-threaded — it depends. Let’s talk about syscalls for a little bit to understand this. Syscalls are a way for your program to talk to the kernel and ask for something, for example, the contents of a file on the disk. Syscalls are required because there are several system resources that programs are unable to directly interact with because they are not allowed to. There exist blocking and non-blocking syscalls, where blocking syscalls block the thread until the result is ready. When this happens, the thread does not get any CPU time until the blocking syscall finishes. With non-blocking IO, the syscall returns immediately without blocking the thread. The IO is still in progress, and the kernel takes care of that. In the context of NodeJS, for example, in the poll phase of the event loop, it checks if any of the IO it started has finished, and if it has, calls the respective callback. For any IO that has not finished, it continues progressing without blocking the thread.</p><p>In most cases, if a program can use non-blocking syscalls to do something, that is what it will do. NodeJS is able to use libuv to spawn worker threads to perform operations that do not have system level non-blocking syscalls, such as DNS queries.</p><p>Non-blocking syscalls are preferred over blocking syscalls because spawning new threads for every file read or network wait, for example, can quickly result in a lot of threads being spawned, which as we’ll see later on, is not good for performance.</p><h3>Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85yF-l0ybY5sYalcoQbIjw.png" /></figure><p>Concurrency refers to a situation where two or more things are in progress, but not necessarily progressing at the same point in time. Sounds familiar? This is because we did this in Asynchrony. When we proceed to Thing 2 while waiting for Thing 1 to finish, we are indeed making progress in two different tasks. This means that asynchrony implies concurrency. Simple as that!</p><p>The difference between asynchrony and concurrency is that with asynchrony, the reason you might do two things at a time is because one of them is performing a slow operation which you do not want to block the thread for, whereas concurrency is about doing multiple things at once because that’s inherently the objective.</p><p>Concurrency does not necessarily mean that multiple tasks have to be making progress <strong>at the exact same moment in time</strong>. They can make progress whenever possible. This means that time slicing, or progressing in turns, is totally fine and still implies concurrency. The only condition is that more than 1 task has to be in progress at a given point in time.</p><h3>Parallelism</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NbUrv2uA4P8YRJBB-T9eQ.png" /></figure><p>This is where things get tricky. Parallelism is a situation where multiple tasks are making progress <strong>at the same point in time</strong>. This is possible when different CPU cores are executing different tasks together. Each CPU core has it’s own chips for calculation/execution, so each CPU core can make progress independently.</p><p>Before we continue, let’s talk a little more about threads. When you launch a program, it is given a thread. The program also has the capability to ask for more threads. The maximum number of threads your system can run is usually way higher than the number of cores you have — for example, it’s 250,000 for me, and I have a 16 core CPU. The only way to run this many threads on a meagre amount of actual cores is, as you might have guessed, sharing the resources. This is done by the scheduler, which is a part of the OS kernel. The scheduler makes sure that all the existing threads get a chance to use the CPU. Imagine a queue of people at a store with only one booth — the actual booth is just one, but it can service multiple people one-by-one. Scheduling is something like that, except the booths are as many as the CPU cores you have, and the decision of whose turn it is next is dependent upon a much bigger variety of factors. Once a thread has exhausted it’s turn, context switching occurs which saves the current progress in the thread, and gives up control to the next thread.</p><p>You might have heard words like “UI thread” or “Background thread”, but this doesn’t mean those threads are specially made for UI or anything like that. It might just be called the UI thread because that’s where some program updates it’s UI. Threads are all structurally identical, except for “metadata” like priority.</p><p>Getting back to the topic, when you create a thread and run some operation on it, given that your programming language does not use green threads (which we’ll talk about in a bit), which core of the CPU the thread is going to run on depends on the scheduler (unless you manually set the thread affinity). This is decided based on a variety of conditions, like how long the thread has been running for, what the priority of the thread is, and so on. The finer details of scheduling and affinity are very complex and out of scope for this blog — they are very well researched topics with decades of development. It also depends on the type of the processor — for example, Intel recently released a performance-efficiency core based model on their newest CPUs; in this case, only some of the cores are suitable for CPU intensive tasks, and are called performance cores, whereas the rest of the cores are called efficiency cores and are meant to have background tasks with low system load on them. The scheduler has to make active decisions on which thread runs on which core based on the type of work they do.</p><p>Linux uses CFS (Completely Fair Scheduler) by default, which tries to give each thread a fair chance to finish by giving them turns of bursts of time to use the CPU cores. After that, it performs what’s known as “context switching”, where the current state of the registers is saved in the thread so that it can resume when it gets a turn next, and the next thread (calculated based on several factors) is given a chance to use the CPU. Context switching is a relatively expensive operation, since the state of all the registers has to be stored, and when the next thread is determined, the registers have to be populated with the values from when that thread last ran.</p><p>Hypothetically, you could have an extremely large number of threads since the kernel is able to time-slice and context switch and give each of them some time with the CPU, but this would not let any of the threads make any progress, because each of them would have so little time to progress it would take an eternity for any of them to finish. Hence, OS threads are not scalable, and operating systems usually have an upper limit for thread count.</p><p>This is where green threads come in! One example of a popular programming language that uses green threads is Golang, and it calls them goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QViBEa8XAdTbvUH8CZ_ldQ.png" /></figure><p>Goroutines are like threads, and run on OS threads. The Go runtime creates one OS thread for every CPU core you have, although the OS is probably running hundreds or thousands of threads already, created by other running programs.</p><p>Since you are allowed to have more goroutines than the number of OS threads the runtime creates, the Go runtime also comes with a scheduler! This scheduler is built into the Go runtime, and handles which OS thread runs which goroutine and for how long. What OS threads are to CPU cores, Goroutines are to OS threads (as OS threads are mapped onto CPU cores, and goroutines are mapped onto OS threads).</p><p>Summing it up, when you create multiple goroutines, the go scheduler schedules them on OS threads, and the kernel schedules those OS threads on the CPU cores where the code is finally run.</p><p>There are three benefits to this approach:</p><ul><li>The Go runtime knows what is going on in your program. It has access to the call stack and information about the execution state, which allows it to make more informed scheduling decisions.</li><li>A simple language-native communication method between goroutines, which we know as channels, is made possible. The inner workings of channels are out of scope for this blog.</li><li>The ability to create millions of goroutines worry free, since goroutines are faster to start, and switching to another goroutine is way cheaper than OS thread context switching.</li></ul><p>Talking about threads, you might have noticed CPUs advertising they have N cores and N * 2 threads. Something like “6 cores 12 threads”. But since threads are a software concept, why does a processor, something that is purely hardware, advertise this? This is probably where most of the confusion about threads being hardware comes from.</p><p>The reason why CPUs are able to advertise thread count as double the core count is thanks to Simultaneous Multithreading (SMT), which Intel calls Hyperthreading. Modern processors are very powerful, and one thread is often unable to satiate all the resources on a core, since instructions might have dependency chains, or experience high memory latency. Hence, modern CPUs expose two “logical” cores per physical core to the operating system. This allows hungry execution units to be fed with instructions at all times, and improves efficiency of resources. Since one physical core is represented as two logical cores in the OS, the scheduler can run two separate threads on these two logical cores, which ends up with, for example, 16 cores being able to run 32 threads.</p><p>Anyway, we got a bit sidetracked. In summary, asynchrony is being able to perform a task while waiting for another task to finish performing a slow operation like I/O, concurrency is about doing multiple things at a given point of time with that being the inherent goal, and parallelism is about doing multiple things at the exact same point of time. Asynchrony implies concurrency, but not necessarily parallelism (JS is able to achieve asynchrony and concurrency without parallelism thanks to the event loop). Concurrency might imply asynchrony (doing two things at once may be because that was the inherent goal, or because we moved on while waiting for a slow operation to finish), but not necessarily parallelism (concurrency might be due to things running on different cores or via time slicing). Parallelism implies concurrency, but not necessarily asynchrony (again, tasks might simply be performing computations and not necessarily waiting on something to happen on different cores).</p><p>And there you have it! Hopefully you now know a bit more about what Asynchrony, Concurrency, and Parallelism mean, along with a little bit about what threads are and how they work. Note that there are several topics mentioned here that are very complex, especially scheduling, and what I’ve written about them is an oversimplification at best. There are always many, <em>many</em> more details to dive into, should you wish to. Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309377e847bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/goalist-blog/asynchrony-concurrency-and-parallelism-309377e847bc">Asynchrony, Concurrency, and Parallelism</a> was originally published in <a href="https://medium.com/goalist-blog">Goalist Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>