<?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 David Gavilan on Medium]]></title>
        <description><![CDATA[Stories by David Gavilan on Medium]]></description>
        <link>https://medium.com/@endavid?source=rss-fb3d57a95c51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HoHi0CWynWwY-BHk</url>
            <title>Stories by David Gavilan on Medium</title>
            <link>https://medium.com/@endavid?source=rss-fb3d57a95c51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:03:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@endavid/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[En David 2025 Retrospective]]></title>
            <link>https://medium.com/@endavid/en-david-2025-retrospective-840c4f3c0d82?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/840c4f3c0d82</guid>
            <category><![CDATA[indiedev]]></category>
            <category><![CDATA[retrospectives]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 21:08:06 GMT</pubDate>
            <atom:updated>2026-01-01T21:08:06.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oPeu9qfDbc6N3sG3.jpg" /><figcaption>Happy new year 2025 🐴 &amp; a visual summary of my 2025</figcaption></figure><h3>Overview of my 2025</h3><p>Happy new year! あけましておめでとう！ 🥳</p><p>I’m still processing the ending of “Stranger Things”, but I figured out it was time to write down this retrospective of 2025.</p><p>2025 has been a year without many surprises, which it’s good, I suppose. I was planning to write more blog posts, but I failed to do so. I did write a lot of internal technical articles for work, though. I wrote more than 50 articles, so around 1 article per week. Unfortunately, I can’t share any of that, but I used my shader app, Mantis Shrimp, to generate some of the animated figures in the articles I wrote for work. For instance, here’s a figure I used to illustrate Phong Shading:</p><p>Your browser does not support the video tag. Illustration of Phong shading created with Mantis Shrimp</p><p>I didn’t do much programming on my free time, but I did implement some updates for <a href="https://mantisshrimp.endavid.com/">Mantis Shrimp</a>, and started a new word puzzle game to practice Japanese, <a href="https://kotobanokabe.endavid.com/">Kotoba No Kabe / ことばのかべ</a>. But I haven’t released any of that yet.</p><p>I did a few trips this year, both long and weekend trips, and met some good friends. I also spent some time recording and editing simple videos for my Spanish geeky Youtube channel. It’s mostly a vault where I talk and keep a record of things I’ve found interesting, like the Japanese novels I’ve reading recently. But in one of the trips <a href="https://youtu.be/hEnIu27iris?si=pQX_9VS8jcZLRG9j">I interviewed a friend, Luis from Shinyuden</a>, and that interview got around 900 views. It may not seem like much, but it’s like 100 times more than usual… Considering the video is 75 minutes long, it’s a lot.</p><p>My laptop “died” right after Christmas. It was an old 13-inch Retina MacBook Pro from 2012. It was actually working, and I had updated it to the latest macOS using OpenCore, so I could use it for programming and stuff. However, the chasis had been bent for a few months, and for some reason I hadn’t thought it could be a swollen battery… 😅 I took it to an Apple Store and they confirmed that it was, but they don’t do battery replacements because the laptop is too old. I could try to find a third party replacement place, but it was Christmas season and many things were closed… I didn’t want to risk it to go on fire while I’m not at home, so I decided to play it safe and leave it there for recycling. Thank you for 13 years of flawless service 🥲</p><p>More details about my year below.</p><h3>Indie development</h3><p>I did some small development on the side. I added support for music playback to Mantis Shrimp, so I can create visualizers like the one in the screenshot on top of this article. I didn’t try to publish the update yet because I’m afraid Apple may misunderstand again the purpose of my app — last time they complained the video playback of the app didn’t work, but what I added was a video recording feature, not video playback… It took me a while to explain. Anyway, I recorded a video about Mantis Shrimp and about Metal SDK and Metal shaders: <a href="https://youtu.be/ukM8_IVKDJQ?si=9KnvdWd5OrmIPDh0">Metal shaders playground with Mantis Shrimp 🦐🖥️</a>.</p><p>I also started creating a new word puzzle game. It’s like the Japanese version of <a href="https://sopilabitas.endavid.com/">Sopilabitas</a>. I called it <a href="https://kotobanokabe.endavid.com/">Kotoba no Kabe (ことばのかべ)</a>, or Word Wall JP in English. I’m drawing everything by hand and scanning my drawings, because I’m becoming a bit overwhelmed of the “too perfect” looks of GenAI drawings. I wrote a postmortem of Sopilabitas in this blog, with a small introduction to the new game: <a href="https://endavid.com/index.php?entry=108">Let’s build a wall: Sopilabitas Postmortem</a>. I hope I can finish it in 2026.</p><p>Related to my word puzzle games, I wrote a slightly technical article about sorting strings in different languages: <a href="https://endavid.com/index.php?entry=107">Swift string comparison with Locale configuration</a>. This was part of a bug fix I released for some of my games.</p><p>I was thinking of skipping <a href="https://adventofcode.com/">Advent of Code</a> this year, but it turns out it’s now just 12 days, instead of 25, so I gave it a go. I got stuck with a couple of exercises but I managed to complete. I only did a couple of interesting visualizations: <a href="https://www.instagram.com/p/DR99b6SjBFF/?utm_source=ig_web_copy_link&amp;igsh=MzRlODBiNWFlZA==">AoC 2025 visualizations</a>.</p><h3>Music with Generative AI</h3><p>Although I’ve been complaining of being tired of GenAI images, I must confess I spent a lot of time in 2025 generating music with Suno AI… 😅 I created a YouTube channel with a very explicit name: <a href="https://www.youtube.com/@50AIMusicSeal">50% AI music seal</a>. The “seal” in the name is a reference to my passion for cute seals. The 50% is because I either write the lyrics, or I use the AI to do covers of original materials.</p><p>For instance, I spent some time remembering my time in Tokyo and writing lyrics in Spanish for those memories. And with those I created a city-pop-like album, but in Spanish, <a href="https://youtu.be/C4JlqaQJDmo?si=2fu8T07pWMVq149B">Spanish Gaijin City Pop</a>. Or I created another rave-style album with a mixture of Japanese and Catalan lyrics: <a href="https://youtu.be/eLRO3AVhnoc?si=Cj0rnxuJ2rndtf2k">J-cat rave</a>. I programmed the visualizers with Mantis Shrimp.</p><p>Although I’m not very fond of AI, I recognize it’s allowing me to express myself in different ways I wouldn’t thought possible.</p><p>At the end of the year I wrote funny Spanish Christmas carols based on video games, and then I sang them. But I used the AI to create covers from those audio files, so I don’t have to torture people with my voice: <a href="https://youtube.com/playlist?list=PLPyYMokUPTh5Vua5oGwjFQv5_jTj8HA_b&amp;si=LvrdQBBuG9XJAh2Z">Videogame Spanish carols</a></p><h3>Trips</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EjgvL3ZIm97r9O9_.jpg" /><figcaption>Some photographs from my trips in 2025, from <a href="https://www.instagram.com/endavidg/">@endavidg Instagram</a></figcaption></figure><p>In 2025 I’ve been to Tokyo, Barcelona, Bilbao, Geneva, Valencia, Copenhagen, and to the seaside in southern Catalonia. I bought a pair of microphones and I’ve been vlogging a bit. Although I don’t have many views, it’s been quite fun to record some “podcasts” with my friends, Luis and Vanessa. Although some of the videos have English subtitles, everything is in Spanish. But if you are curious, you can take a look here: <a href="https://youtube.com/playlist?list=PLPyYMokUPTh70JVIbmHwLCDwSXx3YqMgl&amp;si=AuBrHT-kf95wc010">Focáchara podcast in YouTube</a>.</p><p>And I attended a few video game concerts which were spectacular: the Final Fantasy VII Rebirth concert in Barcelona, the “Metal Gear in Concert” in London, and Strands of Harmony concert in London, the Death Stranding concert. In the era of AI I really recommend going to listen to music live. It’s truly moving. By the way, in 2025 the Japanese composer <a href="https://en.wikipedia.org/wiki/Yoko_Shimomura">Yoko Shimomura</a> was awarded with a <a href="https://en.wikipedia.org/wiki/BAFTA_Fellowship">BAFTA Fellowship</a> for a lifetime of great video game soundtracks (Street Fighter 2, Legend of Mana, Parasite Eve, Kingdom Hearts, Final Fantasy XV, etc.). She’ll be attending another concert in London in June 2026, <a href="https://www.musicofsquareenix.com/">The Music of Square Enix</a></p><h3>Readings</h3><p>I started the year with a very interesting reading: “The art of thinking clearly”, a book about biases. Although these books are usually not very practical, this one is one of the most practical ones I’ve read. I took lots of notes.</p><p>Then, I read a book about a station cat in the UK, Felix the cat. It was cute, but it wasn’t exactly a page-turner. Unfortunately, while writing this I just found that Felix passed away a couple of years ago: <a href="https://www.bbc.com/news/articles/c97383pvyy8o">Railway cat and internet sensation Felix dies</a>.</p><p>The page-turners were all the Japanese novels from <a href="https://en.wikipedia.org/wiki/Keigo_Higashino">Keigo Higashino</a> I read after that. Higashino, writer of mainly mystery novels, is one of the most popular authors in Asia and, reportedly, the most popular novelist in China, so that means he’s reached millions of people! 😳 I read 3 of his books in 2023, and I resumed reading more of his novels this year, just from September. In 4 months I read 5 of his novels, in Japanese. That’s a lot for me, because I don’t usually read much… But he’s very good.</p><p>I usually don’t read fiction because I feel a bit like I’m wasting time, but since I’m reading these in Japanese, I think it’s a good excuse for practicing the language. Sometimes I search for words that I don’t understand, but many other times, I search just for the reading of those words. In Japanese, evenf if I can understand the meaning of a word, from the context or from the ideograms/kanji, many times I don’t know how to read them. Anyway, I don’t need to read everything inside my head as I would do when reading English or Spanish, so I feel I’m getting faster at reading Japanese, or at least, mystery novels!</p><p>Here’s a list of all the books I’ve read: <a href="https://endavid.com/lists/readings08.html">Readings</a>.</p><h3>Video games</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CQZLZgxYOe5xN5F9.jpeg" /><figcaption>Some screenshots I took while playing FF VII Rebirth</figcaption></figure><p>I’ve played and cleared 3 games in 2025:</p><ul><li><em>Final Fantasy VII Rebirth</em>. I loved it. It is a bit of a nostalgia trap, but it’s still quite fun to play. I uploaded several videos analyzing it, and analyzing the English and Spanish translations, compared to Japanese. I even started playing the game in hard mode, until it became too difficult and it stopped being fun (and then I quit).</li><li><em>Final Fantasy VII Crisis Core</em>. Not as fun as I expected, but it’s good as well.</li><li><em>Death Stranding 2: On the beach</em>. Perhaps I played this game for way too long… Some colleagues told me they got Platinum in about 90 hours, so I decided to attempt going for the Platinum trophy as well… But apparently I’m not that good because it took me more than 200 hours… (that’s still less than the 250h I spent in FF7 Rebirth… and I didn’t get Platinum in Rebirth…) As an excuse, I must say that I spent lots of time taking pictures because the scenery of this game is too pretty.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oFspFQbL_5ybZs2M.jpg" /><figcaption>Some screenshots I took of the breathtaking sceneries in Death Stranding 2, from <a href="https://www.instagram.com/endavidg/">my Instagram</a></figcaption></figure><h3>Health and best wishes for 2026</h3><p>I didn’t manage to play badminton regularly this year, but I’ve continued going to a yoga class weekly. Let’s all try to keep healthy in 2026!</p><p>Also, let’s see if I can find the time to do all the things I want to do…</p><p>Peace ☮️🕊 to the world 🙏 and Happy New Year 2026 🐴</p><p><em>Originally published at </em><a href="https://endavid.com/index.php?entry=109"><em>https://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=840c4f3c0d82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s build a wall: Sopilabitas Postmortem]]></title>
            <link>https://medium.com/@endavid/lets-build-a-wall-sopilabitas-postmortem-1b5da3bf2124?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b5da3bf2124</guid>
            <category><![CDATA[indie-game]]></category>
            <category><![CDATA[learning-spanish]]></category>
            <category><![CDATA[word-puzzle-game]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 18:01:23 GMT</pubDate>
            <atom:updated>2025-11-29T18:01:23.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IAe6SzfkKSDyqlin.png" /><figcaption>Screenshots of the game Sopilabitas</figcaption></figure><h3>Introduction</h3><p>In this postmortem I’m not going to dig into the technical details of my word puzzle games. Instead, I’ll tell you about the personal journey that took me to create them, and about Sopilabitas (Word Wall ES) in particular. It’s probably a game you never heard of 😅, but it’s still on Apple’s <a href="https://itunes.apple.com/us/app/sopilabitas/id1507790384?ls=1&amp;mt=8">App Store</a>.</p><h3>A word search game for my mum</h3><p>In 2015 my mum had a brain stroke. She eventually recovered, but she suffered from different degrees of aphasia since then. At the beginning, it was quite hard for her to articulate any words or to read anything. When thinking of ways I could help, I came up with the idea of making a word puzzle game.</p><p>I remembered buying the PlayStation Portable during Christmas of 2004 in Tokyo, and a game with it, <a href="https://en.wikipedia.org/wiki/Kotoba_no_Puzzle:_Mojipittan">Mojipittan (ことばのパズル もじぴったん大辞典)</a>, a word puzzle game. I had lots of fun with it at the time. It works great for word discovery because you can try random combinations of syllables (hiragana) and discover new words by chance. I realized that I wanted this game for my mum, but in Spanish. And I made Silabitas in 2016. I had to make my own set of rules to divide words, because real syllables can’t be recombined in that many ways, and it’s too hard to make words by connecting a single letter at a time. You can get more details about it in this video of the making of Syllabits, the English version of the game: <a href="https://youtu.be/z2NaUlUPfho?si=3rDTXf17kiD0W8_a">🇬🇧 Syllabits: History &amp; Introduction</a>. You can also play Syllabits from your browser on <a href="https://endavidg.itch.io/syllabits">endavidg.itch.io/syllabits</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iMXCSOQrtbLmal0H.jpg" /><figcaption>Screenshots of Silabitas (top row) and Syllabits</figcaption></figure><p>I took Silabitas to Indiecade Europe and a reviewer told me the game was too hard, and it got zero attention in the event (it didn’t help they scheduled my session during cocktails). It also performed poorly in the App Store, but for me it was still a success: my mum cleared its 89 stages! Patience can beat both reviewers and brain strokes.</p><p>Perhaps my mum is truly a genius, even with a brain stroke, but I felt the game was indeed hard, and a bit boring. I thought of adding more gameplay mechanics like in the original Mojipittan, but complicating things wouldn’t make it more fun for my mum. Instead, I checked what other games she played. When I saw she spent a lot of time doing word search games, it clicked: I had to combine Silabitas with word search, and add some time constraint so one stage wouldn’t take that long to clear, and perhaps add some thrill. It would be something like Tetris, or Wordtris.</p><p>The game would be called Sopilabitas, a portmanteau of “Sopa de letras” (literally, “word soup”, i.e. “word search game” in Spanish), and Silabitas. In English I simply called it “Word Wall ES”, though 😆.</p><h3>A story about a wall</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ivMaXo4PHCzg7y81.jpeg" /><figcaption>More screenshots of the game Sopilabitas</figcaption></figure><p>I like it when casual games have some little background story. It was something that was missing from Silabitas and Syllabits. This time I wanted a story for Sopilabitas.</p><p>It was 2019 when I started writing down the concept for the game. At the time, Donald Trump was almost every day on BBC News, even if for just a couple of sentences he had posted on Twitter. The things he said about wanting to build a wall at the border of Mexico resonated with the concept of my game. Sopilabitas was going to be about destroying walls, and it was going to be metaphorical.</p><p>Each stage of the game takes place in a different Spanish-speaking country, and characters tell you bits of information on the story as you progress. The first character you encounter in a woman scientist (a pixel-art version of my mum) that tells you there’s a plague of self-replicating bricks in Latin America, creating walls everywhere. You are sent to destroy those walls.</p><p>When you make Spanish words over those walls, the “level of understanding” increases. This is represented by a “brain bar” on the top right of the screen. The metaphor I was trying to convey here is that learning languages is a tool for better mutual understanding and for breaking barriers.</p><p>The last stage of the first part of the game takes place in Mexico, where you find out that a guy called Mr. Acid (orange face, lemon hair, and strawberry tie) is the person responsible for engineering these self-replicating “syllabits” (bricks with letters).</p><p>There’s a second part in the game that takes place in Spain, where you meet a different type of villain and there’s a new plot. And after you clear everything there’s a small animation of a train, the “train of thought”, running against a wall and turning it into pieces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sq2BYJa8jm8ZifbC.jpeg" /><figcaption>(1) Tutorial; (2) Mexico stage; (3) My mum tops the leaderboards, with more than 1000 daily challenges cleared successfully; (4) Pause at Machu Picchu stage; (5) The last stage parodies Castlevania, but in the Spanish Royal Academy (RAE) building in Madrid.</figcaption></figure><h3>Modest success</h3><p>In hindsight, the story didn’t matter for most people. But the story was important for me to keep me motivated and engaged with the development. I think I needed the story more than the players did. However, the game was generally well received.</p><p>I added a daily challenge with random words from the dictionary, and my mum and my sister have been playing almost every day since the release. That’s almost 5 years! I also play from time to time. The app comes with a widget where you can see the words of the day, and sometimes I just open the app to find out what those words mean.</p><p>There are not that many downloads. Perhaps a half a dozen a month now. But I didn’t try to market it in any way. I tried Apple Keywords, but I was spending more than I was earning, so I stopped the campaign. Marketing is not what motivates me. It would be great if it reached more people, but keeping my mum engaged was for me a success.</p><h3>Giving back to Japan</h3><p>Recently I’ve started creating the Japanese version of Sopilabitas. In English it will be called “Word Wall JP”, to keep it consistent. In Japanese, it is “Kotoba no Kabe” ことばの壁 (literally, “word wall”). Since my development history of word games started with Mojipittan, I thought it was time to give back to Japan some of what I’ve been doing these years.</p><p>The story concept of “Kotoba no Kabe” is about a person trapped in an “isekai” (this Japanese word has been added to the Cambridge dictionary recently! — it means “alternate reality”), and in order to get out you need to remember basic Japanese words. The characters of the game are Japanese animals, and I’m drawing everything by hand.</p><p>Drawing is also part of the point of these games I make as a hobby. I’m not very good at drawing, but I can do some pixel art that works. However, I got a bit bored with my pixel art style, so for “Kotoba no Kabe” I thought of making normal drawings. I toyed with the idea of using AI, but after writing the article on AI and art ( <a href="https://endavid.com/index.php?entry=105">“Can Generative AI create original art?”</a>), I realized I was growing tired of Generative AI. Suddenly, even normal digital drawings looked to me like AI. So I’ve decided to draw everything by hand on paper and scan it. Because I’m not very good at it, it looks childish at times, perhaps. But I think that way it is even more clear that it is definitely <em>not AI</em> and I like that. Here are some screenshots of the game:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QAL8j2ZP-Sst-git.jpg" /><figcaption>Screenshots of Kotoba no Kabe (ことばのかべ) on iPad</figcaption></figure><p>I’ll keep you posted. I hope I can finish it in the early 2026.</p><h3>Wrapping up</h3><p>I’ve spoken with friends that have tried indie game development, either part time or full time, and it doesn’t seem easy for anyone. If you try to do it full time, you have the pressure of having to earn a living, so you may prioritize what the market wants versus what you want. On the other hand, if you do it just in your spare time, you may not have enough time to do something that stands out, or energy to invest in things that you may not enjoy, like marketing or dev-ops.</p><p>Tangential to all that, keeping the motivation up is also hard. Either because you are doing tasks that you don’t want to do, or because the project is too big and you don’t see an end to it.</p><p>I’ve more or less kept motivated through the years, even if I didn’t earn much from my games because:</p><ol><li>I only do it in my spare time, and I have a daytime job where I don’t do game design; programming on Swift for Mac is also a “change of scenery” for me;</li><li>I think first on what would be fun for me to develop — an interesting story full of puns, for instance, even if people may not get it. By the way, the common driver behind all my games is the embedding of some small piece of learning in them. In the case of word puzzle games, the learning is more obvious, but in <a href="https://snake.endavid.com/">Snake on a Sphere</a> the theme was the abuse of resources, and <a href="https://mayandyam.endavid.com/">May &amp; Yam Against Pollution</a> tried to raise awareness about different pollutants in every stage.</li><li>I try to target a small audience, even if it’s just my mum — making something that it’s going to be both useful and fun for her;</li><li>I try to make small games so I can cope with the development without getting too tired of it.</li></ol><p>Of course it’s also great if other people download it, but I’d rather have 5 positive comments in the app than 100 downloads. Syllabits, by the way, made it to the “New games we love” list from Apple in several countries, when it was released. That was also motivating. But also puzzling that it only got about a hundred downloads on that week.</p><p>You can find a list of all my apps and games here: <a href="https://endavid.com/lists/works.html">EnDavid Works</a>.</p><p>Happy holidays 🎅🏻🎄</p><p><em>Originally published at </em><a href="https://endavid.com/index.php?entry=108"><em>https://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b5da3bf2124" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift string comparison with Locale configuration]]></title>
            <link>https://medium.com/@endavid/swift-string-comparison-with-locale-configuration-9a23dd5b521d?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a23dd5b521d</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 17:48:12 GMT</pubDate>
            <atom:updated>2025-01-23T17:48:12.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*92uPojgR54aGnR5N.jpeg" /><figcaption>Some screenshots of my word puzzle games</figcaption></figure><h3>Bugs in my word puzzle games</h3><p>I have several word puzzle games in the App Store, and 3 of them started acting funny in recent versions of iOS: <a href="http://silabitas.endavid.com/">Silabitas</a>, <a href="http://sillabetes.endavid.com/">Sil·labetes</a>, and <a href="http://sopilabitas.endavid.com/">Sopilabitas</a>. The English one, <a href="http://syllabits.endavid.com/">Syllabits</a>, still works fine.</p><p>What happened is that some words could not be made, as if they were not in the dictionary. For instance, there’s a stage in Silabitas where you have to construct the word “chaqueta” (jacket), but the game doesn’t recognize it, so you can’t clear the stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RDGjiT0if6BGbC5e.jpg" /><figcaption>Screenshot of the “chaqueta” stage in Silabitas</figcaption></figure><p>The bug appeared in recent version of iOS because the way strings are sorted has changed. Continue reading for more details.</p><h3>Alphabetical order across languages</h3><p>In my word games I do string comparison with the compare function in Swift string class to check the order of letters and words. Strings are made of Unicode characters.</p><p>In Unicode, each character is assigned a unique code point. For example:</p><ul><li><em>“ñ”</em> (LATIN SMALL LETTER N WITH TILDE) has a Unicode scalar value of U+00F1.</li><li><em>“o”</em> (LATIN SMALL LETTER O) has a Unicode scalar value of U+006F.</li></ul><p>When comparing strings or characters in Swift, the result depends on the collation algorithm being used. <em>Collation</em> determines how characters are ordered, taking into account locale-specific rules.</p><p>It seems that by default the string comparison was using the locale before, but that seems to have changed. If no locale is explicitly provided, Swift must be using binary Unicode ordering now, instead of a specific linguistic locale. That means that the “ñ” will appear at the end of the alphabet, after the “z”, instead of appearing after the “n”, and before the “o”, because its numerical value is greater than “z”.</p><p>To fix that I simply needed to specify the locale when calling compare. See the unit test below:</p><pre>func testSpecialSymbolsOrder() {<br>    // &quot;z&quot; has a Unicode scalar value of U+007A.<br>    // &quot;ñ&quot; has a Unicode scalar value of U+00F1.<br>    XCTAssertFalse(&quot;ñ&quot; &lt; &quot;o&quot;)<br>    XCTAssertFalse(&quot;ñ&quot; &lt; &quot;z&quot;)<br>    // to properly sort,<br>    let loc = Locale(identifier: &quot;es&quot;)<br>    XCTAssertEqual(ComparisonResult.orderedAscending, &quot;ñ&quot;.compare(&quot;o&quot;, locale: loc))<br>    XCTAssertEqual(ComparisonResult.orderedDescending, &quot;ñ&quot;.compare(&quot;n&quot;, locale: loc))<br>}</pre><h3>Issues with binary search</h3><p>The reason why that change in iOS prevented the game from functioning correctly was that I sorted the dictionary in advance using the correct collation for the given language. And then, I used binary search to find whether the word existed in the dictionary. If the sorting changes, binary search will fail.</p><p>Imagine that you have the words “mono, moño, mote, mozo, mula”. If you are looking for “moño” with binary search and you start in the middle with “mote”, if the sorting is wrong it will believe that “moño” should appear after “mote” (because the Unicode value of “ñ” is greater than “t”), and we will fail to find the word in the dictionary.</p><h3>Diacritics and other symbols</h3><p>The solution wasn’t that easy in Catalan. The character <em>“ç”</em> was treated before as appearing after “c” and before “d”. That is correct, but when appearing in a word, the <a href="https://ca.wikipedia.org/wiki/Ordre_alfab%C3%A8tic">Catalan collation rules</a> say that the “ç” should be treated as a a <em>diacritic</em>, that is, the “ç” is equivalent to a “c” and only placed after it when there are 2 equivalent occurrences. That means that the order should be “caca, caça, cacatua, cada”, and not “caca, cacatua, caça, cada” as the older version of iOS had given me.</p><p>Another example of such diacritic symbol in Catalan is the <a href="https://en.wikipedia.org/wiki/Interpunct#Catalan">interpunct</a> between els (to make a longer “l” sound): <em>“l·l”</em>. An example of sorting words using the correct collation would be: “filla, fil·lastomàtid, fillastra”.</p><p>But the collation algorithm is not ignoring other symbols such as the hyphen or the apostrophe, that appear in some words of the dictionary, such as “pèl-blanc”, or “d’amagatons”. In order to ignore these, I remove them from the string before doing any comparisons.</p><p>Here’s some reference code in Swift to do the search with the correct sorting. The binary search function is from <a href="http://stackoverflow.com/a/33674192/1765629">Stackoverflow</a>.</p><pre>extension String {<br>    func noSymbols() -&gt; String {<br>        return self<br>            // e.g. d&#39;amagat<br>            .replacingOccurrences(of: &quot;&#39;&quot;, with: &quot;&quot;)<br>            // e.g. pèl-blanc<br>            .replacingOccurrences(of: &quot;-&quot;, with: &quot;&quot;)<br>    }<br>}<br><br>class WordDictionary {<br>    let words: [String]<br>    let locale = Locale(identifier: &quot;ca&quot;)<br><br>    func getWordIndex(_ word: String) -&gt; Int {<br>        // the diacritic insensitive search treats ñ as n, and ç with c,<br>        // but we want to avoid that, so use the locale and only remove symbols<br>        let ref = words.noSymbols()<br>        let i = words.binarySearch({<br>            let w = $0.noSymbols()<br>            let order = w.compare(ref, options: [.caseInsensitive], locale: locale)<br>            return order == .orderedAscending<br>        })<br>        return i<br>    }<br>}</pre><h3>Allow bad spelling</h3><p>The compare function has also an option to ignore diacritics. When comparing words, I can’t use that option because there are certain things I don’t want to ignore. In particular, the “ç” is a letter that can be input in the game, so “caca” (poo) is different from “caça” (hunt). But the player can’t input accents or interpuncts, so in those cases I do want to ignore the differences.</p><p>So instead of relying on the compare function, I convert every string to a “potentially badly written” one where I removed everything but the “ç” (in the case of Catalan):</p><pre>extension String {<br>    func unaccented() -&gt; String {<br>        return self.lowercased()<br>            .replacingOccurrences(of: &quot;à&quot;, with: &quot;a&quot;)<br>            .replacingOccurrences(of: &quot;ä&quot;, with: &quot;a&quot;)<br>            .replacingOccurrences(of: &quot;è&quot;, with: &quot;e&quot;)<br>            .replacingOccurrences(of: &quot;é&quot;, with: &quot;e&quot;)<br>            .replacingOccurrences(of: &quot;í&quot;, with: &quot;i&quot;)<br>            .replacingOccurrences(of: &quot;ï&quot;, with: &quot;i&quot;)<br>            .replacingOccurrences(of: &quot;î&quot;, with: &quot;i&quot;) // only maître...<br>            .replacingOccurrences(of: &quot;ò&quot;, with: &quot;o&quot;)<br>            .replacingOccurrences(of: &quot;ó&quot;, with: &quot;o&quot;)<br>            .replacingOccurrences(of: &quot;ö&quot;, with: &quot;o&quot;)<br>            .replacingOccurrences(of: &quot;ú&quot;, with: &quot;u&quot;)<br>            .replacingOccurrences(of: &quot;ü&quot;, with: &quot;u&quot;)<br>    }<br>    func badWritten() -&gt; String {<br>        return self.unaccented().noSymbols()<br>            .replacingOccurrences(of: &quot;·&quot;, with: &quot;&quot;)<br>    }<br>}</pre><p>If I find a match in the dictionary, I return the entry from the dictionary so the player sees the correct spelling.</p><h3>Conclusion</h3><p>Nothing apparently simple is really that simple. The evil is always in the details. It turns out that alphabetical order is not universal, and system functions change with time. Be sure you write unit tests for the system functions that are required by the core functionality of your app. In this instance the unit tests I already had in place saved me a lot of time.</p><p>And <em>strings</em> will always be the last boss in computer science! 😂</p><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=107"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a23dd5b521d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[En David 2024 Retrospective]]></title>
            <link>https://medium.com/@endavid/en-david-2024-retrospective-75d75dc4817c?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/75d75dc4817c</guid>
            <category><![CDATA[retrospectives]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 19:51:38 GMT</pubDate>
            <atom:updated>2025-01-12T19:51:38.225Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4WHzw8OIv1fNwUZ8.jpg" /><figcaption>Happy new year 2025 🐍 &amp; a visual summary of my 2024</figcaption></figure><h3>Overview of my 2024</h3><p>2024 has been another year of rollercoasters. I started 2024 without a job, and I did lots of job interviews and studied to prepare for them. I released a macOS app, Mantis Shrimp, and I was busy for a while doing the Genuary challenge using my own app, writing shaders for practice.</p><p>I found a job in a video games company, Lucid Games, so I’m back in the games industry after a gap of 8 years working for fashion. As soon as I secured the job, I flew to Tokyo to take a short break, for 10 days. It was great to meet ex-colleagues and friends again.</p><p>I started work in April and I’ve been quite busy since, so I didn’t write all the blog posts I had planned, but no one was expecting me to, so I should relax 😅</p><p>I’ve done more exercise than usual, but it’s not lots. At the beginning of the year I started badminton and I was playing every week. However, I stopped in summer and I haven’t resumed it yet… I also started yoga 4 months ago, and I’m doing it every week so far 🧘🏻👍</p><p>I’ve also been checking my health. All of a sudden one GP wanted me to have all kinds of checks and I said yes to all, because it’s usually hard to get any attention from NHS and they usually ignore any mild conditions, even if chronic. So I’ve been a bit busy with GP appointments for the past 2 months, but for a good reason.</p><p>In November I heard the bad news that a friend I talked a lot to for the past 5 years had passed away. It wasn’t a surprise because I was aware of his deteriorated health, but it was still very sad. I wrote about him in here: <a href="https://endavid.com/futurebrain/nukunuku.html">Nuku-Nuku / Future Brain</a>.</p><p>In the new year I’m going to start in a new project (at Lucid), so I start 2025 again with more changes.</p><p>Let’s see how 2025 goes. Let me list some of the stuff I did during 2024 first.</p><h3>Work during 2024</h3><p>I did tons of interviews before landing at Lucid Games. I’ve been learning Unreal Engine 5, touching some of the code, and doing cool things. The codebase is huge, so I’m quite overwhelmed at times, but people in the team have been very helpful and I think I’ve levelled up a bit.</p><p>I can’t show anything of what we are doing, but I did some test with Unreal on my spare time using Unreal’s Mass system and storing skinning weights on textures to do the animation on the GPU, and I recorded a funny clip of that. I used it in this music video: <a href="https://www.youtube.com/shorts/uySzrhhBvVM">Programmer’s affliction (vocaloid Japanese voice)</a>.</p><h3>Indie development and GenAI music</h3><p>I haven’t made any games this year. I’ve only done some development of my shader app, <a href="https://mantisshrimp.endavid.com/">Mantis Shrimp</a>. I just released an update last month. I also released some maintenance updates to <a href="https://sillabetes.endavid.com/">Sil·labetes</a>, <a href="https://silabitas.endavid.com/">Silabitas</a>, and <a href="https://sopilabitas.endavid.com/">Sopilabitas</a>. Those 3 had a bug introduced in recent versions of iOS. It’s quite an interesting bug, so I’ve written a blog post about it that I’ll publish soon.</p><p>On a down note, I removed <a href="https://syllabits.endavid.com/">Syllabits</a> from the Google Play store. It was too stressful to maintain. Google is like that last boss monster that you know you could beat with enough grinding, but you can’t be bothered anymore, so you decide to stop playing the game. If you understand Spanish, I recorded about it here: <a href="https://youtu.be/Q6fMBjyn0dY?si=LltEIKN5pha_pqx2">“Rajando de Google Play y adiós a Syllabits”</a>.</p><p>I also managed to clear the Advent of Code challenge again, although I struggled with a couple of exercises… I only cleared Part 2 of Day 24 on the 31st of December (I was home alone with my cat, on New Year’s eve) 😅 — But apparently I finished second in our office ranking, so I may get a small trophy 🥳</p><p>And I created a font with my handwriting. You can find it in some places of <a href="https://endavid.com/">EnDavid.com</a>. See some of the writing on the figure on top of this article. You can download it from here: <a href="https://endavid.com/fonts/EnDavid%20Handwritten.otf">EnDavid Handwritten.otf</a>.</p><p>What I’ve spent lots of time in was writing lyrics 😅 I got a bit addicted to Suno AI. I started by adding music to some old poems I had written, and it is quite satisfying to listen to something you’ve written with a nice melody. Then, I started writing new lyrics and generating more AI music. The AI can also generate the lyrics for you, but that’s not quite fun for me. I like writing lyrics. I have a playlist in YouTube with some of the music I created: <a href="https://youtube.com/playlist?list=PLPyYMokUPTh74hD7WgTtabWVQiC50o1BL&amp;si=95ihhRh_53I8Szfr">Focotaku Music</a>. I’ve done some interesting experiments like mixing Catalan and Japanese in the same song, by creating the song at intervals. Most recently, Suno released a feature (still in beta) that lets you cover your own songs, or even clips you upload. So I started singing some of my lyrics and then covering them to make them sound good (because I sing horribly, but the notes are more or less recognisable). For instance, I wrote, sung, and covered with AI this Christmas Carol about Castlevania: <a href="https://youtu.be/FqaAuQmJdxE?si=7rysyG22HIF1E3zm">Last Castlevania 🏰🧛‍♂️ (Christmas song)</a>. I know Generative AI can be scary and some people hate it, but I’ve had so much fun with this 😅 Please forgive me 🙏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*weSssZrgRict-5eo.jpg" /><figcaption>Some of the drawings I did for #inktober, copying videogame covers with seals 🦭</figcaption></figure><p>I also did some drawings manually to disconnect from the computer. I managed to completely the Inktober challenge for the first time. I drew lots of videogame covers with seals 🦭😂. And I also completed Genuary, a generative art / programmer art challenge. All the code is here: <a href="https://github.com/endavid/MantisShrimpExamples/tree/main/Genuary2024">endavid (github) / Genuary2024</a>.</p><h3>Blogging</h3><p>I had some things in my backlog that I didn’t write about in the end, and I didn’t write lots, but I’m quite happy with what I wrote. Some of these articles took months, or even years to write, if you think of the extend of what they cover. I can list them all because it’s not much:</p><ul><li><a href="https://endavid.com/index.php?entry=100">8+ years programming for fashion</a>. It didn’t take me 8 years to write this, but it’s a summary of those 8 years, so I think it’s a nice glimpse of the tech we used and the tech that is coming (lots of GenAI) — It also happens to be the 100th entry in <a href="https://endavid.com/">EnDavid.com!</a> 🥳</li><li><a href="https://endavid.com/index.php?entry=101">My retrospective of 2023</a>. A rollercoaster year…</li><li><a href="https://endavid.com/index.php?entry=102">Troubleshooting “Disk not ejected properly” on a LaCie USB-C HDD</a>. This blog post took me a couple of months of writing down notes. It was a nice exercise of trying to understand hardware and drivers, and navigating customer support. It’s quite thorough!</li><li><a href="https://endavid.com/index.php?entry=103">Mantis Shrimp: Image Differences with Metal shaders</a>. This is the culmination of the development of my shader toy app, <a href="https://mantisshrimp.endavid.com/">Mantis Shrimp</a>. I was meant to write another article about mesh shaders in detail, but it’s still in my backlog… 😅</li><li><a href="https://endavid.com/index.php?entry=104">Concurrency recipes in Swift and C++</a>. This was a fun exercise in concurrent programming, using one of the exercises of Advent of Code 2023. Quite technical.</li><li><a href="https://endavid.com/index.php?entry=105">Can Generative AI create original art?</a>. After a few months without writing anything, I came back with this. It’s a very lengthy philosophical discussion on what art is. It’s a culmination of months of me playing with Generative AI, mixed with some ideas I explored in my PhD years ago. I defined something I called “fiascart”, but in retrospective, I think everything can be considered art. But I wanted to draw some line between good “human” art, and Gen AI, and art fiascos.</li></ul><h3>Vlogging</h3><p>I’ve recorded lots of videos in 2024 for my “otaku” YouTube channel, mostly about videogames and Japanese culture. For a few months, I was releasing one video weekly! I don’t have many visits, but I just make these to make a “brain dump” of things that I’m curious about and I want to share a bit more widely. For instance, <a href="https://endavid.com/lists/readings08.html">I read the book “Nagomi” by prof. Ken Mogi</a>, and I recorded a video about it (in Spanish), with slides and all: <a href="https://endavid.com/%E2%80%9Cotaku%E2%80%9D">NAGOMI: Filosofía japonesa del equilibrio</a> (at the moment, the video has 450 views, but most videos in that channel have just around 10 to 30 views 😅).</p><p>I also recorded a couple of technical rants, that I’ve uploaded to another channel. Like the rant I mentioned earlier about Google Play.</p><h3>Leisure</h3><p>I played many great games during this year. My backlog of games to play is getting too long, so I tried to clear it up a bit 😅 I played:</p><ul><li><em>Final Fantasy XVI</em> — I had already cleared it, but I had so much fun that I played it again. And I also cleared the DLCs</li><li><em>Final Fantasy VII Remake / Intergrade</em>. This was so much fun and nostalgic! ❤️ And the orchestral remake of the soundtrack is amazing.</li><li><em>The Last Of Us: Left Behind</em>. This was a DLC I bought more than 10 years ago and I hadn’t played it yet 😅 It was good but my heart may not tolerate scary games anymore…</li><li><em>Silent Hill: The Short Message</em>… Who said no horror games? 😅 I’m very fond of the Silent Hill series (one of the reasons why I wanted to work at Konami at the time!), so I had to play this. It’s quite short, and it’s free, so I had to try it. I enjoyed the story. I read bad reviews, but I liked it. And the soundtrack by Akira Yamaoka is very good.</li><li><em>Fantasian</em>. I played this for 3 months or so, but I didn’t clear it. It was fun at the beginning, but at some point it got too hard so I gave up. I don’t think I’ve ever given up on a game after playing for that long (56 hours), but it wasn’t fun anymore. I wouldn’t recommend it, at least not the Apple Arcade version.</li></ul><p>And I also read the 3 NieR novels, in Japanese. So good practice. See: <a href="https://endavid.com/lists/readings08.html">Readings</a>.</p><p>As I said in the introduction, I also managed to visit Tokyo again, and I did lots of catching up with friends. But I also travelled to Madrid and saw a couple of good friends I hadn’t seen in a while. And we attended a beautiful wedding of friends in Barcelona. Friends are a treasure ❤️</p><h3>Wishes for 2025</h3><p>I’m currently playing <em>Final Fantasy VII Rebirth</em> and it’s lots of fun. But I also have some coding (perhaps some new game) I want to start this year. I also have some blog posts, technical and not so technical, in my backlog. A couple of them are almost finished. I just need to add some pictures.</p><p>I’ll continue doing yoga and hopefully I will resume playing badminton. And I have a short trip planned to Tokyo. And several trips to Barcelona to see family and friends.</p><p><em>Peace ☮️🕊</em> to the world 🙏 and <em>Happy New Year 2025 🐍</em></p><p><em>Originally published at </em><a href="https://endavid.com/index.php?entry=106"><em>https://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75d75dc4817c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Generative AI create original art?]]></title>
            <link>https://medium.com/@endavid/can-generative-ai-create-original-art-eefcdb98cc48?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefcdb98cc48</guid>
            <category><![CDATA[art]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[perception]]></category>
            <category><![CDATA[hamparte]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 15:51:44 GMT</pubDate>
            <atom:updated>2025-04-16T13:33:19.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JBU8yU6ljsCaiB4w.jpg" /><figcaption>A robot drawing a posing robot on a canvas, drawn with DALL-E.</figcaption></figure><h3>GenAI as a collage of mental percepts</h3><p>During my PhD I developed an app called <a href="http://sketch2collage.endavid.com/">Sketch-to-Collage</a>. It was a tool to create collages using simple color strokes as input. It used image retrieval to extract blobs from an image dataset and combine them in a new image that resembled the input sketch. See the example below, and this video: <a href="https://www.youtube.com/watch?v=tgXI-lqZvZg">Sketch-to-Collage (Siggraph 2007 Posters)</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mZNDdcDmurKxBLyz.jpg" /><figcaption>The sketch on the left is used to retrieve the images in the middle and create the collage on the right.</figcaption></figure><p>Because I had to write scientific papers, I needed to come up with a method to evaluate the quality of the techniques proposed. In image retrieval, a common strategy is measuring <strong>recall</strong> and <strong>precision</strong>. With that in mind, I used the concept of <em>“mental percepts”</em>, a mental representation of the perceived world state. The sketch from the user represents a draft of their visual mental percepts and I can use the sketch to measure the recall and precision of my app. It’s a bit more complex than that, but that’s the main idea. You can read my PhD thesis here: <a href="http://endavid.com/data/phd.pdf">“Region-based image abstraction for retrieval and synthesis” [Tokyo Tech, 2008] (PDF)</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ppLt2wBNZ0LyAcq.jpg" /><figcaption>Visual Perception model</figcaption></figure><p>To me, Generative AI, or <em>GenAI</em> for short, sounds like a very sophisticated version of such a tool. Your mental percept can be represented by words now, if the input is a text prompt. But you can even use images as input, or combine several inputs, or even combine several tools, i.e. you could create a collage created with my tool as an input to create a better image from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YV-BoqEijlplDNM7.jpg" /><figcaption>A sketch turned into a collage, and then transformed with AI Mirror app into anime style.</figcaption></figure><h3>Originality and copyright</h3><p>Can I collage anything and stay original? We need to check the images used in the original data set. If the dataset contains a copyrighted drawing of an apple and I use it in my collage, I may be infringing copyright, even if one could argue that the collage itself is an original piece of work.</p><p>But what if I simply sample the color of the apple to paint another fruit? Are colors copyrighted? And what if I copy the brush stroke lines as well? Perhaps you see where I’m going: with GenAI is sometimes hard to find traces of any original images because the final result is a “collage” of very small image features.</p><p>Another thing to take into account when thinking of originality is the limit of what we can create. As with my “sketch-to-collage” app, GenAI depends on an initial dataset for training, so there needs to be an a-priori match between your mental percepts and what’s already there. That means that it won’t be able to draw a cat if it’s never seen one.</p><h3>What is art?</h3><p>We doubted the originality of GenAI, but there’s a more fundamental question to answer: <em>Can GenAI produce art at all?</em></p><p>The Wikipedia says that there’s no generally agreed definition of what constitutes art, but it gives this one:</p><blockquote><em>Art is a diverse range of human activity and its resulting product that involves creative or imaginative talent, generally expressive of technical proficiency, beauty, emotional power, or conceptual ideas.</em></blockquote><p>The word <em>“human”</em> suggests that it must be made by humans to be art. I also highlighted the word <em>“talent”</em>, because I think many will agree that we need to appreciate some skill that excels in some way.</p><p>Here’s my attempt to give my own definition, based on the above, but rewritten so it’s easier to evaluate whether something is art or not:</p><blockquote><em>Art is any piece of work created by </em><strong><em>combining mental percepts</em></strong><em> into something to be consumed by </em><strong><em>human senses</em></strong><em>, using a set of sophisticated </em><strong><em>skills</em></strong><em>. It evokes some </em><strong><em>emotion</em></strong><em> in the consumer because of its </em><strong><em>quality</em></strong><em> or </em><strong><em>originality</em></strong><em>.</em></blockquote><p>Let us discuss my definition over some examples (please leave comments on each section if you want to discuss).</p><h4>A banana duct-taped to a wall</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5a36DJ1R_m3Wqr_x.jpg" /><figcaption>“Comedian”, a banana duct-taped to a wall, by Maurizio Cattelan. Antonio García Villarán’s book on “hamparte”, to the right.</figcaption></figure><p>❌🙅‍♂️ This doesn’t match my definition of art because it doesn’t require any sophisticated skills or talent, even though this is sold as art in art galleries.</p><p>Spanish Artist and communicator Antonio García Villarán tagged that piece as <em>“hamparte”</em>, a term he popularized to define art fiascos. “Hamparte” is a portmanteau of the words “hampa” (group of rascals, scammers, or con men) and “arte” (art). Since the word “con art” already exists in English with a different meaning, let me create a new portmanteau for “hamparte” in English with the words “fiasco” and “art”: <em>fiascart</em>.</p><h4>A pianist performance of “Clair de Lune”</h4><p>✅🙆‍♂️ This matches my definition of art, because you need skills to play the piano and it evokes emotions to people who listen to it. It may not be original, but it has quality.</p><p>This art is co-created by 2 people: the composer and the performer. The composer puts down his mental percepts in paper in the form of music notation. But it may not fully represent how he feels it should be played. They may write some “prompts” in the score to express if it needs to be played softer, or “virtuoso”. But in the end it’s the performer’s own mental model and interpretation what we hear.</p><h4>A photograph taken with an iPhone</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IK8UR6BW2-cuc6jW.jpg" /><figcaption>4 photographs I took with my iPhone, from my instagram account (<a href="https://www.instagram.com/endavidg/">endavidg</a>)</figcaption></figure><p>❌🙅‍♂️ There are no skills needed for this, so I would argue it’s not art. That doesn’t mean the picture is not pretty. Perhaps you have travelled far to take a picture of the Northern Lights, the Aurora Borealis. But the travel is not art and the picture that you take with your phone isn’t art either.</p><p>What we can derive from this is that not all pretty pictures are art. Instagram is mostly not art. These pictures can evoke emotions as well, and they can be of high quality. They can even be original, if it captures some rare event. But if they don’t require skills, I wouldn’t consider it art.</p><p>One could argue that the engineers that created the iPhone were the ones who had the skills. But there was not direct intentionality in the engineers to take that particular photo that you’ve taken. The skills should be needed in the person who directly creates the artwork.</p><h4>A painting by Miró</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jLgh07JE7UnXb93A.jpg" /><figcaption>Some paintings by Miró. From left to right: <a href="https://www.fmirobcn.org/es/coleccion/catalogo-obras/5435/p-pintura-sobre-fondo-blanco-para-la-celda-de-un-solitario-i-p">Peinture sur fond blanc pour la cellule d’un solitaire</a>, <a href="https://www.fmirobcn.org/en/colection/catalog-works/5432/p-poem-iii-p">Poem III</a>, <a href="https://www.fmirobcn.org/en/colection/catalog-works/5406/p-woman-dreaming-of-escape-p">Woman dreaming of escape</a>.</figcaption></figure><p>❌🙅‍♂️ This may be controversial, but Antonio García Villarán considers Miró’s work “hamparte” — or “fiascart”, as I defined earlier. I do agree it’s not art. But it’s not the same as a banana on a wall either, so I wouldn’t classify it as “fiascart”. I think Miró’s drawings are <em>designs</em>. A design is created with artistic tools, but it doesn’t need to be art.</p><p>For instance, a straight line on a white T-shirt is a design. But it doesn’t require any special skills to draw such line. Similarly, if you can’t tell apart Miró’s drawings from those from a 5-year old is because what you see is not art. That doesn’t mean the design doesn’t evoke any emotions or that it’s not valuable. But as with the case with the iPhone photograph, it’s just an interesting picture.</p><h4>A drawing made with Photoshop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6USfyXL_vvOioTn6.jpg" /><figcaption>A dragon I drew on paper, and then with Procreate on iPad</figcaption></figure><p>🤔 This depends on how much talent is needed to create that drawing. If anyone can do it with a few clicks, it’s not art. Any digital tools make our lives much easier. For instance, I use Procreate on iPad to draw clean brush strokes that I wouldn’t be able to reproduce with a real brush. Above there’s a dragon I’ve drawn with ink and color pencils, and then there’s the same drawing I made with Procreate. You can still recognize my style in the Procreate drawing, but the finish may look a bit neater. Neither of them can be considered art, I suppose, because I’m not talented enough to create something of good quality. They can be categorized as “artistic expression”, or simply as cute drawings.</p><p>Andy Warhol was a pioneer in digital drawing. He created some iconic drawings with Deluxe Paint in the Amiga computer. Drawing with the mouse wasn’t easier than drawing with paper at the time, though. There were many talented pixel-art artists at the time that spent a lot of time and effort in their creations.</p><h4>A GenAI image from a text prompt</h4><p>❌🙅‍♂️ I would argue that a GenAI image from a text prompt is not art. Even if the prompt is very long and complicated, I wouldn’t consider that an artistic skill. That’s why people that master the current prompt inputs are called “prompt engineers”, and not “prompt artists”. Also note that AI is getting simpler to use, so there may no longer be any need for “engineering” either.</p><p>Some people may confuse originality with art. Even if we assume that GenAI can be original, originality alone does not define art. If there’s no talent involved, a GenAI image is just another pretty image. But this time around is created from other means, other than an iPhone camera.</p><h4>A drawing improved with GenAI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*khL21nSCPHnIKB-t.jpg" /><figcaption>Left: my attempt to draw a fan art of Lunafreya with starscourge, from Final Fantasy XV; middle: drawing improved with AI Mirror app; right: AI Mirror being more inventive.</figcaption></figure><p>🤔 There are two things to check here: the drawing and the transform. If the drawing could be considered art by itself, and the transform doesn’t make the original drawing unrecognizable, I would say it can be considered art. If we accepted a Photoshop drawing by a talented artist as art, why not in this case? The artist could be applying premade textures with Photoshop on their drawing, and it would still be art.</p><p>Another way to think of it is that we allow certain level of <em>“cheating”</em>, i.e. the use of certain good tools. If I were talented and the drawing I made with Procreate (left in the figure above) could be considered art, the image generated with GenAI in the middle may still be art because the original drawing is still recognizable. However, the image on the right is a completely different thing. It does represent the same mental percepts I had in mind, that is, a woman with blue hair and black tears, but it doesn’t require much talent to obtain good quality like that. In this example, <em>it completely hides my lack of talent</em>, so it should smell suspicious.</p><h4>A GenAI song from an original poem</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fp6Wx9cVB6Ls%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dp6Wx9cVB6Ls&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fp6Wx9cVB6Ls%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f12cd4dfb7d5965ef4714faf7afbb5/href">https://medium.com/media/49f12cd4dfb7d5965ef4714faf7afbb5/href</a></iframe><p>🤔 This is somewhat similar to creating a GenAI image from an original drawing. But there’s a difference: there’s no music at all to begin with. If the poem can be considered art, only the poem will be art, but not the song. I think this is more similar to taking a photograph of the Mona Lisa. That photograph contains a piece of art, but the photograph itself is not art.</p><p>(The video above is a poem I wrote in 2009, “Sonnet pretensions of Pluto”, now turned into a song with Suno AI.)</p><h4>A GenAI song from an original song</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUzPnhYmQoTg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUzPnhYmQoTg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUzPnhYmQoTg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/901736a00fbce41791acfb58e6557f84/href">https://medium.com/media/901736a00fbce41791acfb58e6557f84/href</a></iframe><p>🤔 This is close to the case of creating a GenAI image from an original drawing. It works the same way: if the original song can be considered art, then the result will also be art if the original can still be recognized in it. The linked YouTube video above is a song I created with Suno AI by making a cover of my own voice. It produces something of decent quality from something that sounds awful (if you are not afraid, here’s my embarrassing original voice: <a href="https://youtu.be/Z8buPjl_r5Y">“Sonnet pretensions of Pluto”, improvised version by myself</a>). Again, it is not art because it completely hides my lack of talent. It’s just a nice song, in the same way we had nice GenAI drawings, nice iPhone photographs, and interesting designs.</p><h4>A drawing from a GenAI image</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RtbT2YKa61yRVPxB.jpg" /><figcaption>GenAI images generated with DALL-E for reference, and the drawings I made for <a href="https://inktober.com/">Inktober 2024</a></figcaption></figure><p>✅🙆‍♂️ If the drawing is made by a talented artist, I would consider that art (not the case of my drawings of seals I shared above for illustration purposes). If we accept that searching for reference images on Internet is not cheating, then writing a text prompt to generate an image for inspiration should be OK as well. The worry is not whether it is art or not, but whether that art is original. For instance, in the extreme case that the learning dataset contains just images of Van Gogh sunflowers, you’d be copying a Van Gogh drawing.</p><p>In music, the equivalent would be a band creating a song with AI and then playing it live. The performance may be art, but there would be a worry of whether that song is original or not.</p><p>So let’s go back to the subject of originality.</p><h3>Can humans be original?</h3><p>After that long discussion of what art is, I think we can conclude that there are many pretty or interesting creations, either created by humans or by GenAI, that are not necessarily art. Another takeaway is that art doesn’t need to be original. A good reproduction of Las Meninas or a good performance of Gymnopédie can be considered art.</p><p>Even if GenAI is not art, it may have some value, though. And that value may be greater if it represents something original. I discussed this a bit earlier when I talked about originality and the limits of what GenAI can create, depending on the dataset used for learning. But are humans any different? Do we have any limits?</p><p>For me, the creative process starts as <em>“collaging” in the brain</em>, that’s why I talked about collages in the introduction. We <em>copy and paste</em> mental percepts in our brains and then we try to put the result down in paper. When drawing, we repeat this “copy-pasting” by copying familiar shapes, or familiar drawing styles. GenAI just reveals the human tricks that most mortals use. Only a few individuals can be truly inventive. For instance, in pop music Björk and Rosalia come to mind. Everyone else is mostly repeating the same chords, using the same instruments, and repeating the same patterns.</p><p>There may even be a limit to originality. Anime faces may all look the same because it’s hard to create original faces and still have the distinctive anime look. And even something particular to a person, like their voice, may not be original. Some of the songs I created with Suno AI have familiar voices. This song I made from a Spanish poem I wrote 20 years ago, <a href="https://youtu.be/Od9GpqMjWKY">“Si así debiera ser en el mar”</a>, sounds like Spanish singer Anna Torroja. And this other one, <a href="https://youtu.be/vWJByJ0NVdU?si=6LjBcpNSi-FoTr4l&amp;t=1371">“Word Wormhole”</a>, something I wrote for the first chapter of my attempt to write a sci-fi book ( <a href="http://endavid.com/surrealitales/index.html">“Surrealitales”</a>), sounds to me as if sung by David Bowie. Are those singers in the dataset, or is it just that other singers have a similar tone and the “collaging” of voices end up sounding familiar? Since the AI is a black box, it’s hard to know what went into creating the final result.</p><p>I think it is very hard to be truly original. That’s why I put the “or” clause in my definition of art. But originality is tangential to talent, i.e. it’s another dimension. That means that we can create something original, interesting by itself, and GenAI can help us improve its quality.</p><h3>Saturation of the senses and mediocrity rise</h3><p>Since I work in Computer Graphics, I studied a bit how cameras work, in terms of lenses, sensors, and light interactions. However, I never dug deeper into photography because I became saturated with digital photographs early on. When I moved to Tokyo in 2002, all phones in Japan had cameras already. They weren’t great at the time, just 240×320 pixels on my first mobile phone. But it already meant that tons of photographs were shared continuously. It didn’t help that I focused my research on creating a database of such photographs and worked on image retrieval. And then when Facebook, and then later Instagram, appeared, we got bombarded with photographs from all our family and friends.</p><p>At the beginning those photographs were not of very good quality. But now with smartphones with intelligent processing that create beautiful moon pictures that are more fake than real, your Instagram feed looks probably amazing. It doesn’t help that phones tend to saturate colors to make images more appealing. In the end our visual cortex receives too many stimuli and we may be too tired to appreciate real art.</p><p>Let’s pause for a bit and think of what we’ve discussed earlier: most of what we see is probably not art. It’s just pretty pictures. But since everyone can create pretty pictures now, we may become immune to beauty. GenAI exacerbates the problem because now it’s even easier for everyone to create pretty pictures.</p><p>And it’s not only pretty pictures. We can create all kinds of appealing content. Now we can write like a professional novelist, or create catchy songs with just a few clicks. I’ve been pretty excited myself, specially with music. It’s so cool to be able to listen to my poems turn into songs. But when I hear a silly song about eating cookies all day made by a 6-yo, I get a bit down because I start thinking that perhaps my poems were crap to begin with and it’s just the music that makes them sound good.</p><p><em>Real talent is hidden in a sea of mediocrity. And the problem is that our senses can no longer tell the difference.</em></p><h3>Conclusions</h3><p>I’ve provided a definition of art that tries to reflect what I believe to be our common intuition of what art is: a piece of work for the senses created by a talented person, either original or of great quality. Under that definition, GenAI content is generally not art, because it can be produced by anyone without requiring any special skills or talent. However, it can be argued that GenAI may produce original content, or as original as the human “mental collaging” process can be.</p><p>Let me summarize my final thoughts in a few bullet points:</p><ul><li>The majority of the pretty pictures we see are not art.</li><li>Art doesn’t need to be original.</li><li>Original creations aren’t necessarily art.</li><li>Our senses are increasingly saturated with stimuli.</li><li>Non-talented people can now create good quality content that looks like art.</li><li>Real talent will increasingly become hidden in a sea of good quality GenAI content.</li></ul><p>This means that digital artists may be replaced by GenAI at places, unfortunately. But on the bright side, I suppose people will appreciate even more the art created with human hands, like paintings and sculptures, or performance arts, like theater or live concerts. Art won’t disappear, and with more people creating content, there will be more chances of finding interesting and original works.</p><h3>References and links</h3><ul><li>Marcus Pivato. <a href="http://euclid.trentu.ca/pivato/Teaching/models.pdf">“Models of philosophy”, May 2003 (PDF)</a> — Discussion on mental percepts.</li><li>My PhD thesis: <a href="http://endavid.com/data/phd.pdf">“Region-based image abstraction for retrieval and synthesis” [Tokyo Tech, 2008] (PDF)</a></li><li>Antonio García Villarán website: <a href="https://www.antoniogarciavillaran.es/">antoniogarciavillaran.es</a></li><li>My instagram account: <a href="https://www.instagram.com/endavidg/">endavidg</a></li><li>Playlist of music I generated with Suno AI: <a href="https://youtube.com/playlist?list=PLPyYMokUPTh74hD7WgTtabWVQiC50o1BL&amp;si=hpVJQT3nIp3z8P83">Focotaku Music playlist (YouTube)</a>, <a href="https://suno.com/@endavid">suno.com/@endavid</a></li><li>A quiz I prepared to test yourself (I don’t collect any answers): <a href="http://endavid.com/quiz/2024-what-is-art.html">What is art? (Quiz)</a></li></ul><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=105"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eefcdb98cc48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency recipes in Swift and C++]]></title>
            <link>https://medium.com/@endavid/concurrency-recipes-in-swift-and-c-f3606628954a?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3606628954a</guid>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[cpp17]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 11:33:03 GMT</pubDate>
            <atom:updated>2024-03-04T11:33:03.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ozQwcRSaPFC3kRB.jpg" /><figcaption>Screenshot of the benchmark with different running times</figcaption></figure><h3>Introduction</h3><p>There are many ways to create code that runs in parallel. In Swift in the Apple world it was common to use functions from <a href="https://en.wikipedia.org/wiki/Grand_Central_Dispatch">Grand Central Dispatch</a> (GCD), but in Swift 5.5 async and await became <a href="https://en.wikipedia.org/wiki/First-class_citizen">first-class citizens</a> of the language. That means there&#39;s now a more Swift-like way to handle concurrent code.</p><p>I personally get confused with the meaning of some of the keywords across languages. For instance, the async keyword in Swift is not the same as the async function in C++ STD library. That&#39;s why I wanted to compare at least Swift to C++.</p><p>This article shows different ways of running a loop in parallel in both Swift and C++, and I also compare the running times using a problem from <a href="https://adventofcode.com/">Advent of Code</a> as benchmark.</p><h3>Advent of Code “Jengatris” as benchmark</h3><p>I’ve taken the problem from day 22 of Advent of Code 2023 as my benchmark. It’s a problem I like because it’s easy to visualize. In fact, <a href="https://x.com/endavid/status/1745527630521360395?s=20">I first solved it using the Godot Engine</a>, just so I could see it in 3D from the start.</p><p>Please read the full description of the problem <a href="https://adventofcode.com/2023/day/22">in the AoC website</a> for details. But the blunt summary is that you have to solve a game that it’s like a mixture of <a href="https://en.wikipedia.org/wiki/Tetris">Tetris</a> and <a href="https://en.wikipedia.org/wiki/Jenga">Jenga</a>, so I refer to it as <em>“Jengatris”</em>. 3-dimensional bricks or “pieces” fall from above until they stack. Then, in the first part of the problem, you have to find out which pieces are “essential”, that is, if such a piece gets removed other above it will fall. If more than one piece sustains another from above, then they are not “essential” (according to my definition of “essential”; of course if you remove both of them, the one above will fall).</p><p>In the second part of the problem, which it’s what we are interested in for the benchmark, you have to count how many pieces will fall if you were to remove one of the essential pieces. The answer to the problem is the sum of all the pieces that will fall for all the essential pieces.</p><p>Here’s a video made in Godot showing the result: <a href="https://youtube.com/shorts/xWipB6MSyRc?si=nyRK1pGQ3MT_ulIr">https://youtube.com/shorts/xWipB6MSyRc?si=nyRK1pGQ3MT_ulIr</a></p><p>In the first part of the video I let the pieces fall to find the solution of the first part. Then the screen flashes a bit because there are 974 essential pieces for my input, so I have to quickly simulate 974 scenarios to get the sum. Finally you can see I remove all the essentials, just to see more pieces fall (this is not part of the problem, but just for fun).</p><h3>Copyable game state</h3><p>Because we have to simulate each possibility for all the essential pieces, it is very convenient if we can easily create copies of the game state. This will also be very helpful when computing several solutions in parallel, because we want to avoid sharing any data to avoid race conditions.</p><p>In Swift we can simply use a struct, because structs in Swift are passed by value. In contrast, classes are passed by reference, so no data gets duplicated. So to be able to copy the whole game state, I simply declared it like this:</p><pre>struct GameState {<br>  var pieces: [AABB&lt;Int&gt;]<br>  var volume: VoxelVolume&lt;Int&gt;<br>}</pre><p>A game state contains a list of pieces described as integer Axis-Aligned Bounding Boxes (AABBs), and what I called a Voxel Volume, which it’s a 3-dimensional integer matrix that stores the ID of each piece, to know whether that integer coordinate is occupied or not.</p><p>Note that in C++ a struct behaves very differently. In C++ a struct is basically the same as a class, except that all its members are public by default. So to be really explicit that I want to duplicate the game state, I added a &#39;copy&#39; function, and explicitly deleted the copy constructor and the copy-assignment operator:</p><pre>struct GameState {<br>  std::vector&lt; AABB&lt;int&gt; &gt; pieces;<br>  std::shared_ptr&lt;VoxelVolume&lt;int&gt; &gt; volume;<br>  GameState(IntAABBList pieces, std::shared_ptr&lt;VoxelVolume&lt;int&gt; &gt; volume);<br>  std::shared_ptr&lt;GameState&gt; copy() const;<br>  GameState(const GameState&amp;) = delete;<br>  GameState&amp; operator=(const GameState&amp;) = delete;<br>};</pre><p>The copy function looks like this:</p><pre>std::shared_ptr&lt;Jengatris::GameState&gt; Jengatris::GameState::copy() const {<br>  std::vector&lt;AABB&lt;int&gt; &gt; p(pieces.begin(), pieces.end());<br>  return std::make_shared&lt;Jengatris::GameState&gt;(p, volume-&gt;copy());<br>}</pre><p>Note that the Voxel Volume has a copy function as well. You can see the whole code in Github: <a href="https://github.com/endavid/algoDeSwift/tree/main/AoC%202023">algoDeSwift/AoC2023</a>.</p><p>We have done the most important thing for concurrency. Now let’s see how to run the simulations in parallel.</p><h3>Parallel loop in Swift with GCD</h3><p>The sequential solution in Swift can be written functionally with the &#39;reduce&#39; function (remember that the answer to part 2 of the problem is the sum of all possible simulated scenarios):</p><pre>static func countFalls(state: GameState, ids: Set&lt;Int&gt;) -&gt; Int {<br>  return ids.reduce(0) { sum, i in<br>    let (_, n) = Jengatris.simulate(start: state, without: i)<br>    return sum + n<br>  }<br>}</pre><p>It is quite straightforward to rewrite a loop as a parallel loop with GCD:</p><pre>  static func concurrentCountFalls(state: GameState, ids: Set&lt;Int&gt;) -&gt; Int {<br>    let indexArray: [Int] = Array(ids)<br>    var counts = [Int].init(repeating: 0, count: indexArray.count)<br>    DispatchQueue.concurrentPerform(iterations: indexArray.count) { iteration in<br>        let id = indexArray[iteration]<br>        let (_, n) = Jengatris.simulate(start: state, without: id)<br>        counts[iteration] = n<br>    }<br>    return counts.reduce(0, +)<br>  }</pre><p>Notice that we created a shared resource, &#39;counts&#39;, where we save all the intermediate results. But we don&#39;t need any <a href="https://en.wikipedia.org/wiki/Lock_(computer_science)">mutex</a> for this because we aren&#39;t resizing the array and each thread will only write to its unique position, given by &#39;iteration&#39;. The number of threads created will be automatically decided by GCD depending on the number of cores of the CPU and the capabilities of the hardware. In my Mac mini M1 it creates 8 threads.</p><h3>Parallel loop in Swift with async/await</h3><p>As I mentioned in the introduction, Swift 5.5 introduced some keywords for asynchronous code: &#39;async&#39; and &#39;await&#39;. Note that because the code is asynchronous it doesn&#39;t necessarily mean it runs in parallel. For instance, Javascript is very asynchronous, but it&#39;s mostly single-threaded (unless you are using Workers). During each &quot;tick&quot; of the event loop the different callbacks get updated in Javascript.</p><p>But concurrent code is asynchronous by nature, so it is useful to have first-class citizens asynchronous keywords in the language to write concurrent code. You just need to flag a function with &#39;async&#39; to mark it asynchronous. And then you can use the &#39;await&#39; to wait for something to finish before continuing with the rest of the code, without actually blocking the execution of the program.</p><p>There’s a special function called &#39;withTaskGroup&#39; that it&#39;s very helpful for our example. It creates a <a href="https://developer.apple.com/documentation/swift/taskgroup">Task Group</a> where you can keep adding <a href="https://developer.apple.com/documentation/swift/task">Tasks</a>. In our case each task will be one of the simulations. Then, we simply wait for all the results to come back. Here&#39;s the code:</p><pre>static func countFallsAsync(state: GameState, ids: Set&lt;Int&gt;) async -&gt; Int {<br>      var sum = 0<br>      await withTaskGroup(of: Int.self) { group in<br>          for id in ids {<br>              group.addTask {<br>                  let (_, n) = Jengatris.simulate(start: state, without: id)<br>                  return n<br>              }<br>          }<br>          for await n in group {<br>              sum += n<br>          }<br>      }<br>      return sum<br>  }</pre><p>Here we don’t have to worry about the number of threads created either. The system will choose for us. The performance should be the same as with GCD.</p><h3>Parallel loop in C++ with threads</h3><p>Let’s see how the C++ code compares to Swift. Let’s start for writing down the sequential version of it. Instead of using the &#39;reduce&#39; function, I used a for-loop for this one because I think it&#39;s easier to read:</p><pre>size_t Jengatris::countFalls(const GameState&amp; state,<br>                             const std::unordered_set&lt;int&gt;&amp; ids)<br>  {<br>    size_t sum = 0;<br>    for (const auto&amp; id : ids)<br>    {<br>        std::unordered_set&lt;int&gt; moved;<br>        auto s = state.copy();<br>        auto _ = Jengatris::simulate(*s, id, &amp;moved);<br>        sum += moved.size();<br>    }<br>    return sum;<br>  }</pre><p>A simple solution that works is to create a thread for each element in the input. That creates lots of threads, though. My input has 974 entries, so that’s 974 threads. The code below creates a lambda function with the work each thread needs to do, creates all the threads, and then waits for all of them to finish with &#39;join&#39;:</p><pre>  size_t Jengatris::countFallsThreaded(const GameState &amp;state, const std::unordered_set&lt;int&gt; &amp;ids)<br>  {<br>    std::vector&lt;int&gt; idArray(ids.begin(), ids.end());<br>    std::vector&lt;size_t&gt; counts(ids.size());<br>    std::vector&lt;std::thread&gt; threads;<br>    auto parallelWork = [&amp;state, &amp;idArray, &amp;counts](int iteration) {<br>        int id = idArray[iteration];<br>        std::unordered_set&lt;int&gt; moved;<br>        auto s = state.copy();<br>        auto _ = Jengatris::simulate(*s, id, &amp;moved);<br>        counts[iteration] = moved.size();<br>    };<br>    // this will start MANY threads!! (974 threads for my input)<br>    for (size_t i = 0; i &lt; idArray.size(); i++)<br>    {<br>        threads.emplace_back(parallelWork, i);<br>    }<br>    // Wait for threads to finish<br>    for (auto&amp; thread : threads) {<br>        thread.join();<br>    }<br>    return std::accumulate(counts.begin(), counts.end(), 0);<br>  }</pre><h3>Parallel loop in C++ with async</h3><p>In C++ <a href="https://en.cppreference.com/w/cpp/thread/async">‘std::async’</a> is a function template used to run a function asynchronously, potentially in a separate thread which might be part of a thread pool. This is different from flagging a function asynchronous with ‘async’ in Swift.</p><p>This can be used in combination with &#39;futures&#39; to wait for results. Javascript programmers may be used to Futures when using Promises. These are the same. In fact, an <a href="https://en.cppreference.com/w/cpp/thread/future">std::future</a> can also be paired with an <a href="https://en.cppreference.com/w/cpp/thread/promise">std::promise</a>. But here we are interested in the asynchronous function. My code looks like this now:</p><pre> size_t Jengatris::countFallsAsync(const GameState &amp;state, const std::unordered_set&lt;int&gt; &amp;ids)<br>  {<br>    std::vector&lt;int&gt; idArray(ids.begin(), ids.end());<br>    std::vector&lt;std::future&lt;size_t&gt;&gt; futures;<br>    auto parallelWork = [&amp;state, &amp;idArray](int iteration) {<br>        int id = idArray[iteration];<br>        std::unordered_set&lt;int&gt; moved;<br>        auto s = state.copy();<br>        auto _ = Jengatris::simulate(*s, id, &amp;moved);<br>        return moved.size();<br>    };<br>    // Start asynchronous tasks<br>    for (size_t i = 0; i &lt; idArray.size(); ++i) {<br>        futures.push_back(std::async(std::launch::async, parallelWork, i));<br>    }<br>    // Wait for tasks to finish and accumulate the results<br>    // When I put a breakpoint here, Xcode says there are 372 threads.<br>    // Still lots, but less than 974...<br>    size_t total = 0;<br>    for (auto&amp; future : futures) {<br>        total += future.get();<br>    }<br>    return total;<br>  }</pre><p>The code is a bit ugly, though. We can do better with Threading Building Blocks (TBB).</p><h3>Parallel loop in C++ with C++17 and TBB</h3><p>C++17 does include parallel algorithms, such as <a href="https://en.cppreference.com/w/cpp/algorithm/transform_reduce.">transform_reduce</a>. You can pass an execution policy, and if you specify &#39;parallel&#39;, it should run in parallel. So my parallel loop can be cleanly written like this:</p><pre>  size_t Jengatris::countFallsParallel(const GameState &amp;state,<br>                             const std::unordered_set&lt;int&gt; &amp;ids)<br>  {<br>    return std::transform_reduce(<br>        std::execution::par,<br>        ids.begin(),<br>        ids.end(),<br>        size_t(0),<br>        std::plus&lt;&gt;(),<br>        [&amp;state](int id) {<br>            std::unordered_set&lt;int&gt; moved;<br>            auto s = state.copy();<br>            auto _ = Jengatris::simulate(*s, id, &amp;moved);<br>            return moved.size();<br>        }<br>    );<br>  }</pre><p>However, that code does not compile with Apple Clang. If you check the <a href="https://en.cppreference.com/w/cpp/compiler_support/17#C.2B.2B17_library_features">compiler support page</a>, parallel algorithms are not supported in Apple Clang. To compile that in macOS, I installed GCC with Homebrew, and TBB (see below). The code compiles and runs. However, it doesn’t seem to run in parallel. The performance is the same as the sequential version. So I rewrote it with Intel TBB.</p><p><a href="https://en.wikipedia.org/wiki/Threading_Building_Blocks">TBB</a> is a C++ template library developed by Intel for parallel programming. The code got slightly uglier, but here’s the same parallel loop:</p><pre>  size_t Jengatris::countFallsTBB(const GameState &amp;state,<br>                           const std::unordered_set&lt;int&gt; &amp;ids)<br>  {<br>    std::vector&lt;int&gt; idArray(ids.begin(), ids.end());<br>    size_t sum = tbb::parallel_reduce(<br>         tbb::blocked_range&lt;size_t&gt;(0, idArray.size()),<br>         size_t(0),<br>         [&amp;](const tbb::blocked_range&lt;size_t&gt;&amp; range, size_t localSum) {<br>             for (size_t i = range.begin(); i != range.end(); ++i) {<br>                 int id = idArray[i];<br>                 std::unordered_set&lt;int&gt; moved;<br>                 auto s = state.copy();<br>                 auto _ = Jengatris::simulate(*s, id, &amp;moved);<br>                 localSum += moved.size();<br>             }<br>             return localSum;<br>         },<br>         std::plus&lt;&gt;()<br>     );<br>     return sum;<br>  }</pre><p>For some reason, Homebrew doesn’t automatically find the headers and libraries, so I had to point at them manually. For reference, my compiler command is:</p><pre>g++-13 -std=c++17 -O3 -Wall -Wextra -pedantic <br>  -o advent advent2023-cpp/*.cpp -ltbb<br>  -I/opt/homebrew/Cellar/tbb/2021.11.0/include/<br>  -L/opt/homebrew/Cellar/tbb/2021.11.0/lib</pre><h3>Benchmark</h3><p>I’ve collected some numbers, mostly to verify that indeed the parallel code runs faster. I’ve compiled both Swift and C++ versions in Release mode optimizing for speed, not size, and averaged the values of a few runs. See the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*MJHpOaChu-uC4_62.png" /><figcaption>Running times of “Jengatris” with different implementations and compilers</figcaption></figure><p>A few observations:</p><ul><li>Any version runs much faster than GDScript, which takes 24 seconds.</li><li>The C++ code runs a bit faster than Swift.</li><li>Clang performs slightly faster than GCC.</li><li>All the parallel implementations perform similarly to each other, in their respective languages/compilers, except for the “GCC parallel” which doesn’t seem to be working as expected.</li><li>The C++ solution with many threads seems slightly slower than the other C++ solutions in GCC. Presumably because of the overhead of creating that many threads, although it doesn’t seem to make a difference in Clang.</li></ul><h3>Summary</h3><p>There are multiple ways to do computations in parallel in both Swift and C++, some approaches more modern than others. However, always prepare some benchmark to actually check that the solution works. You may get a surprise like the one I got with C++17 (if someone knows why the parallel execution is being ignored, please let me know).</p><p>In the C++ world, go to the <a href="https://en.cppreference.com/w/cpp/compiler_support">Compiler Support</a> to find out which features of the standard are actually implemented in the compiler you are using. If you are targetting multiple platforms, you may not want to use the parallel algorithms from C++17.</p><p>C++ sounds a bit scarier than Swift, but I hope with these comparisons you see C++ doesn’t need to be that much verbose.</p><p>Thanks to Eric Wastl for <a href="https://adventofcode.com/2023/about">Advent of Code</a>.</p><p>All the code can be found in Github: <a href="https://github.com/endavid/algoDeSwift/tree/main/AoC%202023">algoDeSwift/AoC2023</a>.</p><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=104"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3606628954a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mantis Shrimp: Image Differences with Metal shaders]]></title>
            <link>https://medium.com/real-time-rendering/mantis-shrimp-image-differences-with-metal-shaders-6e1cc9e38e7c?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e1cc9e38e7c</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 12:38:13 GMT</pubDate>
            <atom:updated>2024-11-13T19:41:35.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TtUMmzVN4pCze4Ez.png" /><figcaption>Mantis Shrimp image diff tool for macOS</figcaption></figure><h3>Image Diffs and Mantis Shrimp</h3><p>An <em>image diff</em> is an image that visualizes the difference between 2 other images in some manner. There are many image diff tools around, but I often find myself wanting to write my custom difference operator, depending on the thing I’m looking for in the image.</p><p>A mentor I had created once an internal tool in Javascript to do image diffs where you could write a snippet of Javascript. It was very useful, but the code ran in the CPU for each pixel, so it was quite slow. Also, it could only deal with the types of images that the browser could handle, that is, usually just 8-bit images in sRGB color space. He called this web app <a href="https://en.wikipedia.org/wiki/Mantis_shrimp">Mantis Shrimp</a>, one of his favorite animals. The reason: mantis shrimps have up to 16 different type of photoreceptor cells. In comparison, humans have just 3 different type of cells (although some people have <a href="https://en.wikipedia.org/wiki/Tetrachromacy">tetrachromacy</a>). But who needs that many types of photoreceptors when we have technology and software to enhance what we see?</p><p>I borrowed that awesome name for my <a href="http://mantisshrimp.endavid.com/">Mantis Shrimp app</a>, although this app can do more than the original. It can compute image diffs of any 2 images that macOS supports, that is, up to 32 bits per color channel, and different types of color spaces. It does it in real time because the operations happen in the GPU, so pixel operations are done in parallel, not sequentially. The app comes with different preset operators, but you can write your own with Metal shaders as well.</p><p>Because you can write shaders with it, you can do much more than just image differences. You can even create animations with it, pretty much like what <a href="https://www.shadertoy.com/">Shader Toy</a> does in the WebGL world.</p><p>Here’s a 30-second video summary of what Mantis Shrimp can do:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FijJRaahCF0c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DijJRaahCF0c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FijJRaahCF0c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3842427baa1efb48cbf1bb9a7fed2f85/href">https://medium.com/media/3842427baa1efb48cbf1bb9a7fed2f85/href</a></iframe><p>In this article I’m going to give you some details about the actual implementation of Mantis Shrimp.</p><h3>SwiftUI and Metal</h3><p>In WWDC2023 Apple announced new functions to modify a Swift view with custom shaders: <a href="https://developer.apple.com/documentation/swiftui/view/coloreffect(_:isenabled:)">colorEffect</a>, <a href="https://developer.apple.com/documentation/swiftui/view/layereffect(_:maxsampleoffset:isenabled:)">layerEffect</a>, and <a href="https://developer.apple.com/documentation/swiftui/view/distortioneffect(_:maxsampleoffset:isenabled:)">distortionEffect</a>. Distortions modify the location of each pixel, whereas the other two modify its location. I assume they must be fragment/pixel shaders. You can find some nice examples in <a href="https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-metal-shaders-to-swiftui-views-using-layer-effects">How to add Metal shaders to SwiftUI views using layer effects — a free SwiftUI by Example tutorial</a>.</p><p>However, if you want to do something more complex than that and you plan to use SwiftUI, you will need to create a custom <a href="https://developer.apple.com/documentation/swiftui/uiviewrepresentable">UIViewRepresentable</a>. You can find an example of this in the Apple forums: <a href="https://forums.developer.apple.com/forums/thread/119112">MetalKit in SwiftUI</a>.</p><p>For Mantis Shrimp I followed that route, and I encapsulated all the rendering using the Renderer class of my <a href="https://github.com/endavid/VidEngine">VidEngine</a>, an open-source graphics engine I created a couple of years back. VidEngine uses Swift and Metal, but at the time of writing I haven&#39;t released the changes to make it work with macOS and SwiftUI.</p><h3>Mantis Shrimp render passes</h3><p>In VidEngine a <em>“render graph”</em> is simply an ordered list of what I call <em>“plugins”</em>. A plugin encapsulates one or more render passes. A real render graph should be a Directed Acyclic Graph where the nodes are render passes and each node is connected to others through read and write dependencies between the resources they use. One of the best explanations I found of render graphs is in this blog: <a href="https://poniesandlight.co.uk/reflect/island_rendergraph_1/">Rendergraphs and how to implement one</a>.</p><p>Because there are only 3 plugins in Mantis Shrimp, the dependencies are hard-coded. One of the plugins is for <em>Mesh Shaders</em>, that I will discuss in a separate article. Most of the time that plugin is disabled. The other two plugins are the DiffPlugin and the OutPlugin.</p><p>The DiffPlugin is where the actual operation happens. It consists of a simple vertex shader that draws a full-screen rectangle, and a fragment shader with the per-pixel operation. This fragment shader can be substituted by your own code. Apart from the texture coordinates of each pixel, I pass some other variables such as the time in seconds, so you can create animations. Read <a href="http://mantisshrimp.endavid.com/manual.html">the manual</a> for details.</p><p>The DiffPlugin writes the output to an image that it&#39;s the same size, the same bit-depth, and the same color space as the first input image. You can only export images as PNG at the moment, but it should preserve its size, its bit depth, and its color space.</p><p>What you see on screen, though, it’s what the OutPlugin shows you. Its input is the output of the DiffPlugin, and it adapts it to the current view. By default it uses point sampling, so if your image is a few pixels wide, you should see a pixelated image, not a blurred one (if it were linearly interpolated). This is important because in an image diff tool you want to see the details, not a blurred version of them! The view supports display-P3 color space by default, but the pixel format that gets selected may vary depending on the hardware.</p><p>The OutPlugin may also apply the final gamma where necessary. Some pixel formats support the sRGB flag for automatically applying the gamma (or inverse gamma when reading), but it&#39;s not for all pixel formats and its support varies depending on the hardware, so the operation needs to be done in a shader.</p><h3>A diff fragment shader</h3><p>A simple difference operator looks like this:</p><pre>fragment half4 main() {<br>  float4 a = texA.sample(sam, frag.uv);<br>  float4 b = texB.sample(sam, frag.uv);<br>  float4 diff = abs(a-b);<br>  float4 out = float4(uni.scale * diff.rgb, a.a);<br>  return half4(out);<br>}</pre><p>The signature of the function is predefined, and &quot;main&quot; is just a shortcut I&#39;ve defined in Mantis Shrimp, because the function signature can&#39;t be overridden. The actual signature looks like this:</p><pre>fragment half4 diffFragment(<br>  VertexInOut frag [[stage_in]],<br>  texture2d texA [[ texture(0) ]],<br>  texture2d texB [[ texture(1) ]],<br>  sampler sam [[ sampler(0) ]],<br>  constant Uniforms&amp; uni [[ buffer(0) ]])</pre><p>So apart from the fragment texture coordinates, you get two textures, a texture sampler, and some extra variables. The operation above is just subtracting the RGB values of both textures and setting the output to be the absolute value of the difference. Here’s a summary of the different diff presets in Mantis Shrimp:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Plv2VJJr2KrUmr5B.jpg" /><figcaption>Mantis Shrimp image diff presets</figcaption></figure><p>When no image is assigned, a white texture is sampled by default. That means that the default RGB diff operator acts as a negative if you only assign one image. See the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*LSDUkW-dOFAZBpiB.jpg" /><figcaption>Negative painting from Iranian-British artist Soheila Sokhanvari. By default Mantis Shrimp will negate the input.</figcaption></figure><h3>A shader sandbox</h3><p>Mantis Shrimp can also be used to simply test shaders. People familiar with <a href="https://www.shadertoy.com/">Shader Toy</a> or <a href="https://twigl.app/">TwiGL</a> will know that you can create beautiful animations with just a fragment shader.</p><p>A common mathematical tool for that purpose is the use of <a href="https://en.wikipedia.org/wiki/Signed_distance_function">Signed Distance Functions</a> (SDF). An SDF is a function that tells you how far a point is from the surface of the object. When you are inside the object, the distance is negative, hence the “signed”. Because in a fragment shader you get the (u,v) texture coordinate of the output, you can use an SDF to draw simple 2D figures. For instance, a circle centered at (0,0) is just the length of the (u,v) vector minus the radius of the circle.</p><p>If you apply transforms to the (u,v) coordinates, you can do more fancy things. One common transformation is to multiply the (u,v) coordinates by a number greater than one and then taking its fractional part, the decimals. In this manner, you will have repeating coordinates that go from 0 to 1, and then from 0 to 1 again. If you use the time variable to change these transforms across time, you can create some interesting animations. Mantis Shrimp comes with this SDF animation preset to get you started:</p><pre>float sdCircle(float2 p, float r) {<br>  return length(p) - r;<br>}<br>float2x2 rotationMatrix(float angle) {<br>  float s=sin(angle), c=cos(angle);<br>  return float2x2( float2(c, -s), float2(s, c) );<br>}<br>fragment half4 main() {<br>  float t = uni.time;<br>  float aspect = uni.resolution.x / uni.resolution.y;<br>  float2 uv0 = frag.uv * 2 - 1;<br>  uv0.x *= aspect;<br>  float2x2 r = rotationMatrix(cos(t));<br>  uv0 = r * uv0;<br>  float2 uv = fract(2 * uv0) - 0.5;<br>  float d = sdCircle(uv, 0.5) * exp(-length(uv0));<br>  float s = uni.scale + 1;<br>  d = sin(d*s + t) / s;<br>  d = 0.01 / abs(d);<br>  float2 uvImage = 0.5 * float2(sin(t) + 1, cos(t) + 1);<br>  float4 color = texA.sample(sam, uvImage);<br>  float4 out = float4(d * color.rgb, 1);<br>  return half4(out);<br>}</pre><p>The output looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*o9cd-7wc-Ogy1icdIgc3Og.png" /></figure><p>See video here: <a href="http://mantisshrimp.endavid.com/pix/2023-12-14-mantisshrimp-circles.mp4">2023–12–14-mantisshrimp-circles.mp4</a></p><p>SDFs can also be used to represent 3D surfaces. The SDF for a sphere is the same as a circle, but we use the length of an (x,y,z) coordinate instead of a 2D coordinate. Usually these 3D SDFs are combined with a technique called <a href="https://en.wikipedia.org/wiki/Ray_marching">Ray Marching</a>, which consists of casting a ray for every (u,v) coordinate in the screen, starting in the near plane of the camera frustum, and advance the ray along depth based on the value of the SDF. Remember that the SDF tells you the distance to the surface, so you basically know how far you need to move.</p><p>There are plenty of resources online to learn about this. Check out <a href="https://iquilezles.org/">Iñigo Quilez home page</a>. He’s the creator of Shader Toy and he has many interesting resources. The important thing for this article is to highlight that you can use Metal shaders in Mantis Shrimp to create this kind of animations (or “demos”) as well. See these ray-marched cubes (not <a href="https://en.wikipedia.org/wiki/Marching_cubes">marching cubes</a>!):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O5H8aQrQbfPkzJ3mty0vng.png" /></figure><p>See video here: <a href="http://mantisshrimp.endavid.com/pix/2024-01-29-Genuary-SDF-ray-marching.mp4">2024–01–29-Genuary-SDF-ray-marching.mp4</a></p><p>Here’s the shader code for the cubes example: <a href="https://github.com/endavid/MantisShrimpExamples/blob/main/Genuary2024/29-sdf-raymarching.metal">Genuary 29-sdf-raymarching.metal</a>. You can find other examples I did for the <a href="https://genuary.art/">#Genuary</a> challenge in that folder: <a href="https://github.com/endavid/MantisShrimpExamples/tree/main/Genuary2024">endavid/Genuary2024</a>.</p><h3>Beyond fragment shaders</h3><p>Apart from the fact that the original intent of this app was simply comparing 2 images, it felt strange to allow custom vertex shaders. What would be the point if you can’t change the geometry? I would need a way to upload geometry to Mantis Shrimp. But then, that would be a model viewer, rather than an image diff tool!</p><p>However, being able to play with shaders that do more generic things programmatically is still attractive. That’s why I added support for mesh shaders in version 1.1 of Mantis Shrimp. I will discuss this in the next article, but the basic idea is that you have a mesh shader with no geometry at all as input, and you create your own geometry programmatically in the shader. So you can create 3D graphics procedurally, without necessarily using ray marching and SDF functions in a fragment shader. Here’s an example of some cubes generated in a mesh shader: <a href="https://github.com/endavid/MantisShrimpExamples/blob/main/Genuary2024/10-cubes.metal">Genuary 10-cubes.metal</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5k46OEXC3DJVZHsaSg7Fg.png" /></figure><p>See video here: <a href="http://mantisshrimp.endavid.com/pix/2024-01-10-Genuary-Hexagonal.mp4">2024–01–10-Genuary-Hexagonal.mp4</a></p><p>If you use Mantis Shrimp &amp; you like it, please leave me a comment in the App Store. And if you post creations in Twitter or Instagram, use the hashtag <a href="https://twitter.com/hashtag/MantisShrimpApp">#MantisShrimpApp</a> so I can find them 😊</p><p>Happy coding!</p><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=103"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e1cc9e38e7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/real-time-rendering/mantis-shrimp-image-differences-with-metal-shaders-6e1cc9e38e7c">Mantis Shrimp: Image Differences with Metal shaders</a> was originally published in <a href="https://medium.com/real-time-rendering">Real Time Rendering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troubleshooting “Disk not ejected properly” on a LaCie USB-C HDD]]></title>
            <link>https://medium.com/@endavid/troubleshooting-disk-not-ejected-properly-on-a-lacie-usb-c-hdd-ed7594243a6a?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed7594243a6a</guid>
            <category><![CDATA[lacie]]></category>
            <category><![CDATA[hardware]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 17:57:06 GMT</pubDate>
            <atom:updated>2024-02-20T17:57:06.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XjKpUuRwIYehkxFT.png" /><figcaption>Trying out different cables on a LaCie drive to get rid of ejection errors</figcaption></figure><h3>Endless “Disk not ejected properly” popups</h3><p><a href="https://x.com/endavid/status/1741771652285821367?s=20">On January 1st</a> I woke up my Mac Mini M1 from its sleep and I had hundreds of popups saying “Disk not ejected properly”. I had left my external USB-C Lacie Rugged HDD 5 TB drive plugged in, and something had gone horribly wrong.</p><p>The first annoying thing is getting rid of the popups. I think there was a popup every 2 minutes. During 12 hours, that’s 360 popups 😣 Because they are system notifications, they are not grouped into a single app, so you can’t batch-dismiss them. After some search, I found this magic CLI command to get rid of them all:</p><pre>killall NotificationCenter</pre><p>But that didn’t make the problem go away.</p><h3>How to reproduce</h3><p>If you search for that message, you will find people with tons of different problems. If you call Apple support, they’ll make you go through several standard procedures, but you will need some test case to verify that it works. In my case, the issue can be 100% reproduced with the following:</p><ol><li>Plug the USB-C HDD to the USB-C port of the Mac (any of the ports)</li><li>Make sure the drive works by reading a file in it.</li><li>Go to the Apple menu and set the Mac to <em>Sleep</em>.</li><li>Wait 4 minutes.</li><li>Make sure the drive turns off (I touch it to make sure it stopped spinning)</li><li>Wake up the Mac. At that point, I get one <em>“Disk not ejected properly”</em> popup.</li></ol><p>You will need some patience to do tests, but it’s important to have a test case that you can reproduce every time.</p><h3>Things can get worse</h3><p>I ignored the issue because it only happened when the computer went to sleep, so I would disconnect the drive when I finished work. In 2020 I had a similar issue, but at the time I solved it by disabling <em>“Put disks to sleep whenever possible”</em> in the macOS power settings. But that option didn’t help this time.</p><p>But one day things got worse: I got “Disk not ejected properly” every 2 minutes even while I was working with the disk and the computer was awake. At that point, I called Apple Support (chatted twice, called twice).</p><h3>Troubleshooting with Apple Support</h3><p>Unplugging and plugging the drive again didn’t fix the continuous disconnections. After running <em>First Aid</em> on the drive and verifying it’s fine, the Apple support team told me to start the Mac in <em>safe mode</em>, and restart again. That fixed the most pressing problem of the drive disconnecting every 2 minutes, but the issue of the drive disconnecting when the computer goes to sleep persisted.</p><p>The other thing they will tell you to do is to create a <em>test admin user</em> and try from that account. The issue persisted for me.</p><p>Apple support suspected the cable and the disk, but I wasn’t totally convinced, because why would restarting the Mac fix the most pressing issue, the ejections every 2 minutes? A few weeks later after that first call with Apple, I got that same problem again and I fixed it with a restart. Why unplugging &amp; plugging the drive doesn’t fix it, but a computer restart does? I did suspect the driver, or my Mac (spoiler: I was wrong).</p><p>Anyway, let’s remember that the issue wasn’t totally fixed with a restart because when the Mac went to sleep it still caused the abrupt disconnection of the drive.</p><h3>Seagate (lack of) customer support</h3><p>Because the Apple engineer suspected the cable that came with my LaCie disk, I tried to contact LaCie. LaCie support is now part of Seagate support. They have a chatbot, and eventually you can chat with a person (or perhaps it wasn’t?) I pasted all my notes to an agent and I got this: “I understand that you are having issue while connecting to computer. Am I correct?” 😅 Didn’t I give enough detail?</p><p>After 30 minutes, the only thing I got was a suggestion to run First Aid. I can use Google and ChatGPT, thanks for nothing 😑 They also let me know that they don’t offer support by email to individual users… (In 2017 I had a similar issue with another of their drives, and I did all the interactions by email at the time.)</p><h3>Battery of tests</h3><p>I’m going to list down all the things I did to try to isolate the problem. Remember I didn’t know yet what caused it.</p><ul><li>Connect the HDD to the Mac mini USB-A port with a USB-C to USB-A cable (the one that comes with the PS5 controller). I left the drive plugged all night and it worked perfectly, so one would think that the drive is fine.</li><li>Connect the HDD with that USB-C to USB-A cable to a Macbook Pro with macOS Catalina. It works perfectly. Unfortunately that Mac doesn’t have a USB-C port so I can’t test the other cable.</li><li>Connect the HDD to the Mac mini USB-C port with a USB-C cable from an Android phone. With that cable, I don’t get alerts saying that it got disconnected, but all of a sudden the files can’t be read. It seems more dangerous, because it appears connected, but actually the files don’t work. I got <em>“The file xxx could not be opened”</em> when I tried to read any file, and I got some corrupt files while I was writing to the drive. So it’s not really working and it’s super dangerous ⚠️</li><li>Update from macOS Sonoma 14.2.1 to 14.3. It didn’t fix the issue.</li><li>I tried plugging the HDD with the USB-C to USB-A adapter with a USB hub connected to the USB-C port and the drive didn’t turn on! I remember it working at some point in the past… Any other device works, though, so perhaps there’s not enough power for this drive?</li></ul><p>After these tests, I headed to the Apple Store and I did more tests with an engineer at the Genius Bar:</p><ul><li>Using the LaCie USB-C cable, we connected the HDD to one of their Macs, a Macbook Air M2 running Sonoma 14.1.2. Doing the sleep test, the issue reproduced. So it seems unrelated to my Mac mini. It’s either the cable, the disk, or the drivers.</li><li>Using a Thunderbolt 4 data cable (£75) the error happened again 😞 So it wasn’t a problem exclusive to my cable.</li><li>Using a 2m Apple 240W thunderbolt charge cable (£29) the error DOES NOT happen 🎊</li></ul><p>But why? The more expensive data cable says it’s 100W, so it seemed to be related to the power. For the time being, I got the thunderbolt charge cable. I left it plugged all night and it was working correctly. But I wanted to know what was going on. And did I really want to use that cable? (It turns out that that cable wasn’t ideal.)</p><h3>Handshaking in a 3rd call with Apple</h3><p>I called Apple support again. The engineer explained that when you connect the drive to the computer, there’s a <em>handshake</em> that determines whether to use <em>Thunderbolt</em>, or regular <em>USB-C</em>. Even if the port looks the same, Thunderbolt and USB-C are actually different connections. The Mac must think it’s thunderbolt even if I use a regular USB-C cable. And then it’s when it becomes unstable. When it goes to sleep, it tries to keep a register of the connection so it doesn’t have to do another handshake, or spark a new connection again. Then, when it wakes up it sends data as it was Thunderbolt, when it’s not.</p><p>That’s the explanation I got and I was suggested to keep using the 240W thunderbolt charge cable. That doesn’t seem to explain why it didn’t work with the Thunderbolt 4 cable, though.</p><p>Apple told me to speak to the manufacturer.</p><h3>Speed tests with Seagate support</h3><p>I explained the whole thing to Seagate customer support again, and I got this reply:</p><blockquote><em>“Upon checking the issue is from cable not from drive. According to your statement, you have tried with different PC and different cable. You will get the pop up like disk not ejected properly except this 240W thunderbolt charge cable. Kindly use your drive with 240W thunderbolt charge cable. Unfortunately your drive is supported only with this cable — 240W thunderbolt cable.”</em></blockquote><p>I asked why do they sell the drive with a cable that doesn’t work, then, but I got no reply.</p><p>The chat is quite surreal and sometimes I wonder whether I am speaking to a human. Except if it were ChatGPT the grammar would be correct, so I do believe they are human. After 1 hour 40 minutes in the chat, I managed to speak to a more helpful person who asked me to do some speed tests.</p><p>If you are doing this, I recommend using a big file to get consistent results. I zipped my local Movies folder, and that gave me a 1GB ZIP file. To test the copying speed from the Mac mini SSD drive to the external drive, I used rsync. You can use it like this (“LaCie 5TB” is the name of my HDD):</p><pre>rsync -ah --progress ~/Movies.zip /Volumes/LaCie\ 5TB</pre><p>I tried with the Apple cable I got in the Apple store, and with the original LaCie cable:</p><ul><li>With 240W thunderbolt charge cable: 36.87 Mbytes/sec</li><li>With USB-C to USB-A adapter cable (for reference): 38.21 Mbytes/sec</li><li>With USB-C cable from LaCie: 123.62 Mbytes/sec</li></ul><p>So it’s much slower with the charge cable, as slow as using USB-A 😢 But I couldn’t reliably use the LaCie cable. Or the £75 Thunderbolt 4 data transfer cable. Seagate says the drive is compatible with both Thunderbolt 4 and USB-C. The Mac Mini M1 port is Thunderbolt 3. Seagate escalated this issue and they told me to wait 24 hours.</p><p>Perhaps the HDD was needing more power than it should and that’s why it wants the 240W cable? Or perhaps the operating system/driver doesn’t know how much power it needs to give to the HDD? Shouldn’t the driver somehow detect this? And the macOS UI certainly could have a better way to close those 360 popups…</p><p>In the Seagate help page on this issue they say many users have reported this “after updating the macOS”, so I thought perhaps it could be Sonoma-related. Read <a href="https://www.seagate.com/gb/en/support/kb/disk-not-ejected-properly-on-mac/">“Disk not ejected properly on Mac”</a>.</p><p>I decided to speak again with Apple Support.</p><h3>4th call with Apple Support: USB 2.0 &amp; HFS+</h3><p>In this last call with Apple I shared my screen and they helped me troubleshoot and install some things:</p><ul><li>We installed the LaCie tool kit to see if they provide firmware updates, but there aren’t any. See <a href="https://www.lacie.com/gb/en/support/downloads/">LaCie Downloads</a> and <a href="https://www.seagate.com/support/downloads/seatools/">Firmware downloads</a>.</li><li>They recommended me to use the <a href="https://apps.apple.com/us/app/blackmagic-disk-speed-test/id425264550?mt=12">Blackmagic Disk Speed Test app</a> for testing the disk speed.</li><li>They asked me to format the drive again with GUID Partition Map, and <em>HFS+ (Mac OS Extended, Journaled)</em>, with the Disk Utility in macOS Sonoma. I was using APFS, but that’s only recommended for SSD drives, and there is no advantage using it in HDD drives.</li></ul><p>We didn’t manage to fix the problem, but I got faster transfers after the formatting. I was getting about 85 Mbytes/sec with APFS (using the Disk Speed Test app; my rsync test was faster), but something around 130 Mbytes/sec with HFS+. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*mKQyN7DlRnqnISLi.jpg" /><figcaption>Speed tests of my HDD LaCie drive using different cables and file systems</figcaption></figure><p>The other thing I learned is that <a href="https://www.apple.com/uk/shop/product/MU2G3ZM/A/240w-usb-c-charge-cable-2m">the 240W charging cable</a> is USB 2.0, not USB 3.0. That’s why it’s slower. In contrast, <a href="https://www.apple.com/uk/shop/product/MU883ZM/A/thunderbolt-4-usb%E2%80%91c-pro-cable-1m">the Thunderbolt 4 data cable</a> supports USB 3.0 up to 10 Gbits/second, and it also supports USB 4.0, which it’s 40 Gbits/sec.</p><p>So the drive worked when I used USB 2.0, in either the USB-A or the USB-C port, but started failing otherwise. I had to speak to Seagate again.</p><h3>Drive Replacement</h3><p>After another support chat session with Seagate, they told me there must be something wrong with the drive. Since it was still under the 2-year warranty, they asked me to send it back to them, to an address in the UK (tracked, about £8 in the UK).</p><p>A week later I got a new drive.</p><p>I did all the tests several times. I also left the computer sleeping for 30 minutes to be really sure. The problem was gone 🥳</p><p>Just some notes, in case someone uses the same drive:</p><ul><li>I ran the LaCie Setup that comes preinstalled in the drive, and the drive got formatted with GUID Partition Map and HFS+, which matches Apple’s suggestion 👍</li><li>The Setup app redirects you to lyvetst.seagate.com/?sn=… to register the drive, but that URL does not exist. I edited the link to point to lyveint.seagate.com instead, and that worked.</li><li>Disk Speed Test says the speed is: Write 141.2 MB/s, Read 135.5 MB/s 👍</li></ul><p>Happy drive now 🥳</p><h3>Summary</h3><p>Debugging hardware issues is really a pain. Sometimes it’s easier to live with the faulty drive than trying to get to the bottom of it.</p><p>However, I must say that Apple support was very helpful and that I learned lots of things in the process. I can’t say the same from Seagate, because we still haven’t learned what piece of their hardware would cause such a strange behaviour. They sent me a working refurbished drive in the end, but I spent a lot of time and some money to resolve an issue that it was their fault to begin with.</p><p>In any case, I hope this article helps other people struggling with the infamous <em>“Disk not ejected properly”</em> troubleshoot the issue and figure out whether it’s a problem caused by the drive itself or not.</p><p>Thank you very much to the people in Apple support and Seagate support that gave me all the information I’ve mentioned in this article.</p><h3>References</h3><ul><li>How do dismiss many “disk not ejected properly” notifications: <a href="https://apple.stackexchange.com/a/325548/97810">Apple StackExchange</a></li><li><a href="https://support.apple.com/en-gb/101847">If you see “disk not ejected properly” on your Mac Pro (2023)</a> (August 21, 2023). (Not Mac mini!). They also say “Apple is aware of this issue and a resolution is planned for a future macOS update.”</li><li><a href="https://www.seagate.com/gb/en/support/kb/disk-not-ejected-properly-on-mac/">Disk Not Ejected Properly On Mac Seagate help article.</a></li><li><a href="https://forums.developer.apple.com/forums/thread/83688?answerId=779406022#779406022">Disk Not Ejected Properly thread on Apple developers forums</a> (I posted some of this information there)</li></ul><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=102"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed7594243a6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EnDavid: My retrospective of 2023]]></title>
            <link>https://medium.com/@endavid/endavid-my-retrospective-of-2023-77a43b343267?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a43b343267</guid>
            <category><![CDATA[retrospectives]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 22:04:27 GMT</pubDate>
            <atom:updated>2024-01-21T22:04:27.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fxRdCAYsfeWrADVi.jpeg" /><figcaption>Happy new year 2024 🐲 &amp; a visual summary of my 2023</figcaption></figure><h3>My 2023 as a story</h3><p>2023 has been another year of ups and downs. The worst happened at the end of the year, when I lost my job. I’ve already blogged about it in <a href="http://endavid.com/index.php?entry=100">“8+ years programming for fashion”</a>. The best of 2023 happened in June, when <em>I got married 👨‍❤️‍👨</em>. But many other good things happened as well.</p><p>I’ve been quite busy with job interviews this month, and it feels I’m lagging behind lots of things. I finished <a href="https://adventofcode.com/">Advent of Code</a> in January, and I’m 12 days behind in <a href="https://genuary.art/">Genuary</a>. But I guess it’s good to be busy. But I didn’t want January to end without having written a retrospective of 2023. I think it’s always a good exercise to stop and look back, specially to celebrate the achievements. Otherwise it’s easy to get lost in the worries of the present, as if everything is always dark.</p><p>Speaking of darkness, I can’t believe last year we spent the new year in Tel Aviv, and this year there’s war going on there… It seems the number of ongoing wars only keeps increasing… ☹️ Let’s go back to positive things.</p><p>Apart from our wedding, another highlight of my 2023 were the trip <em>S</em> (plural) to Japan. After almost 5 years, I managed to go to Japan and renew my residence card. I was quite stressed about that since the beginning of the pandemic, so I’m so happy I was able to solve that.</p><p>In the first trip, I went for 3 weeks, in February &amp; March. I took some days off, but I also worked remotely. I woke up at 4am, worked from 6am to 10am, then went out &amp; enjoy daylight, and then worked again from 4pm to 10pm. That time in the evening I could have meetings with the team in the UK. I felt a bit tired, but I wasn’t sleepy. I think it was all so exciting that it felt quite nice to make the most of my day.</p><p>One random day I saw a random poster of a <em>Kabuki play of Final Fantasy X</em>. Kabuki is a traditional all-male theater, so at first I thought it was quite funny to see the male actors “cosplaying” as some of the female leads. But then I thought this was a very unique opportunity, and I was lucky enough to be there at the time, since it was shown only for a month and a half. So I bought a ticket, I took an extra day off, and I went to see it. It was very long, from 12pm to 9pm, but it was really worth it. One of the best things I’ve ever seen. I was very moved. I wrote about it in my “otaku” blog — in Spanish, though: <a href="https://www.focotaku.com/2023/03/final-fantasy-x-kabuki.html">Final Fantasy X Kabuki</a>.</p><p>I visited Japan again in May. It was a very short trip, just 3 nights, tagging along my partner’s work. But our flight back to London was cancelled so we stayed 2 extra nights. Perfect for me 😂 I had brought my work laptop, and there was a WeWork office next to the hotel, so I went there one day. I was able to meet some friends I couldn’t see in March. Again, I felt I made most of my time there. I was very tired after a very long flight, but I arrived in the morning and I directly went to Akihabara, met a friend, he showed me some nice interesting retro places, I did some shopping, then we went back to Yokohama, and there we had a really good time in a local sushi restaurant. I uploaded a YouTube video (Spanish again, but with English subtitles) with the talk we had in that restaurant, talking about my time in the Japanese game industry: <a href="https://youtu.be/-PVlhIXZ_EM?si=FPm67E0q2mK7kxmC">Gossip: game devs in Japan, with Ahgueo &amp; Fibroluminique</a>.</p><p>As I said earlier, I got married/civil-partnered in June. Although nothing has changed (we’ve been 14 years together), it was nice to have some friends &amp; family over to celebrate. It was a small ceremony, but we all had a great time. My brother came with his family, and I spent a few fun days with them in London.</p><p>In September, we visited Barcelona and we had another celebration there with friends and family, in a Catalan <a href="https://en.wikipedia.org/wiki/Masia">masia</a>. And then my sister visited us in November for my birthday and we saw the early Christmas lights in London &amp; ate lots of delicious Asian food &amp; Japanese desserts. For Xmas, we went to Barcelona again and we had a lovely time there. We usually avoid Xmas, because flights are always very expensive and very crowded, so it was nice to spend <em>Xmas at home</em> after a while.</p><p>Time to rewind and list the achievements.</p><h3>Work</h3><p>Lots of <em>Generative AI</em> this year. I thought we were doing quite well, but stuff happens… Read summary in here: <a href="http://endavid.com/index.php?entry=100">“8+ years programming for fashion”</a>.</p><h3>Indie development</h3><p>I’m still demotivated with game development. I have some games I wanted to build in my backlog, but it feels a bit pointless if no one is going to play them… But I did release some things:</p><ul><li>I released <a href="http://syllabits.endavid.com/">Syllabits</a> for the browser, Windows and Mac. It’s in <a href="https://endavidg.itch.io/syllabits">itch.io</a>. And almost every Friday evening we’ve been playing it at work, in the Practice mode. I’m glad they liked it in my office! 🥹</li><li>In summer I released maintenance updates for all my iOS games. No new features.</li><li>In December I released a new macOS app called <a href="http://mantisshrimp.endavid.com/">Mantis Shrimp</a>. It was <em>listed 5th</em> in the Top Paid macOS Developer Tools this month! Although only briefly. It was something I was making on the side and that I used at work to compare images. I’ve been doing the Genuary challenge with it, and it’s fun. See my <a href="https://www.instagram.com/p/C149_GlIh6u/?hl=en">#Genuary1 in Instagram</a>.</li></ul><h3>Blogging</h3><p>I didn’t write any technical articles in 2023 😓 Well, I did write one article for my company, but it didn’t get the green light, so it will remain unpublished.</p><p>In the Spanish geek blog, the only thing interesting is the article about the FFX New Kabuki I mentioned earlier.</p><h3>Vlogging</h3><p>This year I decided to spend more time gaming, and I streamed most of my plays on Twitch. I did upload some YouTube videos as well, but I intended to do more technical ones, and I failed to deliver. All my videos are usually in Spanish, but I’ve added some English subtitles on request.</p><ul><li>I did a couple of rants on ChatGPT, and WWDC23 in my “serious” channel: <a href="https://www.youtube.com/@endavidg/videos">@endavidg</a>.</li><li>I uploaded a couple of solutions to Advent of Code 2022 (but not 2023 yet…) in my channel on Swift programming: <a href="https://www.youtube.com/@algoDeSwift/videos">@algoDeSwift</a>.</li><li>I did upload lots of videos to <a href="https://www.youtube.com/@focotaku/videos">@focotaku</a> 🙈 But it was mainly an edit of my play-through of Final Fantasy XIII from 2022. I thought it was good for learning because I was playing it in Japanese and I wrote some language notes in each one of the video descriptions.</li><li>I did upload some other types of videos to <a href="https://www.youtube.com/@focotaku/videos">@focotaku</a>, like book reviews of Japanese novels, and some other game reviews. But my most viewed video is one a bit off from the “otaku” culture. It’s <a href="https://youtu.be/fqJqjUqQs8s?si=V34Ml36-pdrfxV4C">a summary I did about the BBC documentary on the scandal involving Johnny Kitagawa</a> (it has English subtitles), the deceased top figure in Japanese music industry / male model agency. The video has 850 views — perhaps not much, but quite a record for me. I’m glad it’s been informative. I did 3 videos on the topic and they are all quite visited.</li></ul><h3>Learning</h3><ul><li>More <em>Python</em> &amp; some <em>C++</em> at work</li><li>I did all the Advent of Code 2023 in <em>Swift</em>, and I did one of the problems in <em>Godot 4</em> as well, just for the fun of visualizing it: <a href="https://www.instagram.com/p/C1-Mf5II4rs/">AoC 2023 Day 22 on Instagram</a>.</li><li>I practiced some <em>Metal</em> again to create <a href="http://mantisshrimp.endavid.com/">Mantis Shrimp</a>.</li></ul><h3>Leisure</h3><p>I already mentioned several trips in the first section. I wanted to catch up with some JRPG titles, so I did play &amp; cleared these games:</p><ul><li><em>Nier Replicant</em> — I enjoyed it very much. The soundtrack is amazing. There’s are some concerts in Europe in February, including Barcelona, but I failed to get tickets… 😢</li><li><em>Nier Automata</em> — amazing as well.</li><li><em>Final Fantasy XVI</em> — Epic! It was a present from a friend, and then I also got a PS5 as a present! 🤩 I’m actually replaying it because I enjoyed it very much.</li></ul><p>I wasn’t planning to read any novels, but I ended up reading 3 novels in Japanese by the same author, <em>Keigo Higashino</em>. My partner has lots of his novels at home and I got curious. I was surprised I could read them relatively easily. When I tried reading novels in Japanese in the past, it has been usually hard. But the difficult novels were SF or JRPG-related, so the vocabulary may have been weird… I actually read another novel in Japanese, “Egoist”, an LGBT story 🏳️‍🌈, and started another one about NieR, so it’s my record on Japanese novels reading so far! I also read a novel in English called <em>“Tomorrow and Tomorrow and Tomorrow”</em>, about game development. It was really moving. See my <a href="http://endavid.com/lists/readings08.html">list of readings</a>.</p><h3>Wishes for 2024</h3><p>Again, let’s hope 2024 brings <em>peace ☮️🕊</em></p><p>I haven’t written down my personal goals yet, but I hope I can write some technical blog posts this year. I have one planned about Metal and Mesh shaders, related to the development of <a href="http://mantisshrimp.endavid.com/">Mantis Shrimp</a>.</p><p>I also want to upload some videos about Swift development.</p><p>I started the year by joining a badminton group 🏸, so hopefully I do more exercise this year!</p><p>And I hope to visit Japan again some time this year.</p><p>Best wishes to everyone. My dragon-themed new year greetings card at the top of this article (I was also lagging behind on my new year greetings… I started drawing them already in January…)</p><p>Again, <em>Happy New Year 2024 🐲</em></p><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=101"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a43b343267" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8+ years programming for fashion]]></title>
            <link>https://medium.com/@endavid/8-years-programming-for-fashion-2dcd3fe7e87d?source=rss-fb3d57a95c51------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dcd3fe7e87d</guid>
            <category><![CDATA[retrospectives]]></category>
            <category><![CDATA[fashion]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[tryon]]></category>
            <category><![CDATA[ar]]></category>
            <dc:creator><![CDATA[David Gavilan]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 12:55:07 GMT</pubDate>
            <atom:updated>2024-11-19T14:08:12.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sz__Skrtf2nWGkFf.jpg" /><figcaption>A visual summary of some of the stuff I’ve worked on at Metail</figcaption></figure><h3>A retrospective</h3><p>My time at Metail has come to an end, and I thought it was a good time to write a retrospective longer than usual. It’s been an interesting ride, so I think it’s worth to look back and review the things I learned.</p><p>8 years and a half is the longest I’ve ever been in a company. The main reason for staying this long has been the incredibly welcoming atmosphere and the friendly people that worked there, but there were also very interesting technical challenges that aligned well with my technical background. Let me give you a bit more detail.</p><h3>How I ended up here</h3><p>I’m a graphics programmer and before Metail I’ve always worked in the games industry. The games industry is full of amazing people, and very passionate as well. I suppose passion can sometimes transform into angry faces and needless shouting. The year I left the games industry I wasn’t going through the best of times. My mum was fighting cancer, and then she got a brain stroke. So it was hard coping with the stress of work. My counsellor suggested that a change may be good.</p><p>I got a random phone call from a recruiter and they talked about Metail. I wasn’t very interested in fashion at the time, but the technology that they described sounded quite interesting. They needed someone with knowledge in Computer Graphics, but also with a good understanding of Computer Vision and Image Processing. Although professionally I had mostly worked on graphics and optimization, my PhD was on Computer Vision and Image Processing. So this sounded like a nice combo! I passed the interviews and I got in.</p><h3>The MeModel era</h3><p>The main product when I entered Metail was called the MeModel (see figure on top). It was a virtual try-on system where users would enter their measurements to generate a virtual avatar, and then they could try on clothes. It was a web application that retailers could install in their websites. The technology was a mixture of 2D, photographs of clothes and faces, and 3D for the body shapes. The garment physics were done in 2D.</p><p>The technology I was maintaining was a server-side renderer written in DirectX 10, C#, and C++. After getting familiar with the pipeline and the asset publishing, I started by optimizing the performance by removing redundant textures and unnecessary processing. Sometimes graphics code becomes spaghetti 🍝, but a simple PIX GPU frame capture can reveal very interesting things quite easily.</p><p>I also worked on improving the visuals. I introduced a new avatar with more joints and I contacted an ex-colleague to help us author more poses. I changed the skin shaders, and I wrote a WebGL tool to help us tweak the skin to match the photographic heads (see <a href="https://medium.com/real-time-rendering/skin-colour-authoring-using-webgl-101a05865bdd">Skin colour authoring using WebGL</a>).</p><p>I also did some server-side work. Because I had some previous experience with NodeJS, I suggested building a small server in NodeJS for scaling and monitoring. This sat on top of AWS services, but it let us do more complex logic suited to our renderer. The new bottleneck was the starting time of the renderer service -it took several minutes to boot. I looked at some old spaghetti code and rewrote it into a math paper, and then rewrote the whole thing with simpler matrix multiplications. Also, I turned most of the asset loading into lazy initializations, for a final starting time under 2 seconds.</p><p>I built several internal visualization tools, and other tools for the outsourcing teams to help them see what they were creating, for faster iterations (from days to hours). I also became Engineering Manager of a team of 7 and I mentored other developers. I did lots of interesting things.</p><p>Unfortunately, the MeModel didn’t quite take off and the company struggled financially until we were acquired by one of our investors.</p><h3>The EcoShot era</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6bLdspm-fm3_Cxt8.jpg" /><figcaption>From left to right: a scan of myself, my scanatar superimposed on a photograph, and a couple of EcoShot renders</figcaption></figure><p>When we shut down the MeModel service I was working on an idea from our CTO. He thought that in order to strive for realism, we needed to do the garment simulation in 3D. We were experimenting with some 3D CAD cloth authoring software at the time, and I thought it would be relatively simple to reuse all the technology we had to create something for that software.</p><p>Unfortunately, all the client-side developers had to go. So I had to build everything on my own. But the CAD software let you write plugins in Python, so it was quick to get started. I like C++, but Python let us build things faster in this scenario.</p><p>I started by getting a body scan of myself and using our software to automatically rig it, add some poses, and import it into the software. That’s what we call a <em>“scanatar”</em>, i.e. an avatar originated from a scan. When I saw the draping of a single garment in different sizes on an accurate model of my body, I thought this would be a game changer.</p><p>I built a beta of the software in a couple of months, all self-contained -there was no service at the time. After the beta, I worked with the network architect to build a service. I built a renderer that used V-Ray to render the garments using raytracing. For the 2D composition I used mainly ImageMagick, and some OpenCV scripts written by our R&amp;D team.</p><p>Apart from EcoShot, we worked on other projects, such as the European <a href="https://etryon-h2020.eu/">eTryOn project</a> (see my <a href="https://www.youtube.com/live/yNpV6w7PYZw?si=5_2SiDuT2Lkas-rk&amp;t=7200">XR4Fashion talk from 2:00:00, From 3D designs to Lens Studio: Challenges in faithful garment representation</a>), and some other AR collaborations with Snap (see me wearing a virtual Puma tracksuit in the figure on top, using one of my Snapchat filters). So I got to touch some game engines as well, like Unity or Lumberyard, and Lens Studio (see some mentions in <a href="https://medium.com/real-time-rendering/reasons-for-a-solo-dev-to-love-godot-engine-80447b2854a0">Reasons for a solo dev to love Godot Engine</a>).</p><p>2023 has been an interesting year as well with the boom of Generative AI (GenAI for short). I worked on releasing new features and new GenAI avatars for the EcoShot plugin at a very fast pace. Many customers were impressed by the results, and we’ve been getting requests for new imagery.</p><h3>The End &amp; The Future</h3><p>Unfortunately, we ran out of time. EcoShot will continue to exist in the hands of Tronog (see the announcement: <a href="https://metail.com/blog/metail-tronog-partnership/">Metail and Tronog enter into a strategic partnership to transfer EcoShot and make AI-generated fashion accessible to all</a>). By the way, can you tell which models are real and which are GenAI?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iV_gah5eB3p9SXJp.jpg" /><figcaption>Image from Metail website showing some EcoShot &amp; GenAI models</figcaption></figure><p>There are still many exciting things to come for EcoShot in 2024, but I will be moving on. At the time of writing, I don’t know yet where to, though. It seems it was still early for many apparel companies to adopt 3D, so I may not be working again in fashion. Who knows.</p><p>I was attracted to the idea of doing something good for the planet. The fashion industry, specially fast fashion, is a machinery of creating waste. Creating virtual samples before they are manufactured should help reduce some waste. Also, showing customers how the garment fits in different body shapes should help reduce returns. But these technologies still have a slow adoption. I hope that GenAI will revolutionize that.</p><p>While I look for my next adventure, I will be working on some side projects. I recently released an image diff app called <a href="http://mantisshrimp.endavid.com/">Mantis Shrimp</a> 🦐. I borrowed the name from a Javascript web tool made by my team lead when I entered Metail. He loves Mantis Shrimps because of the 16 or so photoreceptor cells in their eyes. I thought it was a nice way of coming back full circle.</p><p>So long and thanks for all the fish 🐋🌈</p><p>Happy New Year 2024 🐲</p><p><em>Originally published at </em><a href="http://endavid.com/index.php?entry=100"><em>http://endavid.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dcd3fe7e87d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>