<?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 Trey Tomes on Medium]]></title>
        <description><![CDATA[Stories by Trey Tomes on Medium]]></description>
        <link>https://medium.com/@trey.tomes?source=rss-9a78cc5abb11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YkKx8tCS1lpk9KJBMiENcg.jpeg</url>
            <title>Stories by Trey Tomes on Medium</title>
            <link>https://medium.com/@trey.tomes?source=rss-9a78cc5abb11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:28:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trey.tomes/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[Managing TypeScript Function Overloads]]></title>
            <link>https://medium.com/@trey.tomes/managing-typescript-function-overloads-dc9b9274d5d1?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc9b9274d5d1</guid>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 18:30:00 GMT</pubDate>
            <atom:updated>2024-06-04T13:37:48.634Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A tale of 2 render functions.</em></p><p>I recently learned how to use function overloading in TypeScript, as you can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*5tyS-POpK623QhyunMtc0w.png" /><figcaption>This function works, but it began hurting my head as soon as I finished writing it.</figcaption></figure><p>Basically, you list out all of your different function signatures, followed by the actual function implementation that needs argument types that can accommodate all of the different function signatures. It makes sense really; TypeScript is just JavaScript in a fancy suit. Everything you write needs to get projected down into JavaScript.</p><p>I love it and I hate it. The function overloads allow me to easily refer to different ways of calling the same function, but implementing the logic to pick and choose which parameter variants to use in the function body is a pain to implement, and even more painful to look at a day later.</p><p>What I finally landed on is a pattern I picked up using the AWS CDK (and React), passing in single-parameter prop types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*UKZn3944RzwcaZAg-l-IaA.png" /><figcaption>Or’ing together prop sets like this ensures that all related props will be passed in to a function together.</figcaption></figure><p>The thing I like about these prop types is that we’ve bundled together the entire set of arguments a function needs to operate in any of its variants. In this example, the function can be called with either x and y parameters, or with a pnt parameter that contains the x and y. The final render function will accept the RenderProps type, which as indicated above can be either the XY or Point variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*WlXBbSkGeYYLQKgZSnQ_rA.png" /></figure><p>You still need to do a bit of type juggling to ensure you are grabbing the correct variant of RenderProps. The instanceof syntax doesn’t work with types that I know of, which is a shame in this case. I love that I can tell with a quick glance exactly what this function is trying to do with its parameters.</p><p>So it’s not official TypeScript function overloading, but so far it seems to be better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc9b9274d5d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Flood Fill Algorithm]]></title>
            <link>https://medium.com/@trey.tomes/the-flood-fill-algorithm-a984b559da02?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/a984b559da02</guid>
            <category><![CDATA[gamedev]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[pixel]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Mon, 20 May 2024 19:07:17 GMT</pubDate>
            <atom:updated>2024-05-20T19:56:44.916Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The flood fill algorithm allows us to fill any arbitrarily-shaped region with a color (or a pattern, if you are determined to do so).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*5RdSRN6pDQgpzZN8QOZ4wQ.png" /><figcaption>So pretty!</figcaption></figure><p>The basic algorithm goes as follows:</p><ol><li>Pick a point in the region you want to fill. The color at that point is the color we will be replacing (the sourceColor) with our target color (the targetColor).</li><li>Push that point onto a queue.</li><li>Pull the next point off of your queue. If there are no more points in the queue then we’re done.</li><li>If that point’s color matches sourceColor: change it to match targetColor, then push the points to the north, south, east, and west onto the queue.</li><li>Go to 3.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FGRaZJQE%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DGRaZJQE&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FGRaZJQE&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FGRaZJQE-512.jpg%3Fversion%3D1716214900&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a09eeaafb31b38ed21f26f4c12951f/href">https://medium.com/media/e0a09eeaafb31b38ed21f26f4c12951f/href</a></iframe><p>Or, to say it in JavaScript:</p><pre>const floodFill = (x, y, c) =&gt; {<br>  let queue = [];<br>  <br>  // This is the source color we are replacing.<br>  const sourceColor = getPixel(x, y);<br>  <br>  // Need to explicitly ensure 2 colors are the same.<br>  const colorEqual = (a, b) =&gt; (a.r === b.r) &amp;&amp; (a.g === b.g) &amp;&amp; (a.b === b.b);<br>  <br>  // Is it in range?  Does it match our source color?<br>  const isValid = (xp, yp) =&gt; (xp &gt;= 0) &amp;&amp; (xp &lt; width) &amp;&amp; (yp &gt;= 0) &amp;&amp; (yp &lt; height) &amp;&amp; colorEqual(getPixel(xp, yp), sourceColor);<br><br>  // Push the origin onto the queue.<br>  queue.push([x, y]);<br><br>  while (queue.length &gt; 0) {<br>    const currPixel = queue.pop();<br><br>    let posX = currPixel[0];<br>    let posY = currPixel[1];<br>    setPixel(posX, posY, c);<br><br>    if (isValid(posX + 1, posY)) queue.push([posX + 1, posY]);<br>    if (isValid(posX - 1, posY)) queue.push([posX - 1, posY]);<br>    if (isValid(posX, posY + 1)) queue.push([posX, posY + 1]);<br>    if (isValid(posX, posY - 1)) queue.push([posX, posY - 1]);<br>  }<br>}</pre><p>This method of walking through each point in a region is similar to what I would do to implement the A* Search Algorithm, which is what we will be covering next.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fu6eQkrj4QTc&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Du6eQkrj4QTc&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2Fu6eQkrj4QTc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/71b688c670b30f127d1af6f3a5d65378/href">https://medium.com/media/71b688c670b30f127d1af6f3a5d65378/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a984b559da02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Midpoint Ellipse Algorithm]]></title>
            <link>https://medium.com/@trey.tomes/the-midpoint-ellipse-algorithm-d3c7442866da?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c7442866da</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[retro]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[pixel]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Tue, 14 May 2024 15:13:37 GMT</pubDate>
            <atom:updated>2024-05-14T15:13:37.596Z</atom:updated>
            <content:encoded><![CDATA[<p>The midpoint ellipse algorithm looks a lot like the circle algorithm that we dug into <a href="https://medium.com/@trey.tomes/bresenhams-circle-algorithm-2153b32a0ecf">last time</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*6p-T5FOl60nX-8wn8MCYNg.png" /></figure><p>Given an ellipse plotted out something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SRdHPtOfLALO08p1.png" /></figure><p>The standard form of the ellipse equation looks something like this:</p><pre>((x - h) ** 2) / (a ** 2) + ((y - k) ** 2) / (b ** 2) - 1 = 0</pre><p>So let’s dive in to the code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FZENGEeX%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DZENGEeX&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FZENGEeX&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FZENGEeX-512.jpg%3Fversion%3D1715633430&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fe983ba61fd7746c1ac246f645fbc00/href">https://medium.com/media/6fe983ba61fd7746c1ac246f645fbc00/href</a></iframe><pre>/**<br> * @param {number} rx Radius along the x-axis.<br> * @param {number} ry Radius along the y-axis.<br> * @param {number} xc Center point along the x-axis.<br> * @param {number} yc Center point along the y-axis.<br> * @param {Color} c The color to use.<br> * @param {boolean} filled Should the interior of the circle be filled in?<br> */<br>export const drawEllipse = (rx, ry, xc, yc, c, filled=false) =&gt; {<br>  // Draw points based on 4-way symmetry.<br>  const drawQuadrants = (x, y) =&gt; {<br>    if (filled) {<br>      for (let xx = xc - x; xx &lt;= xc + x; xx++) {<br>        setPixel(xx, yc + y, c);<br>        setPixel(xx, yc - y, c);<br>      }<br>    } else {<br>      setPixel(x + xc, y + yc, c);<br>      setPixel(-x + xc, y + yc, c);<br>      <br>      setPixel(x + xc, -y + yc, c);<br>      setPixel(-x + xc, -y + yc, c);<br>    }    <br>  };<br>  <br>  let x = 0;<br>  let y = ry;<br><br>  // Initial decision parameter of region 1.<br>  let d1 = (ry * ry) - (rx * rx * ry) + (0.25 * rx * rx);<br>  let dx = 2 * ry * ry * x;<br>  let dy = 2 * rx * rx * y;<br><br>  // For region 1<br>  while (dx &lt; dy) {<br>    drawQuadrants(x, y);<br>    <br>    // Checking and updating value of decision parameter based on algorithm<br>    if (d1 &lt; 0) {<br>      x++;<br>      dx = dx + (2 * ry * ry);<br>      d1 = d1 + dx + (ry * ry);<br>    } else {<br>      x++;<br>      y--;<br>      dx = dx + (2 * ry * ry);<br>      dy = dy - (2 * rx * rx);<br>      d1 = d1 + dx - dy + (ry * ry);<br>    }<br>  }<br><br>  // Decision parameter of region 2<br>  let d2 = ((ry * ry) * ((x + 0.5) * (x + 0.5))) + ((rx * rx) * ((y - 1) * (y - 1))) - (rx * rx * ry * ry);<br>  <br>  // Plotting points of region 2<br>  while (y &gt;= 0) {<br>    drawQuadrants(x, y);<br>    <br>    // Checking and updating parameter value based on algorithm<br>    if (d2 &gt; 0) {<br>      y--;<br>      dy = dy - (2 * rx * rx);<br>      d2 = d2 + (rx * rx) - dy;<br>    } else {<br>      y--;<br>      x++;<br>      dx = dx + (2 * ry * ry);<br>      dy = dy - (2 * rx * rx);<br>      d2 = d2 + dx - dy + (rx * rx);<br>    }<br>  }<br>};</pre><p>The basic premise goes back to the standard form of the equation. If you plug all of your variables into the equation, and it equals 0, you are directly on the path of the ellipse. If the result is less than 0 you are inside the ellipse, otherwise you are outside the ellipse. The while-loops check against 0, then modify the other variables accordingly to keep as close to the path of the ellipse as possible.</p><p>The standard form of this equation plots 4 points for each (x, y) coordinate based on the 4-way symmetry of the ellipse. We further take advantage of this symmetry to fill in the inside of the ellipse when the filled parameter is toggled.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKz4PWvtrhA0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKz4PWvtrhA0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKz4PWvtrhA0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3368dc9e1065f17eebf123f628a87a2b/href">https://medium.com/media/3368dc9e1065f17eebf123f628a87a2b/href</a></iframe><p>In the CodePen you will see this code in the onRender function:</p><pre>const r = 80<br>const dx = width / 2<br>const dy = height / 2<br>drawEllipse(r / 2 + r * Math.sin(totalTime / 256), r + (r / 2) * Math.cos(totalTime / 256), dx, dy, colors[4], Math.floor(totalTime / blinkIntervalMs) % 2);</pre><p>By modifying the x and y radius values by a factor of totalTime, we are able to animate the ellipse a bit. Plugging time into sin and cos functions allows us to constrain the radius modifier to a range of [-1, 1].</p><p>Our raster graphics library can now handle lines, boxes, circles, and ellipses. Tune in next time to see the flood fill algorithm in action!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c7442866da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bresenham’s Circle Algorithm]]></title>
            <link>https://medium.com/@trey.tomes/bresenhams-circle-algorithm-2153b32a0ecf?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/2153b32a0ecf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[pixel]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[retro]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Mon, 06 May 2024 20:57:19 GMT</pubDate>
            <atom:updated>2024-05-06T21:59:05.197Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Circles done 3 ways! Which one is your favorite?<br>This is the 5th part of my series on raster graphics algorithms, which begins </em><a href="https://medium.com/@trey.tomes/a-clean-canvas-for-retro-game-dev-03dd21dbf4e7"><em>here</em></a><em>.</em></p><p>Have you ever really thought about how weird a circle is? Most any child could draw one without thinking. Just swoop that pencil in a line and you’re done. Now write out the steps atomically so you can tell a computer how to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*DwIlSNrT5ICrSXz-zEZwwQ.png" /><figcaption>Circles are so weird.</figcaption></figure><p>We can’t even completely describe circles mathematically. Sure we have constants like pi, but that only allows us to <em>approximate</em> a circle. And yet they’re the most natural thing in all of creation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FZEZgMEE%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DZEZgMEE&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FZEZgMEE%3Feditors%3D0010&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FZEZgMEE-512.jpg%3Fversion%3D1714998970&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6486692b43097b382e49f6bf7ab2cda1/href">https://medium.com/media/6486692b43097b382e49f6bf7ab2cda1/href</a></iframe><p>In our first attempt at drawing a circle we’ll be using a bit trigonometry. This is probably the easiest algorithm to make this work, you just gotta know the formula:</p><pre>x = dx + r * cos(θ)<br>y = dy + r * sin(θ)</pre><p>dx and dy represent the screen offset to the center of your circle, ris the radius, and θ is the angle. Don’t forget to convert from degrees to radians!</p><pre>const pi = 3.14159265359;<br>const radius = 100;<br>const xOffset = width / 2;<br>const yOffset = height / 2;<br>for (let angle = 0; angle &lt; 360; angle++) {<br>  const radians = angle * pi / 180;<br>  const x = xOffset + radius * Math.cos(radians);<br>  const y = yOffset + radius * Math.sin(radians);<br>  setPixel(x, y, colors[4]);<br>}</pre><p>Aside from the expensive math involved, this algorithm works fine at small radiuses, but as the circle grows bigger not the gaps between pixels. You could account for this by modifying the angle++ increment to something smaller, but how small should you go? Go too small and you’re loop will run for too long, go too big and you’ll still have gaps. And you will need to continue decreasing that increment as your circle grows!</p><p>Let’s try another:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FKKYOrWB%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DKKYOrWB&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FKKYOrWB&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FKKYOrWB-512.jpg%3Fversion%3D1715006964&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bebff3e86e028844aa2cf6b7dcffd0c3/href">https://medium.com/media/bebff3e86e028844aa2cf6b7dcffd0c3/href</a></iframe><p>The standard equation for a circle is: (x+dx)^2+(y+dy)^2)=r^2. We need to do a bit of algebra to solve for x if we want to plot this from x=[0,width):</p><pre>(x-dx)^2+(y-dy)^2=r^2<br>(y-dy)^2=r^2-(x-dx)^2<br>y-dy=(sqrt(r^2-(x-dx)^2) | -sqrt(r^2-(x-dx)^2))<br>y=(sqrt(r^2-(x-dx)^2)+dy | -sqrt(r^2-(x-dx)^2)+dy)</pre><p>From that point iterating across the x-axis and solving for y at each point is relatively painless:</p><pre>for (let x = 0; x &lt; width; x++) {<br>  let y = Math.sqrt(r ** 2 - (x - dx) ** 2) + dy;<br>  setPixel(x, y, colors[4]);<br>  <br>  y = -Math.sqrt(r ** 2 - (x - dx) ** 2) + dy;<br>  setPixel(x, y, colors[4]);<br>}</pre><p>This algorithm does solve a couple of over our first attempt. We will only ever need width number of iterations through our for loop to plot the circle, and we are only plotting 2 pixels for each value of x. It also scales well; the sides of our circle will look equally bad at any size! The problem is that huge jump as the sides of our circle go vertical. We could solve for this by running a second for-loop with our equation flipped, solving for x instead y , but then we’ll be doubling on plotting most of the pixels. This is not ideal. So now I’ll show you a better way.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FWNWVBjG%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DWNWVBjG&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FWNWVBjG&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FWNWVBjG-512.jpg%3Fversion%3D1715027861&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7342ed0b13479dc2594ff835a6c54ccb/href">https://medium.com/media/7342ed0b13479dc2594ff835a6c54ccb/href</a></iframe><p>Bresenham’s Circle Algorithm takes advantage of the circle’s symmetry: If you can calculate the coordinate for 1 point on the circle, you can then extrapolate that to find 8 symmetrical points around the circle! It is functionally similar to Bresenham’s Line Algorithm, using simple arithmetic to walk around the circle along with some error correction to keep it on course. Aside from that, this is one of those algorithm’s that I would suggest you take a look at, but don’t worry too much about the deeper math behind it. It’s fast, accurate enough, and worth keeping a copy of in your raster graphics arsenal.</p><pre>export const drawCircle = (xc, yc, r, c, filled = false) =&gt; {<br>  xc = Math.floor(xc);<br>  yc = Math.floor(yc);<br>  r = Math.floor(r);<br>  <br>  const drawOctants = (x, y) =&gt; {<br>    setPixel(xc + x, yc + y, c);<br>    setPixel(xc - x, yc + y, c);   <br>    setPixel(xc + x, yc - y, c);<br>    setPixel(xc - x, yc - y, c);<br>    <br>    setPixel(xc + y, yc + x, c);<br>    setPixel(xc - y, yc + x, c);<br>    setPixel(xc + y, yc - x, c);<br>    setPixel(xc - y, yc - x, c);<br>  };<br>  <br>  const fillOctants = (x, y) =&gt; {<br>    for (let xx = xc - x; xx &lt;= xc + x; xx++) setPixel(xx, yc + y, c);<br>    for (let xx = xc - x; xx &lt;= xc + x; xx++) setPixel(xx, yc - y, c);<br><br>    for (let xx = xc - y; xx &lt;= xc + y; xx++) setPixel(xx, yc + x, c);<br>    for (let xx = xc - y; xx &lt;= xc + y; xx++) setPixel(xx, yc - x, c);<br>  }<br><br>  let x = 0, y = r;<br>  let d = 3 - 2 * r;<br>  filled ? fillOctants(x, y) : drawOctants(x, y);<br>  while (y &gt;= x) {<br>    x++;<br><br>    if (d &gt; 0) {<br>      y--;<br>      d = d + 4 * (x - y) + 10;<br>    } else {<br>      d = d + 4 * x + 6;<br>    }<br>    filled ? fillOctants(x, y) : drawOctants(x, y);<br>  }<br>}</pre><p>I have modified the original algorithm a bit here with the fillOctants function. By modifying how we handle the octant coordinates, we give the user the option to fill in the circle!</p><p>“Accurate enough”. When you’re attempting to simulate some aspect of the natural world inside of a computer, you will find yourself stumbling on this concept often. Bresenham’s circles look a little at small radius values, but they are accurate enough and most people will overlook the problem.</p><p><em>Exercises for the reader:</em></p><ul><li><em>Modify the circle radius. Check out the rendering at different sizes.</em></li><li><em>Follow along with my Electron Game Engine series on YouTube </em><a href="https://youtu.be/m18MsH1MIZI"><em>here</em></a><em>.</em></li></ul><p>This function is fine as long as all we need are circles, but what about ellipses? To be continued…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2153b32a0ecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bresenham’s Line Algorithm]]></title>
            <link>https://medium.com/@trey.tomes/bresenhams-line-algorithm-2dc69ee7dc15?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dc69ee7dc15</guid>
            <category><![CDATA[retro-gaming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pixel-art]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 01:30:35 GMT</pubDate>
            <atom:updated>2024-04-30T01:30:35.064Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the 4th installment of my retro graphics algorithm series. You can find part 3 </em><a href="https://medium.com/@trey.tomes/generative-art-with-1d-automata-582b01716fdb"><em>here</em></a><em>.</em></p><p>Jack Elton Bresenham developed this algorithm all the way back in 1962! The first home computers didn’t hit the market for another decade, and didn’t really start becoming popular for yet another decade after that, but programmers were already plotting out the fastest way to draw pictures on screens.</p><p>A special thing about Bresenham’s algorithm is that it doesn’t require multiplication or division. It’s all simple operations, which means it’s fast. I started programming in the last ’80s, and I still have this idea locked in my head to this day that multiplication and division should be avoided at all costs if you want to move quickly. Especially division; you haven’t lived until you have built a logic circuit that will perform base-10 division (it’s hard)!</p><p>I’ve been writing these articles to roughly correspond with <a href="https://www.youtube.com/watch?v=f1cwb-Hh8RQ&amp;list=PLsC0KLtToCh2KVIasEFGQeBxP_yIzl6K2">my YouTube series</a> on building a retro game engine based in the Electron framework. It took 3 videos for me to figure out exactly how I wanted to implement line drawing in JavaScript:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbRqVkoRVOOE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbRqVkoRVOOE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbRqVkoRVOOE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d480b01708e05ae0cbf40fb20a61a8/href">https://medium.com/media/57d480b01708e05ae0cbf40fb20a61a8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0osaxa30Yvo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0osaxa30Yvo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0osaxa30Yvo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d59120f284fe70170abc037f3af1f67e/href">https://medium.com/media/d59120f284fe70170abc037f3af1f67e/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FU7xw49LSM_Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DU7xw49LSM_Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FU7xw49LSM_Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/900bb3a607b926571c73b74581950446/href">https://medium.com/media/900bb3a607b926571c73b74581950446/href</a></iframe><p>Live coding videos are fun to watch, but they’re more of a long hayride than a roller-coaster. Watch them when you have a chance to sit back and relax into some comforting JavaScript.</p><p>Lucky for you, the problems I encountered implementing this live on video will simply be skipped over for you. You get to enjoy the end result of all that hard labor!</p><p>We have 3 categories of functions that we’ll be implementing:</p><ol><li>Horizontal and vertical line drawing,</li><li>Rectangles and filled rectangles,</li><li>And finally, Bresenham’s algorithm for fast, arbitrarily plotted lines.</li></ol><p>I’m starting with horizontal and vertical lines because they are the easiest.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FbGJJyEo%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DbGJJyEo&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FbGJJyEo&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FbGJJyEo-512.jpg%3Fversion%3D1714433310&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c57d17af89c91018d675d192e40c45e/href">https://medium.com/media/5c57d17af89c91018d675d192e40c45e/href</a></iframe><p>Both functions (drawHorizontalLine and drawVerticalLine) operate basically the same, running a for-loop from one end of the line to the other.</p><pre>/**<br> * Draw a horizontal line from (x1, y) to (x2, y).<br> *<br> * @param {number} x1<br> * @param {number} x2<br> * @param {number} y<br> * @param {{r: number, g: number, b: number}} color<br> */<br>const drawHorizontalLine = (x1, x2, y, color) =&gt; {<br>  for (let x = x1; x &lt;= x2; x++) {<br>    setPixel(x, y, color);<br>  }<br>}</pre><p><strong>Note: These functions are not as fast as they could be. More on that in a later article.</strong></p><p>Check out the onRender function for an example of how to use these functions to draw a grid. The principal to drawing a grid isn’t all that different than drawing a line. And, if you collapse the grid space to one, you have a rectangle!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FQWPPRBV%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DQWPPRBV&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FQWPPRBV&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FQWPPRBV-512.jpg%3Fversion%3D1714438285&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e663dfbefeabb9caee831e9dd9c1e0dd/href">https://medium.com/media/e663dfbefeabb9caee831e9dd9c1e0dd/href</a></iframe><p>Two new functions here: drawRectangle and fillRectangle. Check out the source code (click the “JS” button in the CodePen) and see if you can make sense of them! drawRectangle creates a rectangle from 2 horizontal line and 2 vertical lines; fillRectangle runs a loop much like the grid renderer in our previous example, stacking horizontal lines on top of each other until we’ve filled the entire space.</p><p>The tricky part is actually implementing Bresenham’s algorithm. It’s not a hard algorithm in itself, just simply need to remember to implement the <em>entire thing</em>. It works by deconstructing the line algorithm you probably learned in Algebra class (y=M*x+B), then running a loop that walks a point along the line one pixel at a time either horizontally or vertically. That “one pixel at a time” thing is the most important bit; I could simply run a loop from x1 to x2 and calculate the y value of each point, but I would miss entire vertical runs of pixels! Here’s the entire function that brings the magic to us:</p><pre>const drawLine = (x1, y1, x2, y2, color) =&gt; {<br>  let dx = Math.abs(x2 - x1);<br>  let sx = (x1 &lt; x2) ? 1 : -1;<br>  let dy = Math.abs(y2 - y1);<br>  dy = -dy;<br>  let sy = (y1 &lt; y2) ? 1 : -1;<br>  let err = dx + dy;<br><br>  while (true) {<br>    setPixel(x1, y1, color);<br>    if ((x1 == x2) &amp;&amp; (y1 == y2)) break;<br>    let e2 = err &lt;&lt; 1;<br>    if (e2 &gt;= dy) {<br>      if (x1 === x2) break<br>      err += dy;<br>      x1 += sx;<br>    }<br>    if (e2 &lt;= dx) {<br>      if (y1 === y2) break;<br>      err += dx;<br>      y1 += sy;<br>    }<br>  }<br>}</pre><p>Honestly, the easiest way to come up with code like this (aside from copying mine) is to dig up some old C implementation, and convert it to JavaScript line by line. Which is exactly what I did here. Algorithms like this are best taken at face value. There is deeper theory to learn here about how this function manages to cover the 8 octants of the coordinate grid, and how exactly the error correction value works, but as a software developer the most important thing has been to simply to make sure it looks right when you run it, and to make it run as quickly as possible.</p><p>And at last, we are able to Bresenham’s Line Algorithm in action.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FVwNNORp%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DVwNNORp&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FVwNNORp&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FVwNNORp-512.jpg%3Fversion%3D1714439799&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc78f4749d978fcbf7e0a84a9ba611f3/href">https://medium.com/media/dc78f4749d978fcbf7e0a84a9ba611f3/href</a></iframe><p>It’s fast enough that we will probably dispense with the horizontal and vertical line drawing functions in our final raster graphics library. We <em>do </em>have a performance problem coming up soon: The way we are calling setPixel every time we draw a pixel is not very efficient! We’ve gotten away with it on these small demos, but it will come back around to bite us soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*tdiWx9fndGDt3Mi3A3HANA.png" /><figcaption>It looks almost like an eye. If only we knew how to draw a circle in the center…</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dc69ee7dc15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Art With 1D Automata]]></title>
            <link>https://medium.com/@trey.tomes/generative-art-with-1d-automata-582b01716fdb?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/582b01716fdb</guid>
            <category><![CDATA[cellular-automata]]></category>
            <category><![CDATA[retro]]></category>
            <category><![CDATA[pixel-art]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 20:26:54 GMT</pubDate>
            <atom:updated>2024-04-29T20:26:54.830Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is the 3rd article in my series on basic graphics algorithms. You can read my previous article on the Chaos Game </em><a href="https://medium.com/@trey.tomes/sierpinskis-triforce-03c114e62238"><em>here</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kr13NlRa1LgHlUF6s6uClA.png" /><figcaption>Rule-90 - I feel like we’ve seen this one before…</figcaption></figure><p>I first learned about 1D cellular automata (and 2D as well), from Steven Levy’s book “Artificial Life: The Quest for a New Creation”, which I <a href="https://amzn.to/4dtFhyG">highly recommend</a> as reading material to anyone wanting to learn about the landscape of artificial intelligence research beyond the modern fascination with large language models. Steven Levy’s book will give you a tour of the entire artificial life / intelligence field, covering fields such as neural networks, cellular automata, generative art, and genetic algorithms. He introduces the people who began this field of research, and will get you thinking about the philosophy of what makes something “alive”, versus simply “intelligent-seeming”.</p><p>The concept of 1D cellular automata was originally popularized by Stephen Wolfram all the way back in 1982. You might recognize that name if you’ve ever used <a href="https://www.wolframalpha.com/">Wolfram Alpha</a>. The connection is not a coincidence. What’s amazing is that the images generated using this algorithm can also be found in nature, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KiIV5Fj0AOExb2ROe9_YCA.jpeg" /><figcaption>This image came from Steven Levy’s book. What algorithm did this shell use to pattern itself?</figcaption></figure><p>Let’s walk through the JavaScript code necessary to produce a 1D cellular automata image.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FExJJXwm%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DExJJXwm&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FExJJXwm&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FExJJXwm-512.jpg%3Fversion%3D1714406134&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/465314b28a32aa47db90063c3b692c48/href">https://medium.com/media/465314b28a32aa47db90063c3b692c48/href</a></iframe><p>I will only be explaining the code that has changed since my last article, so you will want to <a href="https://medium.com/@trey.tomes/a-clean-canvas-for-retro-game-dev-03dd21dbf4e7">go back and read those articles</a> if you need a deeper look at what’s going on here.</p><p>Probably the most important bit of this entire applet is the rules array:</p><pre>const rules = {<br>  0b000: 0,<br>  0b001: 1,<br>  0b010: 0,<br>  0b011: 1,<br>  0b100: 1,<br>  0b101: 0,<br>  0b110: 1,<br>  0b111: 0,<br>}</pre><p>A rule is executed for a single pixel by looking at the 3 pixels just above it: the top-left, top-center, and top-right. Each source pixel can be on or off, so that leads to 2³=8 rules. Each rule will result in the target pixel being on or off, leading to 2⁸=256 possible rulesets. There’s a great article about these rulesets up on <a href="https://mathworld.wolfram.com/ElementaryCellularAutomaton.html">mathworld.wolfram.com</a>. The JavaScript code in the previous block is for rule 90: 01011010, reading the digits from top-to-bottom, and plugging them into the binary number from right-to-left (least significant digit always sits on the right, but the 0th index of an array is listed first).</p><p>As to the general flow of the program: onInit clears the screen and sets the “seed” pixel at the top-center of the screen, then onRender is called on each frame to update some variables and draw whatever we’re going to draw. I’ve modified this function a bit from my last article to make it easier to read.</p><p>The purpose of this block is to have our point move from the top-left to bottom-right of the screen, moving by one pixel on each frame:</p><pre>// Our point will move left-to-right, top-to-bottom.<br>point.x++;<br>if (point.x &gt;= width) {<br>  // When the point reaches the end of a line, we move y to the next line and reset x to the beginning of the next line.<br>  point.x = 0;<br>  point.y++;<br>  <br>  if (point.y &gt;= height) {<br>    // When the point reaches the end of the last line, make sure it stays in bounds and toggle the isDone flag to end rendering.<br>    point.y--;<br>    isDone = true;<br>  }<br>}</pre><p>The if-blocks there will check if the x or y positions have gone out of range and wrap them around to 0 if so, then activate the isDone flag at the end to make sure we stop executing the block.</p><p>Once we have our point in the next position, we need to check our rules to see what color to assign to the new point.</p><pre>// Get the color of the 3 points in the line just above the current point.<br>// We defined the getPixel function just for this purpose!<br>let topLeft = getPixel(point.x - 1, point.y - 1);<br>let topCenter = getPixel(point.x, point.y - 1);<br>let topRight = getPixel(point.x + 1, point.y - 1);<br><br>// Now that we have the colors, we test if that pixel is &quot;active&quot; by comparing it to black.<br>topLeft = !isBlack(topLeft);<br>topCenter = !isBlack(topCenter);<br>topRight = !isBlack(topRight);<br><br>// Now we construct a binary number from the 3 boolean values.<br>const ruleIndex = (topLeft ? 0b100 : 0b000) + (topCenter ? 0b010 : 0b000) + (topRight ? 0b001 : 0b000);<br>const result = rules[ruleIndex];<br><br>// Plot the pixel if the result is true.<br>if (result) {<br>  setPixel(point.x, point.y, blue);<br>}</pre><p>getPixel will retrieve an object with {r, g, b} values for the color of the target pixel, so we can grab the color of the 3 pixels directly above the current position. We then need to see which of those colors are not block, then do a bit of math to convert our 3 true/false values into a 3-digit binary number. I’m using a ternary operator (?:) to accomplish this bit. You can learn more about the ternary operator <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator">here</a>.</p><p>We could do more with this algorithm. You could have multiple rulesets operating on each of the 3 red, green, blue channels. You could seed the top row with random numbers to generate a more complex final product. We have the algorithm running left-to-right, top-to-bottom; you could rotate or flip the algorithm onto a different axis and layer it with other rulesets. What do you think you’ll try to make?</p><p>That’s probably it for pixel plotting articles for now; next up I would like to talk through Bresenham’s line drawing algorithm. Raster graphics starts getting really interesting when you can draw a line wherever you want.</p><p><em>Exercises for the reader:</em></p><ul><li><em>Modify the width and height values a the top of the JavaScript code. See what the image looks like at different resolutions.</em></li><li><em>Head down to line 28 for the list of </em><em>rules. Modify the numbers, either randomly or using Wolfram’s code as a guide. See what patterns you can make!</em></li><li><em>I’m only setting the top-center pixel to “seed” our image. Try plotting some more pixels on that top row and see how it affects the result.</em></li></ul><p><strong>References</strong></p><ul><li><a href="https://amzn.to/4dtFhyG">“Artificial Life: The Quest for a New Creation”, by Steven Levy</a></li><li><a href="https://en.wikipedia.org/wiki/Stephen_Wolfram">Wikipedia biography of Stephen Wolfram</a></li><li><a href="https://en.wikipedia.org/wiki/Elementary_cellular_automaton">Wikipedia entry on 1D / Elementary Cellular Automata</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582b01716fdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sierpinski’s Triforce]]></title>
            <link>https://medium.com/@trey.tomes/sierpinskis-triforce-03c114e62238?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/03c114e62238</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[retro-gaming]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 19:50:20 GMT</pubDate>
            <atom:updated>2024-04-29T20:29:32.240Z</atom:updated>
            <content:encoded><![CDATA[<p><em>You’ll want to read </em><a href="https://medium.com/@trey.tomes/a-clean-canvas-for-retro-game-dev-03dd21dbf4e7"><em>this</em></a><em> article before starting in here. It explains where all the graphics code is coming from.</em></p><p>Once upon a time there was a mathematician called Wacław Franciszek Sierpiński. I don’t know a whole lot about him. He was born almost exactly 100 years before me. He made important contributions to several areas of mathematics theory that most of us will never use. The reason I learned his name at such a young age (middle school-ish?), was because of this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*pa0DjfPcx9ndWCFmqYXX8A.png" /><figcaption>Sierpinski’s Triangle</figcaption></figure><p>One of the very first games I ever played on the NES was the Legend of Zelda. Pop open nearly any Zelda game and you’ll see triforces all over the place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*IeBhQjfwPWL2aLUF.png" /><figcaption>This is clearly a rip-off of the life work of a famous mathematician.</figcaption></figure><p>It’s a neat example of a fractal, a shape that continues to show detail forever as you zoom in to it. And super easy to build for yourself! Let’s talk about the Chaos Game.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FzYXbjdM%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DzYXbjdM&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FzYXbjdM&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FzYXbjdM-512.jpg%3Fversion%3D1714146638&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/45a7dcec6bb946219a16d2938d1b4816/href">https://medium.com/media/45a7dcec6bb946219a16d2938d1b4816/href</a></iframe><p>The algorithm goes like this:</p><ol><li>Define 3 corners for your triangle. Equilateral triangles are the most popular, but any 3 points will do.</li><li>Draw a dot halfway between any 2 corners of your triangle.</li><li>Pick another corner at random. Draw a dot halfway between your last dot and the new corner.</li><li>Keep repeating step 3 forever.</li></ol><p>If you check out the JavaScript, that’s basically what you’ll see. This bit here defines our 3 corners:</p><pre>// These 3 points define the shape of our initial triangle.<br>const corners = [<br>  { x: width / 2, y: 0 }, // top-center<br>  { x: 0, y: height - 1 }, // bottom-left<br>  { x: width - 1, y: height - 1 }, // bottom-right<br>];</pre><p>Then we initialize our nextPoint variable with a random corner. I’ve gone out of my way to over-document getRandomCorner function for those of you not familiar with JavaScript, but you’ll have to open the CodePen to see it.</p><pre>// Initialize our first point.<br>let nextPoint = getRandomCorner();</pre><p>This bit in the onRenderFrame function will choose a second corner, move nextPoint halfway between the last point and the new corner, then draw a dot there. Because it’s in onRenderFrame it will play the part of step 3, getting repeated forever.</p><pre>// Pick a corner at random.<br>const randomCorner = getRandomCorner();<br><br>// Our next point is halfway between the previous point and the randomly-selected corner.<br>nextPoint.x = (randomCorner.x + nextPoint.x) / 2;<br>nextPoint.y = (randomCorner.y + nextPoint.y) / 2;<br><br>// Plot the pixel.<br>setPixel(nextPoint.x, nextPoint.y, yellow);</pre><p>There are several other really neat algorithms for generating Sierpinki’s Triangle. 1D cellular automata and L-systems jump immediately to mind. We might cover each of those in a future article; they’re both really neat algorithms to try and implement.</p><p><strong>Note: There is no actual proof that the Legend of Zelda developers even knew who Sierpinki was when they wrote their game. As far as the world knows this is simply a happy coincidence.</strong></p><p><em>An exercise for the reader:</em><br><em>Make a copy of the </em><a href="https://codepen.io/treytomes/pen/zYXbjdM"><em>Sierpinki’s Triforce CodePen</em></a><em>. You’ll need to create your own CodePen account for this. Pick 3 new points for the </em><em>corners array and see what the resulting picture looks like. Make sure you keep the x and y values between </em><em>0 and </em><em>width/</em><em>height. Maybe even change the </em><em>width and</em><em> height values themselves to change the size of the pixels. Send me a screenshot of what you come up with!</em></p><p>Continue this adventure in retro graphics algorithm <a href="https://medium.com/@trey.tomes/generative-art-with-1d-automata-582b01716fdb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03c114e62238" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Clean Canvas for Retro Game Dev]]></title>
            <link>https://medium.com/@trey.tomes/a-clean-canvas-for-retro-game-dev-03dd21dbf4e7?source=rss-9a78cc5abb11------2</link>
            <guid isPermaLink="false">https://medium.com/p/03dd21dbf4e7</guid>
            <category><![CDATA[retro-gaming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <dc:creator><![CDATA[Trey Tomes]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 19:57:53 GMT</pubDate>
            <atom:updated>2024-04-29T00:18:51.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*LrOtsHvSa83uYIMkhU7Z-Q.png" /><figcaption>Bouncing a pixel around the screen.</figcaption></figure><p>I’m going to be writing a lot about retro video game development. I cut my teeth on an 8-bit NES in the late ’80s, and will always be fascinated with how those games were developed. So much was built back then with so little.</p><p>Most books on game development will focus on C++, OpenGL, Vulkan, shaders, WebGL, 3D math, etc. Building models and settings up realistic reflection and shadows. I’ll be working from a much simpler foundation: Vanilla JavaScript. My goal is to build a game engine suitable for designing the type of experience you might have received on an old NES or SNES. Low resolution, palette-based coloring, 2D graphics. 8-bit music and sounds effect perhaps? Around 60 frames per second? My proposal is that all of this is very achievable from a JavaScript framework. If a program from the ’80s could do it in assembly on a processor measured in the megahertz, a modern program on a gigahertz processor can do it from a scripted language.</p><p>I’m aiming to include an interactive demo with each of these articles, beginning with the canvas we’ll be using as a display.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fembed%2Fpreview%2FYzMgyMb%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DYzMgyMb&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Ftreytomes%2Fpen%2FYzMgyMb&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FYzMgyMb-512.jpg%3Fversion%3D1714070983&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3875cd23936164b7675eb19f4b8298d8/href">https://medium.com/media/3875cd23936164b7675eb19f4b8298d8/href</a></iframe><p>If you dig into the CodePen you’ll notice there’s no HTML. The canvas is created at runtime by in JavaScript, and is a simple “2d” rendering context. The CSS is designed to ensure the document and canvas both fill the viewport without overflowing (scrollbars kill the retro game vibe), and that the canvas remains pixelated. Anti-aliasing won’t do when we’re wanting to admire the natural shape of the pixels.</p><p>The JavaScript section has some constants at the top you can play with:</p><pre>// The resolution of the original NES!<br>const width = 256;<br>const height = 240;<br><br>// Our goal is 60 frames per second.  We can do anything we want if we can maintain this framerate.<br>const targetFPS = 60;</pre><p>The context will be filled out when we initialize the canvas. setPixel and clear would normally get socked away in a library file. setPixel uses the input coordinates to calculate the offset into the 1-dimensional array of pixel color values to know where to place the next color:</p><pre>const setPixel = (x, y, color) =&gt; {<br>  const offset = (y * context.width + x) * context.bpp;<br>  context.pixels[offset + 0] = color.r;<br>  context.pixels[offset + 1] = color.g;<br>  context.pixels[offset + 2] = color.b;<br>  context.pixels[offset + 3] = 255; // Alpha will always be set to opaque.<br>};</pre><p>The important thing here is remembering to multiply out not just by the width of the screen but the <em>stride</em>, width * bytes-per-pixel. I’m taking the easy solution for clearing the screen; a double-for-loop over the screen size that sets all pixels to a color. There are more efficient ways to accomplish this that we will probably cover later. The import bit to review here is the onResize function:</p><pre>/**<br> * On initial load, and on every resize, recalculate the size and position of the render canvas<br> * to match the requested aspect ratio.<br> */<br>const onResize = () =&gt; {<br>  const canvas = context.canvas;<br>  const aspectRatio = canvas.width / canvas.height;<br>  const heightFromWidth = window.innerWidth / aspectRatio;<br>  const widthFromHeight = window.innerHeight * aspectRatio;<br><br>  let offsetX = 0;<br>  let offsetY = 0;<br>  if (window.innerWidth &gt; widthFromHeight) {<br>    offsetX = (window.innerWidth - widthFromHeight) / 2;<br>  } else if (window.innerHeight &gt; heightFromWidth) {<br>    offsetY = (window.innerHeight - heightFromWidth) / 2;<br>  }<br>  <br>  canvas.style.inset = `${offsetY}px ${offsetX}px`;<br>  canvas.style.width = `calc(100% - ${offsetX * 2}px)`;<br>  canvas.style.height = `calc(100% - ${offsetY * 2}px)`;<br>};</pre><p>This function is responsible for ensuring the canvas remains centered and as large as possible without losing the aspect ratio we requested with the width and height constants. It runs on the initial load and on every resize, hooking into the window’s resize event.</p><p>The demo’s “game loop” is kicked off by the built-in requestAnimationFrame function, which we must call at the end of each frame, and calls onRenderFrame to manage the movement of our pixel across the screen. The rest of the code is well documented (by my tastes at least), so hopefully you can follow along.</p><p>Over the next several weeks I will be building up a pixel-based raster graphics library. Follow along with me; let’s dive into some awesome ’80s and ‘90s-era graphics algorithms!</p><p><em>Continue reading </em><a href="https://medium.com/@trey.tomes/sierpinskis-triforce-03c114e62238"><em>here</em></a><em> for an example of something interesting we can do with a simple pixel plotter.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03dd21dbf4e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>