<?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 Turk M. Ergin on Medium]]></title>
        <description><![CDATA[Stories by Turk M. Ergin on Medium]]></description>
        <link>https://medium.com/@turkmergin?source=rss-e701bb44a99f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PMNWmk5ekw__fTEcCKU9SQ.jpeg</url>
            <title>Stories by Turk M. Ergin on Medium</title>
            <link>https://medium.com/@turkmergin?source=rss-e701bb44a99f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:53:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@turkmergin/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[Maximizing Performance: Entity Component  System,— Vol.2]]></title>
            <link>https://medium.com/@turkmergin/maximizing-performance-entity-component-system-vol-2-8ecf78eebe90?source=rss-e701bb44a99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ecf78eebe90</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[data-oriented-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[entity-component-system]]></category>
            <dc:creator><![CDATA[Turk M. Ergin]]></dc:creator>
            <pubDate>Fri, 16 May 2025 11:40:43 GMT</pubDate>
            <atom:updated>2025-05-16T11:43:00.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Maximizing Performance: Entity Component System — Vol.2</h3><h4>Performance by default, Data Oriented Design</h4><h3>Foreword</h3><p>Most of us started learning programming the <strong>Object-Oriented</strong> way.<br> It’s the most common and approachable paradigm — almost every course, book, or tutorial teaches it first. And for good reason: it’s intuitive and practical for small- to medium-sized problems.</p><p>But as projects grow, things get messy.<br> To manage complexity, we start introducing patterns, abstractions, base classes, and more… until it becomes a tangled web of inheritance and indirection.</p><p><strong>But what if there was another way?</strong><br> A way that’s simpler, more maintainable, and actually faster — especially in performance-critical domains like game development?</p><p>In this article, we’ll explore the <strong>Entity Component System (ECS)</strong> architecture using <strong>TypeScript</strong>, and why it might just be a better alternative to traditional Object-Oriented Programming.<br> (Yes, there will be examples — duh.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJxPzjxk8hu47gUfr_D4VQ.png" /></figure><h3>What’s Data Oriented Design?</h3><p>In short, Data-Oriented Design aims to maximize CPU cache utilization and optimize memory allocation for performance. Every time a new object is created in Object-Oriented Design, stored in an instance variable, accessed in a handler, or reused across handlers, you’re likely retrieving that object from a non-contiguous memory location in RAM — resulting in frequent cache misses and causing countless milliseconds of performance loss.</p><p><strong>Example</strong>:</p><p>When you extend your favorite fruit class and name it banana, the object is getting heavier and heavier with the time.</p><pre>class Effect {<br>  apply(player: Player) {}<br>}<br><br>class HealthEffect extends Effect {<br>  value: number;<br>  constructor(value: number) {<br>    super();<br>    this.value = value;<br>  }<br><br>  apply(player: Player) {<br>    player.health += this.value;<br>  }<br>}<br><br>class SpeedEffect extends Effect {<br>  value: number;<br>  constructor(value: number) {<br>    super();<br>    this.value = value;<br>  }<br><br>  apply(player: Player) {<br>    player.speed += this.value;<br>  }<br>}<br><br>class Player {<br>  public health: number = 100;<br>  public speed: number = 0;<br><br>  public addEffect(effect: Effect) {<br>    effect.apply(this);<br>  }<br>}<br><br>class Fruit {<br>  public effects: Effect[] = [];<br><br>  public eat(player: Player) {<br>    this.effects.forEach(effect =&gt; player.addEffect(effect));<br>  }<br>}<br><br>class Banana extends Fruit {<br>  constructor() {<br>    super();<br>    this.effects.push(new HealthEffect(10));<br>    this.effects.push(new SpeedEffect(5));<br>  }<br><br>  public eat(player: Player) {<br>    super.eat(player);<br>  }<br>}</pre><p>And so on — you keep extending, implementing, introducing new types of bananas that apply effects to the player. Every time eat is called, the player has to be fetched along with its list of effects—likely causing multiple cache misses. Not to mention, implementing the Effect class with several different effect strategies... When you step back and look at the big picture, you realize how quickly Object-Oriented Design becomes overly complex.</p><p>Lets imagine the same thing in Data Oriented. But before, i will briefly explain what ECS is about.</p><h4>Whats ECS?</h4><blockquote>Entity Component System is about separating logic from data — where all entities in your world are nothing more than just IDs.</blockquote><p>Think in terms of data. Design your systems around how your data flows. Assign data (components) to entities. And stop worrying about the rest. It’s that simple.<br> Think of a system as a behavior. You assign and tell the system which component types to operate on to execute that behavior.</p><p>Components are purely data and nothing else than data!</p><p>Lets do the example i just mentioned previously in ECS,</p><p><strong>Components (Only Data!):</strong></p><pre>class Component {}<br><br>class Stat extends Component {<br>  // you can also implement min, max value but for the sake of this article,<br>  // i keep things more simple.<br>  value: number;<br>  constructor(value: number) {<br>    super();<br>    this.value = value;<br>  }<br>}<br><br>class Health extends Stat {}<br><br>class Speed extends Stat {}<br><br>// Tip: There’s no shame in creating empty components—they’re great as indicators!<br><br>class PlayerTag extends Component {} // Just to mark an entity as a player<br><br>class FruitTag extends Component {} // Just to mark a fruit entity</pre><p><strong>Creating Entities:</strong></p><p>You can create new entities and assign components directly, or use a static world or prefab system.<br> Here’s a simple version that creates them manually:</p><pre>// Create player entity<br>const player = Entity.create();<br>Entity.addComponent(player, new PlayerTag());<br>Entity.addComponent(player, new Health(100));<br>Entity.addComponent(player, new Speed(0));<br><br>// Create banana entity<br>const banana = Entity.create();<br>Entity.addComponent(banana, new FruitTag());<br>Entity.addComponent(banana, new Health(10));<br>Entity.addComponent(banana, new Speed(5));</pre><p><strong>Implementing the System:</strong></p><p>Now, we build a system that consumes the fruit when a player interacts.</p><pre>class FruitConsumptionSystem extends System {<br>  execute() {<br>    // Best to do in constructor or listen to component handler like;<br>    // onComponentAdded kinda event and add it to your instance variable; fruit component list<br>    // but for the sake of the example, i keep it abstract as possible;<br>    // i will cover it in more details in vol 3.<br>    const fruits = Query.with(FruitTag, Health, Speed).getEntities();<br>    const players = Query.with(PlayerTag, Health, Speed).getEntities();<br><br>    // Let&#39;s say &quot;player pressed E near banana&quot;<br>    fruits.forEach(fruit =&gt; {<br>      const player = players[0]; // Simplified: one player<br><br>      const fruitHealth = Entity.getComponent&lt;Health&gt;(fruit);<br>      const fruitSpeed = Entity.getComponent&lt;Speed&gt;(fruit);<br><br>      const playerHealth = Entity.getComponent&lt;Health&gt;(player);<br>      const playerSpeed = Entity.getComponent&lt;Speed&gt;(player);<br><br>      playerHealth.value += fruitHealth.value;<br>      playerSpeed.value += fruitSpeed.value;<br><br>      Entity.destroy(fruit); // Banana is eaten<br>    });<br>  }<br>}</pre><p>And don’t forget — you can implement rendering systems, audio systems, and more the same way. Just implement and attach a RenderComponent to the entities you want to draw on the screen assign the desired banana texture as variable, and let the rendering system handle the rest—no headaches, no tangled code.</p><p>Imagine ECS like building a vertical LEGO structure: each block (component) snaps neatly into place. Instead of cooking a spaghetti al dente mess with Object-Oriented Design, you get a clean, modular, and flexible build.</p><p>I would recommend <a href="https://amzn.eu/d/649zUNm">this book</a>, which helped me a lot grasping the idea and the philosophy behind ECS.</p><p>In next Volume, i will briefly cover how we combine ECS with typed arrays in typeScript and build a small game using pixiJS with all other good practices out there so stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ecf78eebe90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning Pixels into Music: Creativity with Image-to-Audio Conversion]]></title>
            <link>https://medium.com/@turkmergin/turning-pixels-into-music-creativity-with-image-to-audio-conversion-ea55ec5313dc?source=rss-e701bb44a99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea55ec5313dc</guid>
            <category><![CDATA[music]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Turk M. Ergin]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 18:26:37 GMT</pubDate>
            <atom:updated>2024-11-29T10:09:33.330Z</atom:updated>
            <content:encoded><![CDATA[<h4>or Yet, Better Just Noise..</h4><p>A few days ago, I found myself a little bored with some free time on my hands. Around the same time, I visited a photography exhibition that sparked my imagination. The images I saw there inspired an idea in my mind: turning pixels into sound waves. Or just noises.. (Most of the cases).</p><p>Of course, it’s not an entirely original idea — this concept has been explored before. But still, I thought;</p><blockquote>Yeah, this would be an interesting project to dive into.</blockquote><h3>Concept</h3><p>The idea behind it is super simple: analyze each pixel in the image, extract its RGB value, and turn those values into sound waves. Then, repeat this process for each pixel, transforming the visual data into auditory signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*AicTpSy2bXZAOFlAc3yKbA.png" /><figcaption>RGB values of the specific pixel.</figcaption></figure><h3>Implementing</h3><p>I chose the Node.js environment and decided to work with TypeScript for this project. To quickly get started, I did some research on existing libraries and found two particularly useful ones. The first is <a href="https://www.npmjs.com/package/canvas">Canvas</a>, which allows me to extract pixels from an image. The second is <a href="https://www.npmjs.com/package/wavefile">Wavefile </a>, a library for creating WAV files, which I used to convert the extracted data into sound.</p><pre>const image = await loadImage(inputImagePath);<br>const { width, height } = image;  <br>const canvas = createCanvas(width, height);<br>const ctx = canvas.getContext(&#39;2d&#39;);<br>ctx.drawImage(image, 0, 0);<br>const imageData = ctx.getImageData(0, 0, width, height);<br>return imageData.data;</pre><p>This is the first step of the implementation where I extracted all the data from the image. Which are the RGBA values.</p><pre>const frequencies: number[] = [];<br> const amplitudes: number[] = [];<br><br>  for (let y = 0; y &lt; height; y++) {<br>    for (let x = 0; x &lt; width; x++) {<br>      const idx = (y * width + x) * 4; // RGBA format<br>      const rgb = _normalizeRGB({<br>        r: data[idx],<br>        g: data[idx + 1],<br>        b: data[idx + 2],<br>      });<br><br>      const freqR = _mapFrequency(<br>        rgb.r,<br>        rgbFrequencyRange.r.min,<br>        rgbFrequencyRange.r.max,<br>        rgbFrequencyRange.r.offset<br>      );<br>      const freqG = _mapFrequency(<br>        rgb.g,<br>        rgbFrequencyRange.g.min,<br>        rgbFrequencyRange.g.max,<br>        rgbFrequencyRange.g.offset<br>      );<br>      const freqB = _mapFrequency(<br>        rgb.b,<br>        rgbFrequencyRange.b.min,<br>        rgbFrequencyRange.b.max,<br>        rgbFrequencyRange.b.offset<br>      );<br><br>      frequencies.push(freqR, freqG, freqB);<br>      amplitudes.push(rgb.r, rgb.g, rgb.b);<br>    }<br>  }<br><br>  return { frequencies, amplitudes };</pre><p>Next, I iterated through the extracted raw data and mapped the RGB values to frequency. Additionaly if you noticed, Amplitude is analog to RGB values. Which the higher RGB value, the stronger the sound gets.</p><p>As the frequency ranges i used;</p><ul><li>R: between 30hz to 500hz with an offset of 60.</li><li>G: 500 hz - 2000hz, offset: 250.</li><li>B: 2000hz - 10khz, offset: 1000.</li></ul><p>I find it fascinating how the characteristics of the tones change with each different range setup. Feel free to adjust and experiment with it!</p><pre>offset + value * (max - min)</pre><p>This is how i mapped the frequency. Every color channel has a min, max frequency value with the original value itself plus the offset. <br>Basically each channel has its own frequency range.</p><pre>const totalSamples = Math.floor(frequencies.length / 3) * Math.floor(sampleRate * duration);<br>  const audioSamples = new Float32Array(totalSamples);<br><br>  let sampleIndex = 0;<br>  for (let i = 0; i &lt; frequencies.length; i += 3) {<br>    const [freqR, freqG, freqB] = [frequencies[i], frequencies[i + 1], frequencies[i + 2]];<br>    const [ampR, ampG, ampB] = [amplitudes[i], amplitudes[i + 1], amplitudes[i + 2]];<br><br>    for (let t = 0; t &lt; sampleRate * duration; t++) {<br>      const time = t / sampleRate;<br>      const sample =<br>        (ampR * Math.sin(2 * Math.PI * freqR * time) +<br>          ampG * Math.sin(2 * Math.PI * freqG * time) +<br>          ampB * Math.sin(2 * Math.PI * freqB * time)) /<br>        3;<br>      audioSamples[sampleIndex++] = sample;<br>    }<br>  }<br><br>  return audioSamples;</pre><p>After mapping the frequencies, this is how I generated the sound waves. Which is a combination of R, G and B’s put together and created a sample for each pixel. To adjust the sine wave’s pitch, you can modify the ‘2’ in the equation that defines the sample. By decreasing this value, the pitch becomes lower; increasing it raises the pitch, resulting in a higher tone. The <strong>duration</strong> refers to how long each sample plays. The higher the duration, the longer the sample will sound. <em>This part you can change and get creative.</em></p><pre>  const wav = new WaveFile();<br>  wav.fromScratch(1, sampleRate, &#39;32f&#39;, audioSamples);<br>  const wavBuffer = Buffer.from(wav.toBuffer());<br>  fs.writeFileSync(outputAudioPath, wavBuffer);</pre><p>Finally, I generated the WAV file and saved it.</p><h3>Result</h3><p>Well, some images sound like R2D2 beeping, while others resemble an old CD-ROM laser. But the philosophy behind creating something truly interesting lies in the willingness to experiment. I experimented with everything from real-life pictures I took to small images I created in Paint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/1*-6cZnBE3Fm0WVs_D8YFsLw.png" /><figcaption>Image created by me using paint :)</figcaption></figure><p><strong>Pro tip:</strong> As a best practice, always keep the image size small. Larger images can easily exceed the buffer limit, causing issues. <strong>Stick around 250x250 or less.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/0*cpXe_gV0IzxMwMfm" /><figcaption>Or this</figcaption></figure><p>Barcodes also produce some super interesting sound.</p><h3>Pixeltone.JS</h3><p>If you enjoy experimenting but want to skip the implementation details, or have further interest, you can try my <a href="https://www.npmjs.com/package/pixeltone.js">library</a>. I’ve wrapped up most of the complexities and am actively adding new features to extend the library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*bk6McNpiihhyy9b4jG4beQ.png" /></figure><p>Its super easy to use:</p><pre>npm i pixeltone.js</pre><pre>import { Pixeltone } from &#39;pixeltone.js&#39;;<br>const pixeltone = new Pixeltone();<br>pixeltone.createAudioFromImage({ inputImagePath: &#39;input.png&#39;, outputAudioPath: &#39;output.wav&#39; });</pre><p>Here is a small example how this picture sounds like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/50/1*9eG5n_1AJL8j9UO9rtY20A.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F1969364367%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fturk-m-ergin%2Fprototype-1%3Fsi%3D2994d266c5c545aa8ed8cb91387ae0c0%26utm_source%3Dclipboard%26utm_medium%3Dtext%26utm_campaign%3Dsocial_sharing&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-WlIYNOXwksGKQ0Dd-dOhWGQ-t500x500.jpg&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae7ff95777beea88dab70742ecabc5a2/href">https://medium.com/media/ae7ff95777beea88dab70742ecabc5a2/href</a></iframe><p>If you are interested, check out the <a href="https://www.npmjs.com/package/pixeltone.js">NPM </a>page for more details! Feel free to <a href="https://github.com/RecursiveVoid/pixeltonejs">fork the project on GitHub</a> , create your own projects with it, and if you like to contribute, don’t hesitate to get in touch!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea55ec5313dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximising Performance: A Deep Dive into PixiJS Optimization]]></title>
            <link>https://medium.com/@turkmergin/maximising-performance-a-deep-dive-into-pixijs-optimization-6689688ead93?source=rss-e701bb44a99f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6689688ead93</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pixijs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Turk M. Ergin]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 09:01:52 GMT</pubDate>
            <atom:updated>2025-05-16T11:41:36.921Z</atom:updated>
            <content:encoded><![CDATA[<h4>Take your PixiJS Applications to the Next Level with Advanced Strategies and Techniques</h4><h3>Foreword</h3><p>This post goes over the different ways one can best optimize the rendering of multiple elements within pixiJS in terms of both CPU / Memory. For example, considering the difference between re-rendering every frame without any caching-which performs well in terms of CPU usage-or caching a rendered graphics in memory. This will increase the memory usage in proportion to the number of graphics in the scene.</p><p>There are a number of strategies for dealing with such optimizations. Of particular note is Data-Oriented Design, which presents a radically alternative set of approaches from the more traditionally common Object-Oriented way of programming.</p><p>Other major ways include: culling and utilizing far more structured formats — NativeArrays in C# and TypedArrays in TypeScript, for example. These will allow much greater management of memory buffers, which may limit cache-misses, but which also need significant engineering experience and/or customisation.</p><p>In this post, I will be focusing on one working method of optimization for a WebGL environment with PixiJS: The Object-Oriented Approach, inclusive of best practices. This shall provide you with a well-organized means to increase speed and efficiency in your PixiJS applications.</p><p>In my next article, I will be talking about another strong optimization approach: the Entity-Component-System Approach. The ECS approach is strikingly data-oriented and offers a fresh look when it comes to optimizing PixiJS in high-performance environments. Continue on Medium for this article where, in-depth, I go into the nitty-gritty of the ECS approach.</p><p>Always remember that there is always something that can be done better in an attempt to optimize and further enhance the performance of your Pixi application. By better, it does not mean most optimized or fastest. Best solution is a question of trade-off between amount of time you invest in an optimization and return on that investment to make sure you can meet the project deadlines but with enough optimization to hopefully satisfy any potential users without over-expanding your resources.</p><h3>Object Oriented Approach</h3><p>In this section, I’m going to guide you through the best ways of optimizing PixiJS applications.</p><p><a href="https://pixijs.com/guides/production/performance-tips">This section is based on official tips, worth to check!</a></p><p>The rest of our discussion will revolve around Pixi Graphics, Sprites, Meshes and when to use a Particle Container instead of the default Pixi Container. This chapter should give you a clear view of how all can be used optimally in an Object-Oriented context so your PixiJS projects are functional and rendered with the greatest efficiency.</p><h4>Understanding the Inner Workings of Pixi Graphics</h4><p>In order to effectively use Pixi graphics, we need to understand how they function internally. So let’s start by showing a very basic example of creating a graphics object in Pixi:</p><pre>const graphics = new PIXI.Graphics();<br>graphics.beginFill(0xff0000);<br>graphics.drawRect(0, 0, 200, 100);<br>graphics.endFill();</pre><p>What is important in this simple implementation, however, is what happens ‘under the hood’. In creating this kind of graphic, Pixi creates something called a <em>GraphicsGeometry </em>object. That object takes on the shape and size based on the dimensions and properties you specify for the shape you are drawing. The final Geometry object is then stored inside a <em>GeometryList </em>within the Graphics object.</p><p>Note that each time you are drawing something with the help of PIXI.Graphics, <em>GeometryList </em>gets updated. Sometimes, you just want to clear this list, but at the same time keep your Graphics object alive-that is where the<em> .clear()</em> method comes into play. Knowing how this process works will help you greatly when using Pixi, as it directly affects how Pixi will handle and render the graphics in your app.</p><h4>Optimization Techniques for Pixi Graphics</h4><p>Let’s explore optimization strategies through a use case of creating 100 Graphics objects in PixiJS.</p><pre>function createGraphics(x, y) {<br>    const graphic = new PIXI.Graphics();<br>    graphic.beginFill(0xDE3249);<br>    graphic.drawCircle(x, y, 10);<br>    graphic.endFill();<br>    return graphic;<br>}<br><br>for (let i = 0; i &lt; 100; i++) {<br>    const x = Math.random() * app.screen.width;<br>    const y = Math.random() * app.screen.height;<br>    const graphics = createGraphics(x, y);<br>    app.stage.addChild(graphic);<br>}</pre><p>In this scenario, if all 100 Graphics objects share the same width and height, we can optimize by reusing the geometry.</p><figure><img alt="Here is the result of using 100k Graphics object on stage" src="https://cdn-images-1.medium.com/max/331/1*fSjSBbrygl23OwsZ7hBkzw.png" /></figure><h4>Passing GraphicsGeometry as Reference</h4><p>Create a single geometry for a circle and reuse it:</p><pre>// Create a single geometry for a circle<br>const circleGeometry = new PIXI.Graphics();<br>circleGeometry.beginFill(0xDE3249);<br>circleGeometry.drawCircle(0, 0, 10); // Draw a circle at the origin<br>circleGeometry.endFill();<br>// Function to create a graphic using the circle geometry<br>function createCircle(x, y) {<br>    const circle = new PIXI.Graphics(circleGeometry.geometry);<br>    circle.x = x;<br>    circle.y = y;<br>    return circle;<br>}<br>// Create 100 circles using the same geometry<br>for (let i = 0; i &lt; 100; i++) {<br>    const x = Math.random() * app.screen.width;<br>    const y = Math.random() * app.screen.height;<br>    const circle = createCircle(x, y);<br>    app.stage.addChild(circle);<br>}</pre><p>This method significantly reduces memory usage by referencing the same geometry instead of duplicating it for each object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*wwIwiA9OFB8b0gzWBZHlgA.png" /></figure><h4>Draw All in One Graphics Object</h4><p>For static graphics or complex structures, drawing all elements in a single Graphics object is another optimization technique:</p><pre>const graphics = new PIXI.Graphics();<br>// Draw 100 circles using the same PIXI.Graphics instance<br>for (let i = 0; i &lt; 100; i++) {<br>    const x = Math.random() * app.screen.width;<br>    const y = Math.random() * app.screen.height;<br>    graphics.beginFill(0xDE3249);<br>    graphics.drawCircle(x, y, 10);<br>    graphics.endFill();<br>}<br>// Add the graphics to the stage<br>app.stage.addChild(graphics);</pre><p>In this approach, instead of creating new Graphics objects, we add new geometries to the GeometryList of a single Graphics instance. This method is particularly efficient for more complex graphic structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HEWy-55K2iJz9I5-5VtB-w.png" /></figure><h4>Leveraging the Power of CacheAsBitmap in PixiJS</h4><p>One of the most powerful features within PixiJS is CacheAsBitmap. Essentially, it lets the engine treat graphics like sprites. This can bring performance up substantially in certain cases.</p><ul><li>Only use CacheAsBitmap if the object is not updated too often.</li><li>Big batch of Graphics can be cached as bitmap in container. Instead having 100 Graphics re-rendered, pixi will take a snapshot and pre-render it as a bitmap</li><li>Always consider the memory usage, cached bitmaps are using a lot of memory.</li></ul><h4>When to Use CacheAsBitmap</h4><p>One should use cacheAsBitmap judiciously. It will be most effective when applied to objects that need to update seldom. For instance, if one happens to have thousands of volume of Graphics that are static or have only a rare change, caching them as a bitmap radically reduces rendering overhead.<br>Instead of re-rendering 100 individual Graphics, PixiJS can take a ‘snapshot’ of these and render them as single bitmap. This is how you can implement:</p><pre>const graphicsContainer = new PIXI.Container();<br>// Add your graphics to the container<br>// ...<br>// Cache the entire container as a bitmap<br>graphicsContainer.cacheAsBitmap = true;</pre><h4>Memory Usage Consideration</h4><p>However, it’s important to be mindful of memory usage. Cached bitmaps can consume a significant amount of memory. Therefore, while cacheAsBitmap can drastically reduce the rendering load, it trades off by using more memory. This trade-off should be carefully considered based on the specific needs and constraints of your application.</p><p>In summary, cacheAsBitmap is an effective tool for optimizing performance in PixiJS, particularly for static or seldom-updated graphics. It simplifies rendering by treating complex graphics as single bitmaps, but it&#39;s essential to balance this with the memory footprint implications.</p><h3>Why Sprites Are Often More Efficient than Graphics in PixiJS</h3><p>When it comes to memory efficiency in PixiJS, sprites generally have the upper hand over graphics. This is particularly evident when dealing with multiple objects that share the same shape or texture. Let’s revisit the example of creating 100 circle graphics, but this time using sprites.</p><h4>Creating Sprites from a Single Texture</h4><p>First, we create a texture from the geometry of a single circle graphic:</p><pre>const circleGraphic = new PIXI.Graphics();<br>circleGraphic.beginFill(0xDE3249);<br>circleGraphic.drawCircle(0, 0, 10);<br>circleGraphic.endFill();<br>// Generate a texture from the graphic<br>const circleTexture = app.renderer.generateTexture(circleGraphic);</pre><p>Next, we use this texture to create sprites:</p><pre>// Function to create a sprite using the circle texture<br>function createCircleSprite(x, y) {<br>    const sprite = new PIXI.Sprite(circleTexture);<br>    sprite.x = x;<br>    sprite.y = y;<br>    return sprite;<br>}<br><br>// Create and add 100 circle sprites to the stage<br>for (let i = 0; i &lt; 100; i++) {<br>    const x = Math.random() * app.screen.width;<br>    const y = Math.random() * app.screen.height;<br>    const circleSprite = createCircleSprite(x, y);<br>    app.stage.addChild(circleSprite);<br>}</pre><p>In this approach, instead of re-rendering graphics and managing a growing geometry list for each object, we create one texture and reuse it across multiple sprites. This significantly reduces the rendering load and memory usage.</p><h4>Limitations and Creative Solutions</h4><p>One limitation of this method is that you’re constrained by the textures you’ve created. However, this is where creativity becomes key. You can generate various shaped textures using PIXI.Graphics and apply them to Sprites. An especially efficient approach is to create a baseTexture, like a 1x1 pixel bitmap, and reuse it for all rectangular sprites. By resizing the sprite to different dimensions, you can leverage the same baseTexture across multiple sprites without redundancy.</p><p>For instance:</p><pre>// This creates a 16x16 white texture<br>const baseTexture = PIXI.Texture.WHITE;<br><br>// Use this baseTexture for all rectangular shapes<br>const sprite= new PIXI.Sprite(baseTexture);<br>sprite.tint = 0xDE3249; // Set the sprite color<br>sprite.position.set(x, y);<br>sprite.width = width;<br>sprite.height = height;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*9CcpnFifFf6Z7H7Fss-75g.png" /></figure><p>With this method, .tint() allows you to color the sprite without triggering a full re-render, as the tint is applied as an additional shader effect directly on the GPU.</p><p><strong>Using 100k Sprites in Particle Container</strong></p><p>To illustrate the power of this technique, imagine running 100,000 individual sprites with random tints, each transforming on every frame, all while maintaining a smooth 60 FPS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*cow5va154_w_mPbpGawwNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*d7rtCRMtAMumpBWG0eZO_g.gif" /></figure><p>For further reading on optimizing PixiJS, I highly recommend an insightful article by one of the original creators of PixiJS, which delves deeply into the renderTexture technique.</p><p>You can find it here:</p><p><a href="https://medium.com/@bigtimebuddy/rendering-fast-graphics-with-pixijs-6f547895c08c">Rendering Fast Graphics with PixiJS</a></p><p><strong>Wow!</strong> If you’ve made it this far, I want to sincerely thank you for sticking with me through this deep dive into PixiJS optimization. I hope you found the insights and techniques shared here valuable for your projects. <a href="https://medium.com/@turkmergin/maximizing-performance-entity-component-system-vol-2-8ecf78eebe90">Stay tuned for my next article</a>, where I’ll be exploring the Entity-Component-System (ECS) approach and the power of NativeArrays in even greater detail. These methods will take your PixiJS applications to new heights in performance and efficiency. Thanks for reading, and see you in the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6689688ead93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>