<?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 Ethan Beddard on Medium]]></title>
        <description><![CDATA[Stories by Ethan Beddard on Medium]]></description>
        <link>https://medium.com/@ethan_beddard?source=rss-d0e54971b9de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_Xx0PS8XgKlZC6BwEq8pCw.png</url>
            <title>Stories by Ethan Beddard on Medium</title>
            <link>https://medium.com/@ethan_beddard?source=rss-d0e54971b9de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 17:11:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ethan_beddard/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[Visualising the Hydrogen Atom]]></title>
            <link>https://sciencespectrumu.com/visualising-the-hydrogen-atom-3c137c3083f9?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c137c3083f9</guid>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[blender]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-06-24T14:01:03.847Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What does an electron actually look like?</strong></h4><p>The honest answer is that it doesn’t look like anything.</p><p>An electron has no surface, no colour, no well-defined position. Until you measure it.</p><p>What quantum mechanics gives us instead is a <strong>probability density</strong>: a mathematical description of where an electron is likely to be found at any given moment. We call these probability distributions atomic orbitals, and they are among the most beautiful structures in physics.</p><p>The hydrogen atom, with its single proton and single electron, is the only neutral atom we can solve for exactly. With just two particles, it is a tractable two-body problem; in larger atoms, the interactions between many electrons create far more complex many-body problems, and exact solutions are no longer possible.</p><p>This makes hydrogen uniquely important: it is the universe’s simplest atom, and the foundation on which all of atomic physics is built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9_JfY6rzu5HpCHoUqm5yg.png" /><figcaption>n=6 l=2 m=1; Coloured by wavefunction sign.</figcaption></figure><h4>Quantum Numbers</h4><p>Every orbital is defined by three integers called quantum numbers:</p><ul><li><strong>n </strong>(=1, 2, 3, …): The <strong>principal</strong> quantum number, determining the <em>energy</em> level</li><li><strong><em>l</em></strong><em> </em>(0 to n-1): The <strong>angular</strong> momentum quantum number, determining the orbital’s angular momentum and characteristic <em>shape</em>.</li><li><strong>m</strong> (-l to +l): The <strong>magnetic</strong> quantum number, determining the <em>projection</em> of orbital angular momentum relative to some axis.</li></ul><p>These three numbers (plus <a href="https://quantumatlas.umd.edu/entry/spin/">spin</a>) uniquely identify every possible state of the hydrogen electron. The combination of n, l and m gives rise to an extraordinary variety of three-dimensional forms — from simple spheres to multi-lobed structures, toroids, and intricate geometries that honestly seem almost impossible for something so fundamental.</p><h4>Finding the Electron</h4><p>A question to ask now is:</p><blockquote>How do we actually solve for an electron’s probability density?</blockquote><p>Solving for this is fairly involved so I’ll give just an overview, however if you are interested in the maths there are many resources online.</p><p>If you’d rather skip to the graphics, just jump ahead to <strong>Rendering Probability.</strong></p><p>The starting point is the Schrödinger equation — quantum mechanics’ central equation of motion — applied to an electron bound to a proton by the Coulomb force (electrostatic attraction). Written in spherical coordinates (<em>r, θ, </em>φ), it is quite a formidable partial differential equation involving all three spatial dimensions at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9w6WVavZwNWN4uWhCfyVPA.png" /></figure><p>But there is a trick. Because the Coulomb potential depends only on <strong>r </strong>(the distance from the nucleus), and not on any direction, the solution separates cleanly into three independent parts: one for each coordinate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJLh748AmGSnGlvjMxUPFw.png" /></figure><p>This technique is called <em>separation of variables</em>, and it turns one nasty equation into three pretty ordinary ones, each of which describes a different aspect of the electron’s behaviour.</p><p>The <strong>azimuthal equation</strong> (in <strong>φ</strong>) is the simplest. Its solutions are complex exponentials. Now if we say that the wavefunction must return to the same value after a full rotation (i.e. P(φ) = P(φ + 2π)), we can lock the magnetic quantum number <strong>m</strong> to be an integer to satisfy this constraint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9uZimtxw1iNID8jqWUALMA.png" /></figure><p>The <strong>polar equation</strong> (in <strong>θ</strong>) is more involved, but its solutions are the <a href="https://mathworld.wolfram.com/AssociatedLegendrePolynomial.html">associated Legendre polynomials</a>, which are a family of special functions that arise when solving differential equations on a sphere.</p><p>Intuitively, they pop up here because the electron is not in a flat space, but on all possible directions around the nucleus, and any allowed wavefunction must “fit” smoothly over a spherical geometry without blowing up or becoming discontinuous.</p><p>Applying this requirement means only certain angular patterns are mathematically allowed, and this restriction is what quantises the solutions: it forces the angular momentum quantum number <strong><em>l</em> </strong>to <em>take only integer values.</em></p><p>The <strong>radial</strong> <strong>equation</strong> (in <strong>r</strong>) determines how the wavefunction behaves with distance from the nucleus, and this is where the energy levels are fixed. The solutions describe a function that decays as you move further away, reflecting the fact that the electron is bound to the proton.</p><p>Requiring the total probability to be finite and normalisable (i.e. that the electron must exist <em>somewhere</em> in space) forces only certain solutions to be allowed. This condition turns energy into a set of discrete values, giving the ladder of levels labelled by the principal quantum number <em>n</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2oH0p7tFQjI7IY0E1A2EA.png" /></figure><p>Energy is quantised because the electron behaves like a bound standing wave, and only wave patterns that <em>fit </em>consistently around the nucleus are allowed. Like a guitar string that can only vibrate at certain fixed frequencies as a standing wave, the electron can only exist in self-consistent wave patterns that reinforce rather than cancel themselves.</p><p>Classically, an orbiting charge could take any energy at all. Quantum mechanically, hydrogen’s electron is restricted to a fixed ladder of values — it cannot exist at arbitrary energies, only on discrete rungs. Higher <strong>n</strong> means less tightly bound, with the electron eventually escaping to freedom at E=0.</p><p>The radial equation also couples the energy level <strong>n</strong> and angular momentum quantum number <strong><em>l</em></strong>. To get a physical, normalisable solution, only values of <strong><em>l</em></strong> from 0 up to <strong>n — 1</strong> are allowed.</p><p>The full wavefunction is the product of all three parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoS3avABkQVszEL4Oq9j1g.png" /></figure><p>where Yₗₘ, a <em>spherical harmonic, </em>encodes the angular shape.</p><p>The <strong>probability density</strong> (how likely we are to find an electron at some point) is the most useful tool for visualising the electron, and mathematically is the squared modulus of the wavefunction, |<em>ψ</em>ₙₗₘ|².</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIwNKadfxfzIKPw0ieAufA.png" /><figcaption>n=1, l=0, m=0; Coloured by probability density. Quarter cut taken to see internal structure.</figcaption></figure><p>Each combination of (<strong>n, <em>l,</em> m</strong>) produces a distinct cloud. Adding more energy (increasing <strong>n</strong>) spreads the cloud outward and introduces <em>radial nodes: </em>concentric shells of zero probability. Changing<em> </em><strong><em>l</em></strong><em> </em>reshapes the cloud angularly, from spheres (<strong><em>l</em></strong>=0) to dumbbells (<strong><em>l</em></strong>=1) to clovers and toroids (<strong><em>l</em></strong>=2 and beyond). Changing <strong>m</strong> changes the angular structure and the orbital angular momentum projection along the chosen axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhS0whi0C-tCbx-svINfJA.png" /><figcaption>n=2, l=0, m=0; Coloured by probability density. Quarter cut taken to see internal structure.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s54axi_POxUHkXFuN_H6rA.png" /><figcaption>n=2, l=1, m=0; Coloured by probability density. Half cut taken to see internal structure.</figcaption></figure><h4>Rendering Probability</h4><p>There are lots of different ways to render this probability, for example:</p><ul><li>Plotting surfaces of constant probability (isosurfaces)</li><li>Slicing through the orbital to show 2D cross-sections of |ψ|²</li><li>Radial probability plots showing how likely the electron is to be found at a given distance</li><li>Density clouds where brightness or opacity represents probability magnitude</li></ul><p>The approach I took is slightly different, and is inspired by a Reddit <a href="https://www.reddit.com/r/blender/comments/1nctjg1/a_slideshow_of_electron_orbitals/">post</a> by user <a href="https://www.reddit.com/user/belugaborb/">belugaborb</a>.</p><p>We use a Monte Carlo sampling approach: generating many, many points within some volume, calculating the probability density at each point, and throwing it away if it’s below some threshold (not probable enough).</p><p>Now <a href="https://www.reddit.com/user/belugaborb/">belugaborb</a> used the distance from the origin to colour or scale each point. We’ve just found the probability density, though, so can use this to add an extra element of <em>accurate</em> information to the scene. Cuts can be taken into the orbital to look at the internal structure</p><p>Each point is then rendered as an instance of a small icosphere, using Blender’s point clouds and geometry nodes systems. As was just alluded to, the probability density was mapped to a ramp and the result was fed to colour and scale. An ambient occlusion shader gives the clouds a sense of depth, with occluded interior regions appearing darker than open exterior surfaces.<br>We can also look at the <em>sign</em> of ψ and colour accordingly, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coqf-9s9ef4QXTSs0Ga9CQ.png" /><figcaption>n=4, l=2, m=0; Coloured by probability density and ψ sign. Quarter cut taken to see internal structure.</figcaption></figure><h4>Interpretation</h4><p>These images are visualisations of |ψ|², not electron trajectories. Bright/dense regions indicate high probability of detection; dark/sparse regions are far less probable.</p><p>Crucially, this isn’t a map of one electron’s hidden path — it’s the pattern you’d see across many identical measurements on many identical hydrogen atoms. Each individual measurement gives a single point; only the ensemble builds up the cloud.</p><p>The quantum numbers can be read directly from the structure. <strong>n</strong> shows up as size and radial complexity: higher n spreads the cloud outward and introduces additional radial shells. <strong><em>l</em></strong> appears in the angular shape: spherical (<strong><em>l</em></strong> = 0), dumbbell (<strong><em>l</em></strong> = 1), clover-like (<strong><em>l</em></strong> = 2), etc. <strong>m</strong> affects the angular pattern of the orbital, changing how probability is distributed around a chosen axis.</p><p>Nodes (regions of zero probability) are key features of the images. Radial nodes appear as hollow spherical gaps, while angular nodes appear as planes or cones where probability cancels due to wave interference.</p><p>What you see is a map of standing-wave patterns in three dimensions, determined by the Schrödinger equation.</p><h4>Conclusions</h4><p>These renders turn the mathematics of hydrogen into tangible 3D structure. Each image is generated directly from the probability density, making the abstract solutions of Schrödinger’s equation visually accessible.</p><p>Fancy generating your own orbitals like these? The Blender add-on used to produce every visualisation in this article is <a href="https://ethanbeddard.com/shop/addons/hydrogen-orbitals">available here</a> — plug in your own n, l, m values and render the result.</p><p>Prefer ready-made images? A larger batch-rendered library is also available, covering thousands of variations in colour, background, and quantum numbers — perfect for teaching, presentations, or just admiring. <a href="https://ethanbeddard.com/shop/renders/hydrogen-orbital-renders-sample">Browse a substantial sample pack here.</a></p><h4>Gallery of Favourites</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkOlML1kczoWO3bU_y16xw.png" /><figcaption>n=5, l=1, m=0; Coloured by ψ sign</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TozpCbaOxf4npHHmBCCag.png" /><figcaption>n=5, l=0, m=0; Coloured by probability density</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9wqzIQgY74j_9waRtc45g.png" /><figcaption>n=5, l=2, m=1; Coloured by probability density. Half cut taken to see internal structure.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxVci-18Ubun5pem9laWSA.png" /><figcaption>n=5, l=4, m=0; Coloured by probability density. Half cut taken to see internal structure.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AufjZiNLoX0nii0JRZ4pzw.png" /><figcaption>n=7, l=4, m=0; Coloured by probability density. Quarter cut taken to see internal structure.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcfH41QG9rXWixd4sbRL5w.png" /><figcaption>n=6 l=2 m=1; Coloured by wavefunction sign.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c137c3083f9" width="1" height="1" alt=""><hr><p><a href="https://sciencespectrumu.com/visualising-the-hydrogen-atom-3c137c3083f9">Visualising the Hydrogen Atom</a> was originally published in <a href="https://sciencespectrumu.com/">Science Spectrum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continuous Spectra Are Weird]]></title>
            <link>https://sciencespectrumu.com/continuous-spectra-are-weird-5db69c044f16?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/5db69c044f16</guid>
            <category><![CDATA[rainbow]]></category>
            <category><![CDATA[spectrum]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[light]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 15:01:03 GMT</pubDate>
            <atom:updated>2026-02-23T15:01:03.500Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why finite atomic transitions produce smooth, continuous light</h4><figure><img alt="Rainbow falling on the hand of a person" src="https://cdn-images-1.medium.com/max/1024/0*hhk1f846OjB-YdlJ" /><figcaption>Photo by <a href="https://unsplash.com/@yingchih_hao?utm_source=medium&amp;utm_medium=referral">Yingchih</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>If atoms only have a finite number of electronic transitions, why can light be produced as a smooth, continuous spectrum rather than a finite set of colours?</blockquote><p>Take a typical electronic transition: an electron is excited to a higher energy level, then radiatively decays, emitting a photon. The energy of this photon equals the difference in energy between the two levels.</p><figure><img alt="Simple electronic transition process. An electron is excited up from ground state to a higher energy excited state, then radiatevely decays back down releasing a photon as it does so." src="https://cdn-images-1.medium.com/max/1024/1*-Vd2YaKo4-l8gf3zk7ALBw.png" /><figcaption>Simple electronic transition with a radiated photon. Image by Author.</figcaption></figure><p>There are only so many such transitions in a given atom. So how is it possible that we <em>can</em> observe a continuous spectrum of light, rather than just a set of discrete frequencies from the atoms we’re looking at?</p><h4>Multiplicity</h4><p>A naive way to think about it is to say that there are simply so many atoms, so many species, and so many possible transitions that the spectrum ends up <strong>looking continuous</strong>. At large scales, the density of spectral lines appears so high that they blur together into a smooth colour gradient.</p><p>This intuition points in the right direction, but it doesn’t <strong>fully</strong> explain what’s actually happening. The smoothness isn’t just a visual illusion from quantity alone. What we observe as continuity is really built from discrete processes combined with real physical phenomena that smear, overlap, and generate light across continuous ranges of frequencies.</p><figure><img alt="Start from a rectangular rainbow, then stretch it out sideways in both directions to reveal its really made from lots of little lines." src="https://cdn-images-1.medium.com/max/1024/1*R7WDoDP4YOcipKb0cex-tw.gif" /><figcaption>Zooming into a rainbow to show discrete frequency bands. In this example we omit other processes. Image by Author.</figcaption></figure><p>To put things into perspective, even a tiny puff of gas contains countless atoms. If the gas is pure, each atom produces the same discrete photons, so sheer numbers alone don’t create new colours. The real trick when it comes to this is diversity: ions, molecules, and atoms in different excited states each have their own sets of transitions. Layer them all together, and the spectrum becomes a dense forest of lines, so tightly packed that it already starts to look smooth to our eyes.</p><p>And that’s before we even consider how we observe it. Detectors, spectrometers, human eyes, and the like all have finite resolution. The gaps between individual lines can be smaller than what we can resolve, so we <strong>see</strong> a nice band of colour.</p><p>This is <strong>multiplicity</strong>: the diversity of atoms, ions, molecules, and excited states produces so many overlapping lines that the spectrum appears continuous, even though each photon comes from a discrete transition. It’s the first step toward the smooth spectra we observe.</p><h4><strong>True Continua</strong></h4><p>As you may have guessed, not all continuous light is the result of overlapping discrete lines. Some processes produce photons with <em>genuinely</em> continuous energies. In <strong>free–free emission</strong>, or Bremsstrahlung radiation, a free electron passing near an ion is accelerated by the Coulomb force, and it radiates a photon. Since the electron is unbound, its kinetic energy can take any value, and the emitted photon can carry any fraction of that energy. This phenomenon is also called <strong>braking</strong> radiation, since the electron loses energy (slows down) through the interaction.</p><p>Conversely, in <strong>free–bound emission</strong>, a free electron is actually <em>captured</em> into a bound state. The photon carries the sum of the electron’s kinetic energy <em>and the binding energy</em> of the final state. Because the initial kinetic energy is continuous, the resulting photon energies form a continuum.</p><figure><img alt="Left: Free-free emission. Electron travels towards an atom, and is deflected by Coloumb attraction, losing energy as it does so. Right: Free-bound emission. Electron comes in and instead of being scattered, it hops into an unoccupied energy level and is now bound, releasing some of its kinetic energy as it does so." src="https://cdn-images-1.medium.com/max/1024/1*Ulopi-2Hb2Tb0m3jO0AjOQ.gif" /><figcaption>Free-Free (Bremsstrahlung) emission vs Free-Bound emission. Image by Author.</figcaption></figure><p>These mechanisms produce smooth spectra even in the absence of multiplicity, and they become dominant in plasmas, stellar atmospheres, and other high-energy environments where <em>many</em> electrons are unbound or weakly bound.</p><h4><strong>Smearing</strong></h4><p>Even discrete transitions are <em>never perfectly sharp</em>. <strong>Doppler broadening</strong> comes from the thermal motion of atoms or ions. As particles move toward or away from the observer, the frequency of emitted photons shifts slightly due to the Doppler effect. Exactly the same idea as the change in pitch as a car drives past you. The result is that each spectral line spreads into a Gaussian profile whose width increases with temperature and decreases with atomic mass.</p><figure><img alt="Comparison showing the doppler shift for a particle thats stationary (green), one thats moving towards the oberver (blue) and one moving away (red)" src="https://cdn-images-1.medium.com/max/1024/1*DG20bH0aDcRvIWoNi0frrg.png" /><figcaption>Doppler shifting due to particle movement towards / away from the observer. Image by Author.</figcaption></figure><p><strong>Collisional and pressure broadening</strong> occur when nearby particles perturb the emitting atom or molecule. Frequent collisions change the energy levels slightly or shorten the excited state lifetime, spreading the emission over a larger range of frequencies. Denser and higher-pressure environments amplify this effect, making lines broader and less distinct.</p><p>Finally, <strong>natural linewidth</strong> arises from Heisenberg’s quantum uncertainty principle. An excited state with a finite lifetime Δt <em>cannot</em> have a perfectly defined energy. This gives each transition an intrinsic width ΔE ≈ ħ/Δt. Although small compared with other broadening mechanisms, it sets a fundamental limit on line sharpness.</p><h4><strong>Microstructure</strong></h4><p>Even a single atomic transition is rarely a single, isolated line. <strong>Fine structure</strong> arises from spin–orbit coupling: the interaction between an electron’s spin and its orbital motion splits energy levels into closely spaced sub-levels. This produces multiple lines from what was previously considered one transition.</p><p><strong>Hyperfine structure</strong> follows a similar idea, but comes from interactions between the nuclear magnetic moment and the magnetic field produced by the electrons, creating even finer splittings. External magnetic fields introduce <strong>Zeeman splitting</strong>, which shifts energy levels depending on the field orientation and strength.</p><p>Though these splittings are small compared with typical thermal or Doppler widths, they add internal detail to each line. When combined with multiplicity and smearing, they contribute to the richness of spectra.</p><h4><strong>Discrete to Continuous</strong></h4><p>Continuous spectra are the result of multiple layers of phenomena. Multiplicity gives us a dense forest of overlapping lines, true continua add genuinely smooth emission, smearing spreads lines across frequency, and microstructure adds subtle quantum detail.</p><p>Together, these effects turn discrete atomic and molecular processes into the smooth, uninterrupted light we see.</p><p><strong>So next time you see sunlight or switch on an incandescent light, keep this in mind!</strong></p><figure><img alt="Gif starting from a single ideal line and layering each of the effects to build up to a continum in the red freqency range" src="https://cdn-images-1.medium.com/max/800/1*mB17NvIFCIEzZorUiA-l6w.gif" /><figcaption>Layering of proccesses to build a continuous spectrum in the red frequency range. Image by Author.</figcaption></figure><p><em>Thanks for reading</em></p><h4>Happy Spectrum-Spotting!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5db69c044f16" width="1" height="1" alt=""><hr><p><a href="https://sciencespectrumu.com/continuous-spectra-are-weird-5db69c044f16">Continuous Spectra Are Weird</a> was originally published in <a href="https://sciencespectrumu.com/">Science Spectrum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Universe Is Left-Handed]]></title>
            <link>https://sciencespectrumu.com/nature-prefers-left-159583663dcb?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/159583663dcb</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 15:01:05 GMT</pubDate>
            <atom:updated>2026-02-05T15:01:05.892Z</atom:updated>
            <content:encoded><![CDATA[<h4>How the Wu Experiment in 1957 revealed that nature treats left and right differently</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rUnP_9jSF-lel1i6" /><figcaption>Photo by <a href="https://unsplash.com/@chase1211?utm_source=medium&amp;utm_medium=referral">Chase Kennedy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why Left and Right Feel Like They Should Be Equivalent</h4><p>Hold your hands up in front of a mirror. Your left hand becomes a right hand, your right becomes a left, but the physics looks unchanged. The motion is identical. Nothing about the behaviour seems to care.</p><p>This expectation goes far beyond mirrors. If you drop a ball, its mirror image falls the same way. If you build a mechanical device, a mirror-reversed version should still work. Even in physics experiments, orientation doesn’t usually matter. Flip the apparatus (reflect it in space), and the results don’t change.</p><p>That intuition hardened into something stronger: a belief that <strong>the laws of nature themselves don’t distinguish left from right</strong>.</p><p>For a long time, that belief was completely justified.</p><figure><img alt="A red ball bouncing forever infront of an ornate mirror, with its mirror image behaving exactly the same" src="https://cdn-images-1.medium.com/max/1024/1*BE6PAmZqPSUEHVD82EICWw.gif" /><figcaption>A bouncing ball and its mirror behaving physically identically. Image by Author</figcaption></figure><h4>Parity: The Symmetry That Felt Unavoidable</h4><p>Physicists gave this idea a formal name: <strong>parity symmetry</strong>.</p><p>Parity is the operation that flips spatial coordinates — left becomes right, front becomes back. If a law of physics is parity-symmetric, it means the law works exactly the same way in a mirror-reflected world.</p><p>By the middle of the 20th century, parity looked untouchable: every well-understood interaction respected it.</p><ul><li><strong>Gravity</strong> doesn’t care about orientation.</li><li><strong>Electromagnetism</strong> behaves the same way in mirror setups.</li><li><strong>The strong nuclear force</strong>, which binds protons and neutrons, shows no preference either.</li></ul><p>There were no known violations, no borderline cases. Parity conservation felt like a structural feature of reality.</p><p>And that confidence turned out to be the problem.</p><h4>The Weak Interaction and an Uncomfortable Gap</h4><p>The <strong>weak interaction</strong> is responsible for processes like <strong>beta decay</strong>, where a neutron turns into a proton and <strong>emits an electron</strong> and a neutrino. Compared to the other forces, it’s subtle and difficult to probe, but it plays a crucial role in nuclear and particle physics.</p><p>We encounter the weak interaction whenever nuclei change their identity, from radioactive beta decay to the nuclear reactions that power the Sun. It quietly governs how particles <em>transform</em>, rather than how they bind or repel, making its effects easy to miss but impossible to avoid.</p><p>In 1956, physicists <strong>Tsung-Dao Lee</strong> and <strong>Chen-Ning Yang</strong> noticed something strange. While parity had been tested everywhere else, no one had actually checked whether it held for weak interactions.</p><p>Not because anyone suspected a violation — but because nobody thought one was possible.</p><p>Lee and Yang pointed out that this was an assumption, not an experimental fact. They proposed concrete tests and suggested something radical: <em>the weak force might not respect mirror symmetry at all</em>.</p><p>If they were right, one of the most trusted symmetries in physics would fail.</p><h4>Wu’s Experiment: Turning Orientation Into a Measurable Quantity</h4><p>Testing parity in beta decay required a way to define direction at the <strong>nuclear</strong> level, not just in the material as a whole. This is why Chien-Shiung Wu’s experiment was so clever.</p><p>Wu used cobalt-60, whose nuclei have a <strong>non-zero net nuclear spin</strong>, giving them intrinsic angular momentum that can be aligned, and because it undergoes beta decay, which is a consequence of the weak interaction.</p><p><em>Nuclear</em> spin matters because beta decay occurs inside the nucleus; aligning electron spins alone, like in a household magnet, says nothing about the decay’s direction.</p><p>Spin is a quantum form of angular momentum, and nuclear spin responds to magnetic fields much like a tiny bar magnet. Each nucleus carries a small magnetic moment that tends to align with an applied field, defining a preferred direction in space.</p><p>At <em>ordinary </em>temperatures, however, this tendency is overwhelmed by thermal energy. Constant microscopic jostling randomises nuclear spin directions, which washes out any alignment. Only by <strong>cooling the material and applying a strong magnetic field</strong> can the nuclear spins be coaxed into lining up.</p><p>This is not unlike shaking a compass (adding ‘thermal energy’), then stopping (‘cooling it down’) and watching it return to pointing north. Or holding the compass to a fridge magnet and watching the needle align to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUXMGrrl58lalggcv6nG5w.gif" /><figcaption>Simple visualisation showing the effect of temperature and magnetic field on some non-zero spin nuclei. Note most align with the field but some do not. Image by Author.</figcaption></figure><blockquote>(I’ve included some useful links at the end of the article for readers who want a deeper understanding of quantum spin.)</blockquote><p>Wu cooled the cobalt to near absolute zero and applied a strong magnetic field, aligning the nuclear spins. This made “up” and “down” physically meaningful for studying nuclear decay.</p><p>Now came the key question:</p><blockquote>When cobalt-60 decays, which way do the electrons go relative to the nuclear spin?</blockquote><p><strong>If parity symmetry holds, the answer must be: <em>equally in both directions</em>.</strong></p><p>Wu measured the effect using electron detectors placed at opposite ends of a cobalt sample, aligned along the magnetic field. As cobalt-60 nuclei decayed, electrons were counted in both directions relative to the nuclear spin. Reversing the magnetic field flipped the spin direction, allowing the same apparatus to test whether the decay pattern reversed with it. This made it possible to define a left–right comparison without changing the experimental setup.</p><h4>The Prediction Parity Demands</h4><p>Parity symmetry doesn’t allow for a preference.</p><p>Electrons emitted during beta decay <em>should</em> be just as likely to emerge along the spin direction as against it.</p><p>Crucially, a mirror-reflected version of the experiment should produce the same statistics. That’s what parity means at a physical level.</p><p>Either nature respects the symmetry — or it doesn’t.</p><h4>How the Weak Force Breaks Parity</h4><p>Wu’s data was unambiguous.</p><p>Electrons were emitted <strong>preferentially opposite to the direction of the nuclear spin</strong>. The asymmetry was large, reproducible, and robust against experimental changes.</p><p>If you imagined the experiment in a mirror — flipping left and right — the outcome changed. The mirror world behaved differently.</p><p>This was not a small correction. It was a direct violation of parity symmetry.</p><p>The weak interaction, unlike every other known force, <strong>distinguishes left from right</strong>.</p><figure><img alt="A diagram showing three Cobalt-60 nuclei undergoing beta decay. Electrons emitted statistically more often in one direction. One under normal conditions normal space (more electrons down than up), one showing what we EXPECT to hapeen under parity transformation (more electrons down than up), and one showing what actually happened (more electrons up than down)." src="https://cdn-images-1.medium.com/max/1024/1*mXkGJA4uln7Br9hFX1SVtA.png" /><figcaption><strong>Left:</strong> Beta decay from a Cobalt-60 nucleus under an applied magnetic field. <strong>Right: </strong>Mirrored (under parity transformation) nucleus comparing expected result to Wu’s actual observations. Image by Author.</figcaption></figure><h4>What Kind of Symmetry Was Broken?</h4><p>The failure wasn’t in the experiment, and it wasn’t in quantum mechanics.</p><p>What broke was the idea that nature treats spatial reflections as equivalent. The weak interaction couples differently to particles depending on their <strong>handedness</strong>, or <strong>chirality</strong>.</p><p>In simple terms, particles have an internal orientation tied to their motion and spin. The weak force only interacts with <strong>left-handed particles</strong> and <strong>right-handed antiparticles</strong>.</p><p>This isn’t an accident of materials or energy scales. It’s built directly into the structure of the weak interaction itself.</p><p>Parity is not approximately violated. It is fundamentally violated.</p><h4>What “A Left-Handed Universe” Really Means</h4><p>This does not mean that everyday physics becomes skewed or asymmetric.</p><p>Most forces remain mirror-symmetric, and the world we experience still looks balanced. But it does mean something deeper.</p><blockquote>An exact mirror-image universe cannot physically exist.</blockquote><p>A true mirror world would require right-handed weak interactions instead of left-handed ones. That is not a symmetry transformation; it is a different set of laws. Parity violation doesn’t just mean left and right behave differently inside our universe; it means a perfectly mirrored version of reality is not permitted by physics itself.</p><h4>Why This Still Matters</h4><p>Parity violation reshaped modern physics. It forced a rewrite of weak-interaction theory, led directly to the V–A structure of the Standard Model and explains why neutrinos are fundamentally one-handed.</p><p>But its deeper impact was conceptual. It destroyed the assumption that symmetries must be intuitive to be real.</p><blockquote>Some of the most fundamental laws of nature only become visible when intuition fails and experimental evidence takes over.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mqQ4QmnVsSEa8CX2jyDZQ.jpeg" /><figcaption><a href="https://en.wikipedia.org/wiki/Chien-Shiung_Wu">Chien-Shiung Wu</a>. Image from Wikipedia Commons</figcaption></figure><p><em>Thanks for reading</em></p><h4>Happy symmetry-breaking!</h4><h4>Related Reading</h4><p><a href="https://en.wikipedia.org/wiki/Chien-Shiung_Wu">Chien-Shiung Wu</a></p><p>The Wu Experiment — <a href="https://en.wikipedia.org/wiki/Wu_experiment">Wikipedia</a> || <a href="https://www.youtube.com/watch?v=lHi5tZkwpAM">Dr Keating Video</a></p><p>Spin — <a href="https://quantumatlas.umd.edu/entry/spin/">The Quantum Atlas</a> || <a href="https://www.youtube.com/watch?v=ZhL7SWUYfwY">Stern-Gerlach Experiment (Let’s get complex video)</a> || <a href="https://www.feynmanlectures.caltech.edu/III_05.html">Feynman Lecture</a></p><p>The Weak Interaction — <a href="https://www.damtp.cam.ac.uk/user/tong/pp/pp4.pdf">Cambridge Notes</a> || <a href="https://www.youtube.com/watch?v=-gYeLHFr2LA">Fermilab Video</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=159583663dcb" width="1" height="1" alt=""><hr><p><a href="https://sciencespectrumu.com/nature-prefers-left-159583663dcb">The Universe Is Left-Handed</a> was originally published in <a href="https://sciencespectrumu.com/">Science Spectrum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Absurd Engineering of Your Phone Screen — LCDs]]></title>
            <link>https://medium.com/@ethan_beddard/the-absurd-engineering-of-your-phone-screen-8b47a93d330e?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b47a93d330e</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[phone]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[lcd]]></category>
            <category><![CDATA[display]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 09:01:58 GMT</pubDate>
            <atom:updated>2026-01-16T09:01:58.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Absurd Engineering of Your Phone Screen — LCDs</h3><figure><img alt="A zoomed in view of a screen’s pixels, focussing on the cursor" src="https://cdn-images-1.medium.com/max/1024/0*OAdQoMxUEp2X3PBz" /><figcaption>Photo by <a href="https://unsplash.com/@umby?utm_source=medium&amp;utm_medium=referral">Umberto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Right now, you’re staring at more microscopic shutters than there are hours in your life.</h4><p>Each one is controlled by its own transistor, flipping around 60 times per second. That’s about 15 flips in the blink of an eye. And you’re probably using it to watch cat memes.</p><p>Your phone screen has roughly <strong>3 million pixels</strong>, each split into red, green, and blue subpixels. That’s <strong>9 million tiny light “valves”</strong>, squeezed into the palm of your hand. Each one is narrower than a human hair and built with nanometre-scale precision.</p><p>Making a full-colour, moving image at this scale feels like magic.</p><p>It isn’t. But the way it works is still absurd.</p><h3>The Impossible Problem</h3><p>Let’s set the stage. What we’re trying to do is nothing short of unreasonable:</p><ul><li>Millions of independently controllable light elements.</li><li>Full colour.</li><li>Thin and flat.</li><li>Low power.</li></ul><p>Oh — and it needs to survive being dropped, sat on, and overheated in your pocket.</p><p>The real challenge is solving three problems at once.</p><p>First, how do we control light on a microscopic scale?<br><strong> Second, how do we do it precisely enough that colours don’t bleed or mix?</strong><br> Third, how do we do it fast enough for smooth motion?</p><p>The solution didn’t come from one field. It required materials scientists, semiconductor physicists, optical engineers, and chemists all solving different parts of the same puzzle.</p><p>Somehow, it all fitted together.</p><h3>Controlling Light (Without Making It)</h3><p>The hardest part wasn’t producing light, it controlling it. Making millions of tiny light sources would be too slow, too hot, and too complicated.</p><p>Instead, engineers started with a single uniform white backlight and asked a better question:</p><p>What if we just <strong>let the right photons through</strong> and block the rest?</p><p>The key idea is <strong>polarisation</strong>.</p><p>You’ve probably seen the demo: cross two polarising filters and the light disappears. Rotate one, and it comes back. That same trick — letting light through or blocking it based on orientation — is what LCDs use, scaled down to millions of pixels.</p><p>Of course, we can’t mechanically rotate a filter for every pixel.</p><p>So we need a material that can rotate polarisation <strong>electrically</strong>.</p><figure><img alt="A demonstration showing the effect of crossing two polarisers" src="https://cdn-images-1.medium.com/max/1024/1*0SAaObuPCMqzgEtXvmfaGA.gif" /><figcaption>Cross Polarisers Demonstration</figcaption></figure><h3>Enter Liquid Crystals</h3><p>Liquid crystals sit in a strange middle ground between liquids and solids. They can flow, but their molecules maintain a degree of rotationalorder.</p><p>The most useful type for displays is the <strong>nematic liquid crystal</strong>. Its rod-like molecules tend to align along a common direction, called the <em>director</em>. This ordered structure makes the material <strong>birefringent</strong> — its optical properties depend on orientation.</p><p>That’s exactly what we need.</p><p>To transmit light through two crossed polarizers sandwiching a material, the polarisation must rotate by 90° as it passes through the material.</p><p>So the goal becomes simple in principle: make the director rotate by 90° as we propagate through the liquid crystal layer.</p><p>This is done using a <strong>twisted nematic structure</strong>.</p><p>In this configuration, the molecules gradually twist from one surface to the other (this is done with minute ridges on the upper and lower substrates). Linearly polarised light entering the layer follows this twist, rotating as it travels through. By the time it reaches the second polarizer, it’s aligned — and passes through.</p><p>Apply a voltage, and the molecules align with the electric field. The twist disappears. The polarisation no longer rotates, and the second polarizer blocks the light.</p><p>No moving parts. Just controlled molecular alignment.</p><figure><img alt="Twisted Nematic Liquid Crystal under an applied electric potential — gif" src="https://cdn-images-1.medium.com/max/800/1*RhvHXeASQ4adkT6S5H4FIw.gif" /><figcaption>Twisted Nematic Liquid Crystal under an applied electric potential</figcaption></figure><p>The image above shows the polarisation of the light without the polarisers blocking the output.</p><blockquote>The liquid crystal is the <em>filling</em> and <strong>not</strong> the bread</blockquote><h3>What a Pixel Actually Looks Like</h3><p>A single LCD pixel is more complicated than it appears.</p><p>Each pixel contains three subpixels — red, green, and blue. Each subpixel is a layered structure made from:</p><ul><li>a pair of crossed polarisers</li><li>a liquid crystal layer</li><li>transparent electrodes</li><li>and the backlight</li></ul><p>The electrodes need to conduct electricity <em>and</em> let light through, so they’re usually made from <strong>indium tin oxide (ITO)</strong>.</p><p>Each subpixel is controlled by a tiny transistor that sets the voltage across the liquid crystal. That voltage determines how much the polarisation rotates, and therefore how much light gets through.</p><p>By independently controlling the red, green, and blue subpixels, each pixel can produce the full spectrum of colours.</p><figure><img alt="Schematic showing the layers of a LCD pixel" src="https://cdn-images-1.medium.com/max/1024/1*0zOQLFOr6MmcuxjcJKeFKQ.png" /><figcaption>Layered schematic of a LCD pixel</figcaption></figure><h3>Flipping Millions of Pixels — Fast</h3><p>Controlling one pixel is easy.</p><p>Controlling millions of them, dozens of times per second, is not.</p><p>Each subpixel sits on its own <strong>thin-film transistor (TFT)</strong>, acting like a microscopic switch. The display controller rapidly scans across the screen, updating voltages row by row.</p><p>The liquid crystal molecules don’t move instantly. Their viscosity limits how fast they can twist, which is why very fast motion can sometimes cause smearing or ghosting.</p><p>Still, the fact that this works at all is remarkable.</p><h3>How LCDs Are Actually Made</h3><p>Manufacturing an LCD is like building a microscopic sandwich, one layer at a time.</p><p>It starts with two glass substrates, polished and cleaned. Alignment layers are added and gently grooved to guide the liquid crystal orientation. Transparent electrodes are deposited and patterned.</p><p>TFTs are then fabricated using photolithography, with each one mapped to a single subpixel.</p><p>The two glass plates are sealed together, leaving a tiny gap. Liquid crystals are injected into this space, polarizers are added to the front and back, and finally the backlight is attached.</p><p>Every step must be nearly perfect. A single dust particle can ruin millions of pixels.</p><h3>Stepping Stones</h3><p>LCDs were just the beginning.</p><p>Since then, we’ve developed <strong>OLEDs</strong> (organic light-emitting diodes), <strong>QLEDs</strong> (quantum dot-enhanced LEDs), and <strong>microLEDs</strong>, each building on the idea of controlling light more precisely for brighter, sharper, and faster displays.</p><p>These advances aren’t limited to screens. The same principles are being applied to <strong>optical communications</strong>, where carefully controlled light carries information at incredible speeds.</p><h3>The Takeaway</h3><p>There’s nothing mystical about LCDs.</p><p>They work by carefully controlling the transmission of light.</p><p>What makes them impressive isn’t any single idea, but how many fragile, unintuitive physical effects have been engineered to work together, millions of times over, every second.</p><p>The next time you look at your phone, you’re not just seeing pixels.</p><p>You’re looking at one of the most elaborate optical systems ever mass-produced.</p><p><em>Thanks for reading!</em></p><blockquote><em>Happy scrolling!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b47a93d330e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to 3D Print a Guitar]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ethan_beddard/how-to-3d-print-a-guitar-1ec0b53712cf?source=rss-d0e54971b9de------2"><img src="https://cdn-images-1.medium.com/max/2248/1*L-afSfboqGoIKgSmhPILjg.png" width="2248"></a></p><p class="medium-feed-snippet">Tips, tricks and my experience</p><p class="medium-feed-link"><a href="https://medium.com/@ethan_beddard/how-to-3d-print-a-guitar-1ec0b53712cf?source=rss-d0e54971b9de------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ethan_beddard/how-to-3d-print-a-guitar-1ec0b53712cf?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec0b53712cf</guid>
            <category><![CDATA[3d-print]]></category>
            <category><![CDATA[guitar]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[3d-modelling]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 20:15:50 GMT</pubDate>
            <atom:updated>2025-06-08T20:17:31.263Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The Lattice Boltzmann Method (LBM) — Fluid Simulation]]></title>
            <link>https://medium.com/@ethan_beddard/the-lattice-boltzmann-method-lbm-fluid-simulation-43a4fa248614?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a4fa248614</guid>
            <category><![CDATA[science]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[lbm]]></category>
            <category><![CDATA[cfd]]></category>
            <category><![CDATA[fluid-dynamics]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 15:06:53 GMT</pubDate>
            <atom:updated>2025-06-05T14:46:19.128Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Lattice Boltzmann Method (LBM) — Fluid Simulation</h3><figure><img alt="Fluid simulation frame of the flow around a two-tone image of Ludwig Boltzmann" src="https://cdn-images-1.medium.com/max/1024/1*x5tjIHT4VYZAPzXzJZOBlQ.png" /><figcaption>Ludwig Boltzmann in my LBM fluid simulation</figcaption></figure><blockquote><a href="https://medium.com/@ethan_38158/the-lattice-boltzmann-method-lbm-fluid-simulation-43a4fa248614?source=friends_link&amp;sk=f9aace2dbdad21bdab721af7c7d64fcf">🌊 click this link to read for <strong>free </strong>🌊</a></blockquote><p>Fluid dynamics has captivated physicists for centuries. It has the potential to explain and predict massive hurricanes and raging seas, down to the delicate flow of blood through tiny capillaries in our brains.</p><p>There is generally no definite solution to real-world fluid dynamics problems, so we turn to <em>computational</em> fluid dynamics (CFD) to come to reasonable approximations. By numerically solving select governing equations, CFD allows us to simulate complex fluid flows, making it possible to predict and analyze phenomena that would otherwise be impossible to model directly.</p><p>A particular approach is the <strong>Lattice Boltzmann Method (LBM). </strong>Unlike more traditional CFD methods, the LBM models fluid flow by simulating the <em>discrete movement of particles on a lattice grid. </em>It offers a more intuitive approach with advantages in handling complex boundaries and <em>parallel computing</em>.</p><h3>Mathematical Foundation</h3><p>LBM models a fluid as a discrete lattice, each spatial node of which corresponds to some fictitious particle. The velocities for each of these particles are also discretised. These lattices are classified with the ‘DnQm’ notation, where we have ’n’ dimensions and ‘m’ discrete velocity directions and each direction has an associated weight.</p><figure><img alt="D2Q9 configuration for LBM" src="https://cdn-images-1.medium.com/max/1024/1*Kex4bVu6fSO8izjpXSr46w.png" /><figcaption>Diagram for a node in the D2Q9 system. White numbers are weights for each direction <em>eᵢ. Note: The middle one represents stationary.</em></figcaption></figure><p>The two core steps to LBM are <strong>streaming</strong> and <strong>collision</strong>. These steps evolve the density of the fluid at each lattice point over time. Density, like velocity, is discretized and is represented as a <em>distribution function ( f ) </em>at each lattice site, with values corresponding to the probability of particles occupying specific lattice directions.</p><p>Within the collision step, we need the macroscopic properties of the fluid at each lattice site, density <em>ρ </em>and velocity <em>u</em>. Local density is calculated by summing the ‘m’ values in our distribution function, and velocity by summing the product of values in our distribution function and lattice direction vectors, then dividing by the density.</p><figure><img alt="Density and velocity equations for LBM" src="https://cdn-images-1.medium.com/max/552/1*jOaNsBca7E1UlxDdoVODLA.png" /><figcaption>i for D2Q9 is the range 0..9, and indexes the discrete velocity directions</figcaption></figure><p>We take that the model relaxes to some equilibrium via collisions between particles in the fluid. This <em>equilibrium density function </em>for some direction <em>i</em> is used in LBM and we use its Taylor expansion to approximate. It is shown here with <em>ω </em>being weights for each direction based on the lattice geometry and <em>c</em> as the lattice speed.</p><figure><img alt="Equilibrium distribution function equation for LBM" src="https://cdn-images-1.medium.com/max/994/1*Q9otvxfGf3ptESm_b3Xm9Q.png" /></figure><h4>Collision</h4><p>In this step, we update the distribution functions <em>fᵢ </em>for each point on the lattice, based on a relaxation to the equilibrium distribution I just mentioned. The time constant <em>τ </em>controls how quickly it returns to equilibrium and is typically between 0.5 and 1.0 depending on the time step and fluid viscosity.</p><p>We get the ‘next’ distribution functions by using the following Bhatnagar-Gross-Krook (BGK) approximation:</p><figure><img alt="Collision step equation for LBM" src="https://cdn-images-1.medium.com/max/1002/1*fKZCkfJr0odYzgWwI9iX9Q.png" /></figure><h4>Streaming</h4><p>Now using these updated distribution functions, we can ‘stream’ our lattice sites. This is essentially re-distributing the components of a node’s distribution function by moving their values along their respective directions to neighbouring nodes.</p><figure><img alt="Streaming step equation for LBM" src="https://cdn-images-1.medium.com/max/664/1*TtV8cSIuVlXh14LyudIYGQ.png" /></figure><p>The distribution function <em>fᵢ </em>at some point x, is the fluid density at that point moving at a velocity of <em>eᵢ </em>per time step. Now after some time Δt, the next time step, it will have flowed along this velocity vector to x + <em>eᵢ. </em>This is the process streaming represents.</p><figure><img alt="GIF showing distribution values as vector lines, and following one of them through the collision and streaming process" src="https://cdn-images-1.medium.com/max/800/1*W6jfcYJUoQz3ojO6f9t9qQ.gif" /><figcaption>GIF showing LBM process between two nodes, following the north-east direction vector</figcaption></figure><p>These two equations, one for collision and one for streaming steps, are all you really need to write your own LBM solver.</p><h3>Boundaries</h3><p>If you want to do anything with fluid simulations, you will need some sort of boundary conditions. These can be quite tricky, but the LBM approach is very good for handling complex boundaries. We’ll look at three types: <strong>Bounce-Back</strong>, <strong>Zou-He</strong> (known velocity) and <strong>Zero Gradient.</strong> The implementation for these can be a bit lengthy, so I’ll give a brief overview just now and link some useful resources on each.</p><h4><strong>Bounce-Back</strong></h4><p>This condition in LBM is used to model <em>no-slip (zero velocity) </em>walls and is arguably the most simple boundary. When a particle distribution function ‘hits’ the boundary, it is <strong>reflected back upon the source</strong>, effectively reversing its direction. So for example, if <em>f</em>₁ hits a wall it becomes <em>f</em>₃.</p><figure><img alt="Diagram of bounce back boundary condition technique" src="https://cdn-images-1.medium.com/max/1024/1*nestgfkhCogVx_4f-2hjOA.png" /><figcaption>Diagram for process of the Bounce-Back boundary condition method</figcaption></figure><p>This creates zero velocity at the wall and can also be applied to complex geometries, although curved surfaces will often somewhat suffer in accuracy. <a href="https://sites.google.com/site/latticeboltzmannmethodcs205/home/boundary-conditions">Useful link</a>.</p><h4>Zou-He</h4><p>Something we frequently want to introduce is a flow inlet. With the method developed by<a href="https://pubs.aip.org/aip/pof/article-abstract/9/6/1591/260464/On-pressure-and-velocity-boundary-conditions-for?redirectedFrom=fulltext"> Zou and He (1997</a>) we can work out the ‘incomplete’ distribution function at the wall based on some macroscopic property (velocity OR density), the equilibrium function AND the existing parts of the function.</p><p>So for D2Q9, at the left wall inlet, we want to find f1, f5, and f8 so we use the density equation and known remaining parts of the distribution function (f0, f2, f3, f4, f6, f7) alongside our set velocity <em>u</em> and reconstruct our <em>f.</em></p><figure><img alt="Diagram for Zou-He condition on the left wall with inflow flowing right. After streaming, f1, f5 and f8 are ‘unknown’ so solve for this using known, values equilibrium function and velocity." src="https://cdn-images-1.medium.com/max/1024/1*Gy8gtTYeRZR_xiwgy_s_WA.png" /><figcaption>Diagram for Zou-He condition on the left wall with inflow flowing right. After streaming,<em> f1, f5 and f8 are ‘unknown’ so solve for this using ‘known’ values, equilibrium function and velocity.</em></figcaption></figure><p>A similar approach can be used if we have a set density instead of velocity, and this is often done for outflow.</p><h4>Zero Gradient</h4><p>The Zero Gradient condition assumes that we see no change in the given variable (velocity or pressure) along the boundary’s normal. It is implemented by copying distributions from the internal node next to the boundary. This method is pretty simple and computationally cheap however it is less accurate and can cause some instabilities when strong vortices are incident.</p><figure><img alt="Diagram of zero gradient boundary condition. We copy the red arrows from the fluid cell to the boundary cell." src="https://cdn-images-1.medium.com/max/1024/1*cRvvLO9asvB1aiGlrORAxw.png" /><figcaption>Diagram of zero gradient boundary condition. We copy the red arrows from the fluid cell to the boundary cell.</figcaption></figure><p>Essentially, whatever comes in, goes straight out. We often have ‘ghost’ cells around the boundary, so with this condition, we copy the inwards-facing values to the ghost cells in the wall which creates a zero gradient across it. <a href="https://homepages.abdn.ac.uk/jderksen/pages/lbm/ln03_pa.pdf">Useful link</a>.</p><figure><img alt="Examples of fluid simulations and what boundary conditions are in place. Left: Flow over airfoil, top and bottom are bounce-back, left is Zou He inflow and right is zero gradient outflow. Right: Lid driven cavity: Top wall is moving lid (Zou He) and rest are bounce-back no slip" src="https://cdn-images-1.medium.com/max/1024/1*q48BwYcbgP2KEx1eNl23DA.png" /><figcaption>Examples of boundary conditions in <strong>Left:</strong> Airfoil in wind tunnel and <strong>Right: </strong>Lid driven cavity in my fluid solver</figcaption></figure><h3>Creating Your Own LBM Simulation</h3><p>Now if you’re reading this article, chances are you’re considering writing your own LBM-based fluid simulation solver.</p><p>My advice?</p><p>Do it.</p><p>It’s great fun and I’ve learnt so much along the way, not only about fluid dynamics but also how to program in Rust and a bunch of graphics programming techniques to visualise my simulations (<a href="https://medium.com/@ethan_38158/lets-build-a-graphics-engine-in-rust-the-humble-triangle-8a207320afe2">Rust Graphics</a>).</p><p>It’s a little daunting starting off, so here’s a wee guide to get you started with a D2Q9 system.</p><blockquote><a href="https://medium.com/@ethan_38158/how-to-write-a-fluid-simulation-in-rust-lbm-1aaaee9c2a5a"><strong>More extensive guide can be found here</strong></a></blockquote><h4>Setup</h4><p>Start off with two 2D grids, where each cell represents a lattice node, Nx cells wide and Ny cells tall. We will toggle back and forth between reading and updating from each of these grids between each simulation step.</p><p>Each of these cells should store 9 floating point numbers corresponding to the 9 distribution function directions. Initially set them to 1.0 * <em>wᵢ, </em>where <em>wᵢ</em> is a weighting factor in each of these directions. These values are widely available <a href="https://en.wikipedia.org/wiki/Lattice_Boltzmann_methods#Example_Implementation"><em>(wiki is good for this)</em></a>. Consider adding a slight bit of noise to the 1.0 here for each cell, this helps speed up effects like vortex shedding.</p><p>Also create two more Nx * Ny 2D arrays, one for velocity (storing both horizontal and vertical velocity) and one for density. <em>(This is not strictly necessary as we calculate velocity and density in each simulation step anyway but it makes visualising somewhat easier.)</em></p><p>Next, set up visualisation as this will allow you to quickly debug and see if everything&#39;s working ok. Start with, for example, drawing a square for every grid cell, and fill it with a colour proportional to the magnitude of velocity in that cell.</p><h4>Simulation</h4><p>Now let us work on the actual simulation. In one step, we will read from grid A, and write to grid B (then swap in the next step).</p><p><strong>Collision</strong></p><p>For each cell, for each of the 9 directions, we store the new value for the distribution function <em>f*ᵢ, </em>using the currently stored density and velocity values for this cell.</p><p><strong>Streaming</strong></p><p>Next, for each cell and each direction again, we set the cell’s value in the current direction to the corresponding value we’ve just calculated from the collision step.</p><p>Also, we need to impose some boundaries at the walls so that we don’t exceed the indices of our storage structures. For now, just loop from one edge of the grid to the other if the ‘target’ <em>(i.e. the cell in the direction we’re currently looking in) </em>is past the edge.</p><p><strong>Macroscopic Variables</strong></p><p>After streaming, we need to update density and velocity values for each cell before the next simulation step. This is a simple task of summing distribution function values etc. as described earlier.</p><p>Now swap grids and repeat!</p><p>Here is a naïve approach in pseudocode:</p><pre>grid1 = Arrayf32[Nx][Ny][9]<br>grid2 = Arrayf32[Nx][Ny][9]<br><br>densityGrid = Arrayf32[Nx][Ny]<br>velocityGrid = Arrayf32[Nx][Ny][2]<br><br>w = [1/36, 1/9, 1/36, 1/9, 4/9, 1/9, 1/36, 1/9, 1/36]<br>e = [[-1,1], [0,1], [1,1], [-1,0], [0,0], [1,0], [-1,-1], [0,-1], [1,-1]]<br><br>tau = 0.55<br><br>sim_step(gridA, gridB) {<br><br>  //collide<br>  foreach cell{<br>    density = densityGrid[cell]<br>    velocity = velocityGrid[cell]<br>    for i in 0..9{<br>      eq = compute_equilibrium(gridA, density, velocity, w, e)<br>      gridA[cell][i] = collide(eq, gridA[cell][i], tau)<br>    }<br>  }<br><br>  //stream<br>  foreach cell{<br>    for i in 0..9 {<br>      target = cell + e[i]<br>      if target_out_of_bounds() {<br>        target = target_wrap_to_in_bounds()<br>      }<br><br>      gridB[cell][i] = gridA[target][i]<br>    }<br>  }<br><br>  //macroscopic variables<br>  foreach cell{<br>    densityGrid[cell] = compute_density(gridB[cell])<br>    velocityGrid[cell] = compute_velocity(gridB[cell], density)<br>  }<br>}<br><br>//initial condition<br>grid1.fill(1.0 * w * random(0.99,1.11))<br>grid2.fill(1.0 * w * random(0.99,1.11))<br><br>grid1[Nx/2][Ny/2] = 2.0 * w // start with one dense point in middle<br><br>toggle = true<br>for step in 0..steps {<br>  if toggle {<br>     sim_step(grid1, grid2)<br>  } else {<br>     sim_step(grid2, grid1)<br>  }<br>  visualise()<br>}</pre><p>There we have it. A brief overview of the LBM approach to fluid simulations and an insight into how to implement it.</p><figure><img alt="GIF of fluid flow over the letters LBM" src="https://cdn-images-1.medium.com/max/800/1*BVZ22oHOgaP-feSJTggxPg.gif" /><figcaption>GIF of my LBM based 2D fluid simulation engine with ‘LBM’ as solid boundaries</figcaption></figure><blockquote><a href="https://medium.com/@ethan_38158/how-to-write-a-fluid-simulation-in-rust-lbm-1aaaee9c2a5a"><strong>More extensive simulation guide can be found here</strong></a></blockquote><blockquote>Happy Simulating!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a4fa248614" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write a Fluid Simulation in Rust — Lattice Boltzmann Method]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ethan_beddard/how-to-write-a-fluid-simulation-in-rust-lbm-1aaaee9c2a5a?source=rss-d0e54971b9de------2"><img src="https://cdn-images-1.medium.com/max/2022/1*xx0pj887MOnkWAYugBtetQ.png" width="2022"></a></p><p class="medium-feed-snippet">Fluid simulations are at the heart of many scientific and engineering applications, from modelling airflow around vehicles to simulating&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@ethan_beddard/how-to-write-a-fluid-simulation-in-rust-lbm-1aaaee9c2a5a?source=rss-d0e54971b9de------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ethan_beddard/how-to-write-a-fluid-simulation-in-rust-lbm-1aaaee9c2a5a?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aaaee9c2a5a</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[fluid-dynamics]]></category>
            <category><![CDATA[lbm]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 15:04:36 GMT</pubDate>
            <atom:updated>2025-01-17T15:08:06.654Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[If I Peed off the Wall in Game of Thrones, Would it Freeze before Hitting the Ground?]]></title>
            <link>https://medium.com/curious-calculations/if-i-peed-off-the-wall-in-game-of-thrones-would-it-freeze-before-hitting-the-ground-09e0cf8f993a?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/09e0cf8f993a</guid>
            <category><![CDATA[questions]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[thermodynamics]]></category>
            <category><![CDATA[funny]]></category>
            <category><![CDATA[game-of-thrones]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 13:59:22 GMT</pubDate>
            <atom:updated>2025-01-12T14:21:53.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bt253W9NUGk_Q7vob_zSRA.jpeg" /><figcaption>Tyrion peeing off the wall in Game of Thrones S1E3</figcaption></figure><p>I was watching <em>Game of Thrones</em> the other day, and there’s a scene where Tyrion pees off the top of the Wall. It got me wondering — would the pee freeze before hitting the ground? Naturally, I had to find out.</p><h4>Let’s first define the parameters of the problem.</h4><p>As all physicists do, we’ll make a slight assumption to make everything much easier. Let’s examine a single, <strong>2mm radius spherical droplet</strong> of the pee stream. This is a reasonable approximation to make since the stream isn’t perfectly laminar and will split up into droplets anyways, which is something I’m sure you have witnessed yourself.</p><p>The Wall in Game of Thrones is about <a href="https://gameofthrones.fandom.com/wiki/Wall#:~:text=Measurements%20in%20the%20Seven%20Kingdoms,in%20width%20(91%20meters)."><strong>213 meters tall</strong></a>, and we will assume an air temperature of <strong>-20°C </strong>in the winter season <em>based on </em><a href="https://archerkhill.medium.com/game-of-thrones-climate-and-weather-the-north-b51ae597ac42"><em>this article by</em><strong><em> </em></strong><em>Archer K Hill II</em></a>. Our bodies are about <strong>37°C</strong>, so we will take this as the initial temperature of the stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0ndBeXJJ8LWwBXto3y7tw.png" /><figcaption>Diagram of our problem</figcaption></figure><p>This is all the info we need so let’s crack on with the problem!</p><h3>Stream Trajectory</h3><p>To see if the pee will freeze before reaching the ground, we need to work out how long it will take to fall the height of the wall.</p><p>Often in physics problems, we ignore forces due to air resistance but here we will include it. This is because:</p><ol><li>Drag limits acceleration, leading to terminal velocity, which affects descent time</li><li>I don’t yet know how it will compare to the time it takes to cool, so having this extra bit of accuracy may come in useful.</li></ol><p>The forces acting upon the droplet at a moment in time would look like the following, with gravity down and drag opposing the direction of motion. We can say that the horizontal component of velocity here is negligible, so the drop falls straight down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXKNHueFMqlZ8BR0yV-lsA.png" /><figcaption>Diagram showing forces acting on our droplet</figcaption></figure><p>We can write our total force as the sum of these two, and rewrite in terms of velocity with Newton’s trusty second law.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXyTQ7np-oE0mFRAzpzI1w.png" /></figure><p>This is a <strong>nonlinear first-order separable differential equation</strong>, and can be solved by separating variables and integrating as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKmPpL_2kI6d9_GCCNXVXg.png" /></figure><p>Great! We have the velocity as a function of time, and to get the position we just integrate again to get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*Egz20M8n1nogJI-MU_cZyw.png" /></figure><p>Now our droplet will hit the ground when y is equal to the height of the wall: y = 213. Here I’m using 0.5 as the drag coefficient for the sphere .We could solve for t but for brevity&#39;s sake, I will just quote the value given when I plug the equation into <a href="https://www.desmos.com/calculator/e18hxqg85g">Desmos</a>.</p><blockquote>The pee droplet will hit the ground after <strong>23.7 seconds</strong></blockquote><h3>Stream Temperature</h3><p>The temperature of the stream starts at 37°C, and we want to find how long it takes to freeze. There are two stages to this: <strong>Cooling</strong>, where we cool down to 0°C and then <strong>Freezing</strong>, where we must get rid of latent heat to actually freeze completely.</p><p>It’s pretty snowy in the north in Game of Thrones, so let’s assume we’re well hydrated and our pee can be considered to be just water.</p><p>We can do so, using Newton’s cooling law with heat transfer rate, and solving another differential equation for T, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wX2DILfKZ3jZkwG-NTBFEg.png" /></figure><p>We have all the information we need here apart from the value for <em>h</em>. This is the <em>heat transfer coefficient </em>and is is a measure of the ability of a material or surface to conduct heat. It’s dependent on factors such as flow regime (laminar vs turbulent), the fluid’s own properties and even how rough the surface is.</p><p>The heat transfer coefficient varies from scenario to scenario and lets us take into account forced convection due to the droplet’s motion through the air.</p><p>For our case, we can use the <strong>Nusselt number</strong> <em>Nu</em> for spherical particles and is the ratio of total heat transfer to conductive heat transfer. The Nusselt number is related to the <strong>Reynolds number</strong> <em>Re</em>, which describes the flow regime around the droplet which we will also calculate as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrwUYQ9QG6Quw94tf-vCIg.png" /></figure><p>Working things through, <em>using the density of air at -20°C</em> <em>not ambient, </em>we get a heat transfer coefficient <strong>h = 179.2.</strong></p><h4>Freezing</h4><p>We now need to extract the latent heat when the water is at its freezing point 0°C. This is done with heat transfer rate in steady-state conditions where the surface temperature is 0°C.</p><p><em>Q = m Lf​:</em> The total amount of heat that must be removed to freeze the raindrop, where <em>Lf​</em> is the latent heat of fusion of water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaNht_DHOxcnB_mLaBRrMA.png" /></figure><p>Now I have taken some liberties here, factors such as a changing <em>h</em> value, heat loss due to evaporation and the fact that the droplet freezes from the outside in not evenly have all been someone disregarded. These characteristics are a bit out of the scope of this wee article, and with the approximated calculations we can get the info we need.</p><h3>Results</h3><p>From my calculations:</p><ul><li>Time to hit the ground: <strong>23.7s</strong></li><li>Time to cool to 0°C: <strong>16.26s</strong></li><li>Time to freeze after reaching 0°C: <strong>61.9s</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRsNm_qXvHPTCFq4anujFg.png" /><figcaption><a href="https://www.desmos.com/calculator/e18hxqg85g">Desmos Graph</a> of Red: Droplet trajectory, Blue: Cooling curve, Purple: point at which the droplet has frozen</figcaption></figure><p><em>This means that if I were to pee off the wall in game of thrones:</em></p><h3>The Pee would be Partially Frozen when it hits the Ground</h3><p>Comparing this to reality, it would be like <em>freezing rain: </em>where cooled rain freezes almost instantly on contact with the ground.</p><blockquote>Now remember, never eat yellow snow.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09e0cf8f993a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/curious-calculations/if-i-peed-off-the-wall-in-game-of-thrones-would-it-freeze-before-hitting-the-ground-09e0cf8f993a">If I Peed off the Wall in Game of Thrones, Would it Freeze before Hitting the Ground?</a> was originally published in <a href="https://medium.com/curious-calculations">Curious Calculations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It Would Take Longer to Drink an Olympic Swimming Pool Than to Run to the Sun]]></title>
            <link>https://medium.com/curious-calculations/it-would-take-longer-to-drink-an-olympic-swimming-pool-than-to-run-to-the-sun-cd807f5fb9a3?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd807f5fb9a3</guid>
            <category><![CDATA[funny]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[olympics]]></category>
            <category><![CDATA[space]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 13:07:59 GMT</pubDate>
            <atom:updated>2024-12-26T13:09:53.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QpM2BPCC1nqCUn3T" /><figcaption>Photo by <a href="https://unsplash.com/@bradenegli?utm_source=medium&amp;utm_medium=referral">Braden Egli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever wondered if you could drink an entire Olympic swimming pool? Surprisingly, it would take longer to do that than it would to run all the way to the Sun.</p><blockquote>Bonkers, I know.</blockquote><p>An Olympic swimming pool is a whopping 2,500,000 litres when full, or about 660,000 gallons. It would take your kitchen tap almost a <strong><em>full year</em></strong> to fill up <em>(according to </em><a href="https://assets.publishing.service.gov.uk/media/5a807d8ded915d74e622ec1a/gbs-taps-automatic-sprays-showers-urinal-2015.pdf"><em>UK standards</em></a><em>)</em>.</p><p>Let’s assume that some person can drink 3 litres per day (about 0.66 gallons), and they do so consistently. This is generally accepted to be the upper end of what’s safe to drink within reason, although our body is good at getting rid of excess if need-be.</p><h3>This means that it would take 2283<strong> years</strong> to drink an Olympic swimming pool!</h3><p><em>(2,500,000 litres / 3 litres per day / 365 days per year)</em></p><blockquote><strong>The current distance to the Sun is 147.13 million km</strong></blockquote><p>This is an inconceivable distance for our brains to comprehend, no matter how hard we try. Nevertheless, let’s strap on our running shoes and get a move on.</p><p>Now assume we run at an average of 10 kilometers per hour, and we can ignore the relative movement of planetary bodies and the harshities of space.</p><h3>It would take 1680 years to run to the Sun!</h3><p><em>(147,130,000 km / 10 km per hour / 16 hours per day / 365 days per year)</em></p><blockquote><strong>This is a 603 year difference.</strong></blockquote><p>By the time we’ve reached the sun, the pool will still be 26% full.</p><p>In the last 600 years, ~20 entire generations have passed, revolutions have been incited and a basis for modern science was developed<em> (assuming we start from copernicus in 1543). </em>Hell, we could even build and collapse a Roman empire in that time, with still change left over.</p><p><em>As a side note, there are actually about </em><a href="https://pumas.nasa.gov/examples/how-many-days-are-year"><em>365.24 days in a year</em></a><em>, so taking this into account it would really take 1.5 less years to drink the pool, and 1.1 fewer to run to the Sun.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd807f5fb9a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/curious-calculations/it-would-take-longer-to-drink-an-olympic-swimming-pool-than-to-run-to-the-sun-cd807f5fb9a3">It Would Take Longer to Drink an Olympic Swimming Pool Than to Run to the Sun</a> was originally published in <a href="https://medium.com/curious-calculations">Curious Calculations</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Build a Graphics Engine in Rust — Traversing the Third Dimension]]></title>
            <link>https://medium.com/@ethan_beddard/lets-build-a-graphics-engine-in-rust-traversing-the-third-dimension-930ad4a356d6?source=rss-d0e54971b9de------2</link>
            <guid isPermaLink="false">https://medium.com/p/930ad4a356d6</guid>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[computer-graphic-design]]></category>
            <dc:creator><![CDATA[Ethan Beddard]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 22:43:03 GMT</pubDate>
            <atom:updated>2024-12-22T22:43:03.627Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build a Graphics Engine in Rust — Traversing the Third Dimension</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_j3u6LG5d6QkVGHgpYQgiA.png" /><figcaption>Blender Render</figcaption></figure><p>In 3D graphics, the camera is our window into a virtual world, turning abstract geometry into something we can see and explore. It’s easy to get lost in jargon like “projection matrices” and “clipping planes,” but at its heart, a camera is just the way we manipulate vertices to show position and give the illusion of depth on our 2D screen.</p><p>In <a href="https://medium.com/@ethan_38158/lets-build-a-graphics-engine-in-rust-the-humble-triangle-8a207320afe2">part one</a> of this wee series, we created the foundation for a graphics engine in rust, using <a href="https://wgpu.rs/">wgpu</a> and <a href="https://github.com/rust-windowing/winit">winit</a> frameworks. We’re going to build off of this code today, bringing our scene to life with an <strong>interactive camera</strong> and a<strong> third dimension.</strong></p><p><em>Full code on </em><a href="https://github.com/ejb004/render-engine-wgpu"><em>GitHub</em></a></p><p>From the point of view of a vertex, the camera is just a 4x4 transformation matrix that when applied, adjusts the vertex position on screen. This matrix contains information on how to scale, skew, rotate, translate and or project a vertex and can be split up into the product of each individual type of transformation (the order does matter!). We multiply this matrix by the vertex position in the vertex shader to get the resultant transformed vector.</p><p>For example, a <em>translation </em>matrix looks like this, where we move a vertex by (dx, dy, dz):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7M4-bBxsa0kzuHbMneWwPw.png" /><figcaption>Vertex translation matrix.</figcaption></figure><p>If you fancy learning more about the maths involved, <a href="https://developer.unigine.com/en/docs/latest/code/fundamentals/matrix_transformations/index?rlang=cpp">Uniengine</a> and <a href="https://medium.com/@jrespinozah/3d-graphics-the-perspective-projection-d2076f42cdf3">this article by Juan Espinoza</a> are great resources.</p><p>Ok. Enough maths. Let’s do some coding. We will create an orbital camera, where we can rotate it about a spherical shell centered on a target/focal point.</p><pre>pub struct OrbitCamera {<br>    pub distance: f32,<br>    pub pitch: f32,<br>    pub yaw: f32,<br>    pub eye: Vector3&lt;f32&gt;,<br>    pub target: Vector3&lt;f32&gt;,<br>    pub up: Vector3&lt;f32&gt;,<br>    pub bounds: OrbitCameraBounds,<br>    pub aspect: f32,<br>    pub fovy: Rad&lt;f32&gt;,<br>    pub znear: f32,<br>    pub zfar: f32,<br>    pub uniform: CameraUniform,<br>}</pre><p>We’re storing a lot of information here but it’s all pretty straight forward *deep breath*: d<em>istance, pitch</em> and <em>yaw</em> are the current physical characteristics of the camera, <em>eye </em>and<em> target </em>is where the camera is and where it should be looking at, <em>up </em>will be just +z here, <em>bounds </em>is a wee struct that stores the min and max of the first three attributes, <em>aspect </em>and <em>povy</em> are the aspect ratio and field of view of the camera,<em> znear </em>and<em> zfar </em>are the near and far clipping planes and finally, <em>uniform </em>stores our position and projection matrices.</p><p>In the <em>OrbitCamera</em> we need functions to set, and add to distance, pitch and yaw, but these are fairly trivial and the information on this kind of camera movement is widely available so I’ll leave it out for now.</p><p>A specific feature that would be useful is to <strong>pan</strong> the camera, ie. move it up/down and left/right along the axis of our viewing angle (hence changing our target point). We do this with this function:</p><pre>pub fn pan(&amp;mut self, delta: (f32, f32)) {<br>    self.eye.y += delta.1 * self.distance;<br>    self.target.y += delta.1 * self.distance;<br>    // println!(&quot;{:?}&quot;, self.distance);<br><br>    let forward = (self.target - self.eye).normalize();<br><br>    let cross = forward.cross(self.up).normalize();<br><br>    self.eye -= cross * delta.0 * self.distance;<br>    self.target -= cross * delta.0 * self.distance;<br>}</pre><p><em>Delta</em>, is the change in xy mouse position which we will receive in events from the event loop. Seaking of, lets sort that now. In our <em>RenderEngine</em> object, we can stick in the following function, and call it from the device event function described by winit’s application handler.</p><pre>impl ApplicationHandler for App {<br>    //... <br>    fn device_event(<br>          &amp;mut self,<br>          event_loop: &amp;winit::event_loop::ActiveEventLoop,<br>          device_id: winit::event::DeviceId,<br>          event: winit::event::DeviceEvent,<br>      ) {<br>          let (Some(window), Some(render_engine)) =<br>              (self.window.as_ref(), self.render_engine.as_mut())<br>          else {<br>              return;<br>          };<br>  <br>          render_engine.process_event(&amp;event, &amp;window);<br>      }<br>}</pre><pre>impl RenderEngine{<br>    //... <br>    pub fn process_event(&amp;mut self, event: &amp;DeviceEvent, window: &amp;Window) {<br>        self.camera_controller<br>            .process_events(event, window, &amp;mut self.camera);<br>    }<br>}</pre><p>Our camera controller is a struct stored by the render engine (so is the orbit camera) and it looks a bit like this:</p><pre>pub struct CameraController {<br>    pub rotate_speed: f32,<br>    pub zoom_speed: f32,<br>    is_drag_rotate: bool,<br>    is_pan: bool,<br>}<br><br>impl CameraController {<br>    pub fn new(rotate_speed: f32, zoom_speed: f32) -&gt; Self {<br>        Self {<br>            rotate_speed,<br>            zoom_speed,<br>            is_drag_rotate: false,<br>            is_pan: false,<br>        }<br>    }<br><br>    pub fn process_events(<br>        &amp;mut self,<br>        event: &amp;DeviceEvent,<br>        window: &amp;Window,<br>        camera: &amp;mut OrbitCamera,<br>    ) {<br>        match event {<br>            DeviceEvent::Button {<br>                button: 0, // The Left Mouse Button on macos.<br><br>                state,<br>            } =&gt; {<br>                let is_pressed = *state == ElementState::Pressed;<br>                if self.is_pan {<br>                    self.is_pan = is_pressed;<br>                } else {<br>                    self.is_drag_rotate = is_pressed;<br>                }<br>            }<br>            DeviceEvent::MouseWheel { delta, .. } =&gt; {<br>                let scroll_amount = -match delta {<br>                    // A mouse line is about 1 px.<br>                    MouseScrollDelta::LineDelta(_, scroll) =&gt; scroll * 1.0,<br>                    MouseScrollDelta::PixelDelta(PhysicalPosition { y: scroll, .. }) =&gt; {<br>                        *scroll as f32<br>                    }<br>                };<br>                camera.add_distance(scroll_amount * self.zoom_speed);<br>                window.request_redraw();<br>            }<br>            DeviceEvent::MouseMotion { delta } =&gt; {<br>                if self.is_drag_rotate {<br>                    camera.add_yaw(-delta.0 as f32 * self.rotate_speed);<br>                    camera.add_pitch(delta.1 as f32 * self.rotate_speed);<br>                    window.request_redraw();<br>                } else if self.is_pan {<br>                    camera.pan((<br>                        delta.0 as f32 * self.rotate_speed / 2.0,<br>                        delta.1 as f32 * self.rotate_speed / 2.0,<br>                    ));<br>                    window.request_redraw();<br>                }<br>            }<br>            _ =&gt; (),<br>        }<br>    }<br>}</pre><p>This admittedly looks a little daunting at first, but it’s really not too bad. All we do, is check for say mouse motion and if the mouse is currently being pressed, call our camera add pitch/yaw functions. The <em>delta</em> we get from the event here, is how much the mouse’s position has changed since the last frame.</p><p>With that, our camera is done. However, there is a glaring problem. We’re not sending any of this information to the GPU! That’s where <strong>uniform buffers</strong> come in. Uniform buffers are small batches of read only information that is efficiently shared to the GPU. They are designed specifically with tasks like camera projections and model transformations in mind.</p><p>In our <em>RenderEngine::new() </em>function, lets create a camera and a global uniform buffer object (UBO), representing any data we want globally in our scene on the gpu which in this case is just the camera. These will be stored within the render engine struct.</p><pre>let mut camera = OrbitCamera::new(<br>            1.0,<br>            0.0,<br>            0.0,<br>            Vector3::new(0.0, 0.0, 0.0),<br>            width as f32 / height as f32,<br>        );<br>camera.bounds.min_distance = Some(1.1);<br>let camera_controller = CameraController::new(0.005, 0.1);<br><br>let global_ubo = GlobalUBO::new(&amp;device);<br>let mut global_bindings = GlobalBindings::new(&amp;device);<br>global_bindings.create_bind_group(&amp;device, &amp;global_ubo);</pre><p>Now here I am pulling the later functions out of thin air. In preperation for this I made some general functions to create buffers, uniforms, bind groups etc and put them in a folder called <em>wgpu_utils. </em>Feel free to just copy paste them from <a href="https://github.com/ejb004/render-engine-wgpu/tree/main/the-camera/src/wgpu_utils">github</a>, as it is a lot to cover for one article and I want to keep things interesting.</p><p>We also need to update our camera bits and bobs when <em>update() or resize()</em> is called, which are called when we redraw or resize the window respectively.</p><pre>pub fn update(&amp;mut self) {<br>        // NEW<br>        self.camera.update_view_proj();<br>        update_global_ubo(&amp;mut self.global_ubo, &amp;self.queue, self.camera.uniform);<br>    }<br><br>pub fn resize(&amp;mut self, width: u32, height: u32) {<br>    self.config.width = width;<br>    self.config.height = height;<br>    self.surface.configure(&amp;self.device, &amp;self.config);<br><br>    // NEW<br>    self.camera.resize_projection(width, height);<br>}</pre><p>Currently our pipeline layout does not support the uniform buffer, but I will leave this as an exercise for you to do ;) <em>(Hint: we had a similar problem when introducing verticies in part 1)</em></p><p>Whenever we render a frame, this data still needs to be presented to the gpu, we do this with just a simple line of code when we are doing our pass.</p><pre>render_pass.set_bind_group(0, self.global_bindings.bind_groups(), &amp;[]);</pre><p>In our shader, we can now add the following code to take in a <em>Camera</em> object from bind group 0, binding 0, which we have just passed in.</p><pre>// In shader.wgsl<br>struct Camera {<br>    view_pos: vec4&lt;f32&gt;,<br>    view_proj: mat4x4&lt;f32&gt;,<br>}<br><br>@group(0) @binding(0)<br>var&lt;uniform&gt; camera: Camera;</pre><p>With the camera information finally in the GPU, we can use the little bit of linear maths from the start to transform our vertices.</p><pre>// Vertex shader (in shader.wgsl)<br>@vertex<br>fn vs_main(<br>    model: VertexInput,<br>) -&gt; VertexOutput {<br>    var out: VertexOutput;<br>    out.color = model.color;<br>    let world_position: vec4&lt;f32&gt; = vec4&lt;f32&gt;(model.position, 1.0);<br><br>    out.world_position = world_position.xyz;<br>    out.clip_position = camera.view_proj * world_position;   <br>    return out;<br>}</pre><p>The observant of you may notice that we don’t actually use the camera position in the vertex shader. I’ve instead put this in so that we can use later when we do lighting in the fragment shader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Sl5Q4mTmrmqHD69HkaGRrA.gif" /><figcaption>Working camera but no depth stencil</figcaption></figure><p>Now if we replace our megre triangle with a cube we can see that grea… oh. That’s not quite right. It looks like all the triangles are being rendered in the wrong order! Well on the plus side, our camera works fine. Let’s address the problem and create a <strong>depth texture. </strong>This will tell the gpu how to render the triangles in the correct way, back to front.</p><p>In our render pipeline, we currently have the depth stencil option set to None, so let’s create one and fill in the blanks.</p><p>We’ll use this to create it in the <em>RenderEngine::new() </em>function, where <em>create_depth_texture </em>returns a custom <em>Texture </em>struct, containing a wgpu Texture, TextureView and Sampler<em> (Code in texture.rs)</em></p><pre>let depth_texture =<br>        texture::Texture::create_depth_texture(&amp;device, &amp;config, &quot;depth_texture&quot;);</pre><p>When creating our pipeline we say we want to use this texture.</p><pre>//  let pipeline = device.create_render_pipeline( <br>//..<br>depth_stencil: Some(DepthStencilState {<br>                format: depth_texture.texture.format(),<br>                depth_write_enabled: true,<br>                depth_compare: wgpu::CompareFunction::Less,<br>                stencil: wgpu::StencilState::default(),<br>                bias: wgpu::DepthBiasState::default(),<br>            }),<br>//..</pre><p>And we use it to create a depth stencil for the render pass to use when we render a frame.</p><pre>// let mut render_pass = encoder.begin_render_pass(<br>// ..<br>depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {<br>                    //attach depth texture to stencil attatchement of render pass<br>                    view: &amp;self.depth_texture.view,<br>                    depth_ops: Some(wgpu::Operations {<br>                        load: wgpu::LoadOp::Clear(1.0),<br>                        store: wgpu::StoreOp::Store,<br>                    }),<br>                    stencil_ops: None,<br>                }),<br>// ..</pre><p>Finally, lets not forget to create a new one whenever we resize window, to make sure our depth texture matches the available space from the window.</p><pre>//  pub fn resize(<br>//..<br>self.depth_texture =<br>        texture::Texture::create_depth_texture(&amp;self.device, &amp;self.config, &quot;depth_texture&quot;);</pre><p>That should do it.</p><p>Lets try running it again, fingers crossed 🤞</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*K1pi1RubFkcJApjarPOXZA.gif" /><figcaption>Depth stencil and camera both working</figcaption></figure><p>Success!!</p><p>There we have it, a basic 3D camera for our render engine.</p><p><em>Full code on </em><a href="https://github.com/ejb004/render-engine-wgpu"><em>GitHub</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=930ad4a356d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>