<?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 Lukas Kuppers on Medium]]></title>
        <description><![CDATA[Stories by Lukas Kuppers on Medium]]></description>
        <link>https://medium.com/@lkuppers11?source=rss-2808fede0568------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lIVB_SmJYwfFZINCrgwVVw.jpeg</url>
            <title>Stories by Lukas Kuppers on Medium</title>
            <link>https://medium.com/@lkuppers11?source=rss-2808fede0568------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:40:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lkuppers11/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[A Simple RTS Design Pattern for Unity Games]]></title>
            <link>https://medium.com/@lkuppers11/a-simple-rts-design-pattern-for-unity-games-2851740fbfb0?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/2851740fbfb0</guid>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[strategy-games]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 17:02:43 GMT</pubDate>
            <atom:updated>2023-12-22T17:02:43.293Z</atom:updated>
            <content:encoded><![CDATA[<h4>A basic framework to handle object selection and command delegation in an RTS game</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EBONOvNX945jNgmB" /><figcaption>Photo by <a href="https://unsplash.com/@mirapolis?utm_source=medium&amp;utm_medium=referral">Dave Photoz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>In this Article</h4><ul><li><a href="#335a"><strong>Background</strong></a></li><li><a href="#a427"><strong>Overview of the Design</strong></a></li><li><a href="#dc95"><strong>Implementing the Design Pattern</strong></a></li><li><a href="#ea31">Create the Required Interfaces</a></li><li><a href="#2257">Create the Object Selection Manager</a></li><li><a href="#d894">Implement Control Logic for a specific Unit Type</a></li><li><a href="#62b9"><strong>Additional Info</strong></a></li></ul><h3>Background</h3><p>I’ve recently been building out a prototype for a <a href="https://github.com/LukasKuppers/unity-rts-logging-game">logging RTS game</a> in Unity. I’ve used Unity extensively for other types of projects in the past, like basic mobile games, or 3rd person games (like my game <a href="https://store.steampowered.com/app/2234720/Project_Sail/">Project Sail</a>). However, I’ve never tried to make an RTS-like game where the player is in control of many units that can all operate asynchronously.</p><p>I ran into a number of stumbling blocks while building out the foundations of my prototype, and often found myself asking “What is the <em>right</em> way to do this”? One of the main issues was:</p><p>How can I issue commands to different types of units?</p><p>Different units might require different control schemes, so we can’t just use a centralized class that is capable of controlling each separate unit type based on which one is selected. (Technically, you could, but it would get very messy very fast…)</p><p>While I’m sure there are many sophisticated solutions to this problem, I ended up developing a simple solution that is easy to implement, and can easily be expanded to handle new complexity.</p><h3>Overview of the Design</h3><p>My solution can essentially be boiled down to this:</p><ul><li>A single, centralized class (say, ObjectSelectionManager ) keeps track of which unit/object is currently selected, and handles any raycasting logic used to select objects in the game.</li><li>Selectable objects have a ISelectableObject component attached, which among other things, exposes a public function GetPlayerControlMode() that returns a class that implements the IPlayerControlMode interface.</li><li>IPlayerControlMode classes implement the custom logic specific to controlling a single unit. This is done via a public function HandleNewSelection() which gets called by the ObjectSelectionManager every time the player clicks a new object.</li></ul><p>With all the interface and method names, that might seem complex, but the gist is simple:</p><ul><li>A single class makes raycasts when the player clicks the screen, to get information about which object was clicked.</li><li>That class also keeps track of which unit is currently being controlled, and feeds the newly clicked object to that units control logic.</li><li>If nothing is selected, we will try to select the object that is clicked next.</li></ul><h3>Implementing the Design Pattern</h3><p>A full working version of the implementation can be found in my prototype project: <a href="https://github.com/LukasKuppers/unity-rts-logging-game">unity-rts-logging-game</a>.</p><h4>Create The Required Interfaces</h4><p>First, we need two interfaces which are central to this design pattern:</p><ul><li>ISelectableObject — This will be implemented by MonoBehaviour scripts that are attached to any object we want to be selectable. (any unit, for example).</li></ul><pre>public interface ISelectableObject<br>{<br>    /// Gets the control mode for this object<br>    public IPlayerControlMode GetPlayerControlMode();<br><br>    /// Called when the object is first selected<br>    public void OnSelect();<br><br>    /// Called when the object is deselected<br>    public void OnDeselect();<br>}</pre><ul><li>IPlayerControlMode — Player control modes handle the custom logic to control a unit. Any unique unit should have its own control mode. Additionally, player control modes don’t need to be MonoBehaviours.</li></ul><pre>using System;<br>using UnityEngine;<br><br>public interface IPlayerControlMode<br>{<br>    /// Event invoked when control mode is finished<br>    public event Action SelectionForfeited;<br><br>    /// Give the control a newly selected object to handle<br>    public void HandleNewSelection(GameObject selectedObject, Vector3 selectionPoint);<br>}</pre><ul><li>Note the SelectionForfeited event. This should be invoked by the control mode when it is done issuing commands. (Say, after we tell a unit to move, it will invoke the event, signaling the object selection manager to deselect that unit). This allows a single unit to handle multiple clicks to create a command.</li></ul><h4>Create the Object Selection Manager</h4><p>As stated before, the ObjectSelectionManager is a centralized class that delegates new clicks from the player to specialized control logic implemented by IPlayerControlMode classes. It’s primary purpose is to track which object is currently selected, and select newly clicked objects if nothing is selected.</p><pre>using UnityEngine;<br>using UnityEngine.InputSystem;<br><br>public class ObjectSelectionManager : MonoBehaviour<br>{<br>    [SerializeField]<br>    private GameObject cameraObject;<br><br>    private Camera cam;<br>    private IPlayerControlMode currentControlMode;<br>    private GameObject currentSelectedObject;<br><br>    private void Awake()<br>    {<br>        cam = cameraObject.GetComponent&lt;Camera&gt;();<br>    }<br><br>    private void Update()<br>    {<br>        if (Input.GetMouseButton(1))<br>            OnClick();<br>    }<br><br>    // called every time the player clicks<br>    private void OnClick()<br>    {<br>        GameObject clickedObject = GetClickedObject(out Vector3 clickedPoint);<br>        if (!clickedObject)<br>            return;     // abort if nothing was clicked<br><br>        if (currentControlMode == null)<br>        {<br>            // If clicked object is selectable, select it<br>            ISelectableObject selectableObject = clickedObject.GetComponent&lt;ISelectableObject&gt;();<br>            if (selectableObject != null)<br>            {<br>                // select a newly clicked object<br>                currentSelectedObject = clickedObject;<br><br>                currentControlMode = selectableObject.GetPlayerControlMode();<br><br>                // subscribe to the control modes Selection forfeited event<br>                currentControlMode.SelectionForfeited += OnCurrentSelectionForfeited;<br>                selectableObject.OnSelect();<br>            }<br>        }<br>        else<br>        {<br>            // A unit is currently selected, and ready to receive commands<br>            // feed clicked object to current player control mode<br>            currentControlMode.HandleNewSelection(clickedObject, clickedPoint);<br>        }<br>    }<br><br>    // called when the currently selected unit is done issuing commands<br>    private void OnCurrentSelectionForfeited()<br>    {<br>        currentSelectedObject.GetComponent&lt;ISelectableObject&gt;().OnDeselect();<br><br>        // unsubscribe from the selection forfeited event<br>        currentControlMode.SelectionForfeited -= OnCurrentSelectionForfeited;<br><br>        currentSelectedObject = null;<br>        currentControlMode = null;<br>    }<br><br>    // basic raycast logic to get which object was clicked<br>    private GameObject GetClickedObject(out Vector3 clickPoint)<br>    {<br>        Ray ray = cam.ScreenPointToRay(Input.mousePosition);<br>        clickPoint = Vector3.zero;<br><br>        if (Physics.Raycast(ray, out RaycastHit hit))<br>        {<br>            clickPoint = hit.point;<br><br>            GameObject colliderObject = hit.collider.gameObject;<br>            ParentPointer parentPointer = colliderObject.GetComponent&lt;ParentPointer&gt;();<br>            return parentPointer ? parentPointer.GetParent() : colliderObject;<br>        }<br>        return null;<br>    }<br>}</pre><p>As you can see, the ObjectSelectionManager is acutally quite simple. It just passes information about which object was clicked to the currently selected unit.</p><h4>Implement Control Logic for a Specific Unit Type</h4><p>At this point, the framework is already in place, and we just need to create custom control logic for each unit. How this is done depends on your game!</p><p>As an example, I’ll show how to control a basic humanoid unit that walks to the location the player clicked in the game.</p><ol><li><strong>Implement ISelectableObject</strong></li></ol><pre>using UnityEngine;<br><br>// note that we are inheriting from MonoBehavior and ISelectableObject<br>public class HumanoidSelectableObject : MonoBehaviour, ISelectableObject<br>{<br>    private IPlayerControlMode playerControlMode;<br><br>    private void Awake()<br>    {<br>        // we will implement HumanoidControlMode next<br>        playerControlMode = new HumanoidControlMode(gameObject);<br>    }<br><br>    public IPlayerControlMode GetPlayerControlMode()<br>    {<br>        return playerControlMode;<br>    }<br><br>    // it&#39;s not necessary to implement these<br>    public void OnSelect() { }<br><br>    public void OnDeselect() { }<br>}</pre><p>2.<strong> Implement IPlayerControlMode</strong></p><pre>using System;<br>using UnityEngine;<br><br>// notice that this is not a monobehavior (not attached to a gameobject)<br>public class HumanoidControlMode : IPlayerControlMode<br>{<br>    // invoke once we&#39;ve told the unit where to go<br>    public event Action SelectionForfeited;<br><br>    private GameObject agentObject;  // the unit we&#39;re controlling<br>    private NavMeshAgent navAgent;   // we&#39;ll control the unit using navmesh<br><br>    public HumanoidControlMode(GameObject agentObject)<br>    {<br>        this.agentObject = agentObject;<br>        navAgent = agentObject.GetComponent&lt;NavMeshAgent&gt;();<br>    }<br><br>    // called when the player clicks a point to move to<br>    public void HandleNewSelection(GameObject selectedObject, Vector3 selectionPoint)<br>    {<br>        // set the destination to the clicked point<br>        navAgent.SetDestination(selectionPoint);<br><br>        // tell the object selection manager that we&#39;re done <br>        // controlling this unit. It will be deselected.<br>        SelectionForfeited?.Invoke();<br>    }<br>}</pre><p>As you can see, we’re using basic NavMeshAgent logic to move the unit to the position we clicked.</p><p>In this example, we forfeit the selection of the unit every time a new click is received. It’s important to note though, that a unit can handle many consecutive clicks before it invokes SelectionForfeited .</p><h3>Additional Info</h3><p>I’ve shown a basic example of how to use this design pattern for RTS games, but this is only a small piece of the puzzle.</p><p>If you’re developing an RTS game, I highly suggest you check out the <em>Command Pattern</em>, which is useful for issuing sequences of commands to units. Unity has an official page on the command pattern <a href="https://unity.com/how-to/use-command-pattern-flexible-and-extensible-game-systems">here</a>.</p><p>If you look at my own <a href="https://github.com/LukasKuppers/unity-rts-logging-game">RTS game prototype</a>, you’ll notice I’m using the command pattern.</p><p>Also, it’s common to want to outline selected units in an RTS game. A super useful (and free) asset exists for this purpose, which is far easier that implementing a custom solution: <a href="https://assetstore.unity.com/packages/tools/particles-effects/quick-outline-115488">Quick Outline</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2851740fbfb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extrude a Custom Mesh along Splines in Unity]]></title>
            <link>https://medium.com/@lkuppers11/how-to-extrude-a-custom-mesh-along-splines-in-unity-833a97440c1b?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/833a97440c1b</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[procedural-generation]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[spline]]></category>
            <category><![CDATA[unity3d]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 04:48:15 GMT</pubDate>
            <atom:updated>2023-12-18T15:39:47.809Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Guide to using Unity’s Splines to extrude custom meshes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*HXyGcU3nHREq7iHD7b64Yw.png" /><figcaption>A sample road created using these methods</figcaption></figure><p>Unity recently released it’s own spline implementation as part of the Splines package. Splines are great for many use cases, but one of the most common use cases is to generate a procedural mesh (such as a road).</p><p>The Splines package comes with SplineExtrude.cs by default, but this can only extrude a tube-like shape over the spline. Custom meshes are not supported by default.</p><p>I recently needed to generate procedural roads for a prototype I’m working on, so I decided to create my own solution, which I’ll show here.</p><h4>In this Guide:</h4><ul><li><a href="#977e"><strong>Overview of Extrusion Strategy</strong></a></li><li><a href="#dc0c">Template Mesh</a></li><li><a href="#49a5">Copying the Template Mesh</a></li><li><a href="#6790"><strong>Creating a Simple Mesh Extrusion Script</strong></a></li><li><a href="#eca1">Sampling the Spline</a></li><li><a href="#b29e">Setup The Procedural Mesh</a></li><li><a href="#7baf">Implement the Overall Mesh Generation Algorithm</a></li><li><a href="#6d81">Helper Methods</a></li><li><a href="#afc8">Copy the Template Mesh to Fill a Spline Segment</a></li><li><a href="#a25e"><strong>Other Considerations</strong></a></li><li><a href="#1f42"><strong>Conclusion</strong></a></li></ul><p><strong>TLDR: </strong><a href="https://github.com/LukasKuppers/unity-spline-extrusion/tree/main">This Repo</a> has the complete mesh extrusion script.</p><h3>Overview of Extrusion Strategy</h3><p>Lots of sophisticated (and complicated) algorithms could be employed to extrude custom meshes along a spline. I don’t like complexity, so here’s the gist of how this basic method works:</p><p>We will create a simple template for our mesh (in some modelling software like Blender). Then, we will copy this template repeatedly across the spline to form one coherent mesh.</p><h4>Template Mesh</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*pLcqA-sa2WTVuU1f-K0JPw.png" /><figcaption>The template mesh I used</figcaption></figure><p>Above you can see an image of the template mesh I created in Blender. Essentially, the template mesh is a single segment of the overall mesh we want to generate. The key limitation that applies is that the mesh must be a 2D shape extruded in a single direction. There cannot be any intermediate vertices.</p><blockquote>Note: The mesh origin (depicted as the orange dot in the above picture) will be the position where the spline runs along the mesh. For my case, I wanted the surface of the road to lie on the spline, so origin is positioned on the surface of my road template.</blockquote><h4>Copying the Template Mesh</h4><p>With a template mesh exported to Unity, we are ready to extrude the mesh over a spline. The approach to doing this is actually pretty easy:</p><ol><li>Sample positions along the spline where we want to place edges of our mesh — more sampled positions will result in a more detailed mesh.</li><li>For every two adjacent sampled positions, create a duplicate of the template mesh that will fill the gap between the positions. That means that one edge of the mesh will be placed at one of the sampled positions, and the other edge will be placed at the next sampled position. See the diagram below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*AsVuLq-R-o2ynHmlH5-a7A.png" /></figure><p>In the diagram, the yellow circles are the sampled positions along the spline, the black lines are the edges of the mesh segments, and every gap (labelled as mesh segments 0, 1, 2…) will be filled with copies of the template mesh.</p><p>The benefit of extruding the template mesh in this way is that we don’t need to worry about the specifics of how the mesh is formed (via the triangles array). All we need to do is create copies of the template mesh and correctly position and orient the endpoints to line up along the spline.</p><h3>Creating a Simple Mesh Extrusion Script</h3><p>In this section I’ll show how to create a basic mesh extrusion script that implements the above method. However, for a better and complete script, see <a href="https://github.com/LukasKuppers/unity-spline-extrusion/tree/main">this GitHub repo</a>.</p><h4>Sampling the Spline</h4><p>Firstly, we need to sample positions along the spline to know how to orient edges of our extruded mesh. Since this is useful in general for working with Splines, I’ll put it in a separate Util.cs file.</p><pre>using System.Collections.Generic;<br>using UnityEngine;<br>using UnityEngine.Splines;<br>using Unity.Mathematics;<br><br>public static class Util<br>{<br>    /// &lt;summary&gt;<br>    /// Returns the positions, tangents, and upVectors for points along a spline separated by distance &#39;interval&#39;. <br>    /// Includes the beginning and end of the spline<br>    /// &lt;/summary&gt;<br>    /// &lt;param name=&quot;spline&quot;&gt;The spline to sample&lt;/param&gt;<br>    /// &lt;param name=&quot;containerTransform&quot;&gt;The transform of the object holding the spline&lt;/param&gt;<br>    /// &lt;param name=&quot;interval&quot;&gt;The distance between sample points&lt;/param&gt;<br>    /// &lt;param name=&quot;positions&quot;&gt;The output position array&lt;/param&gt;<br>    /// &lt;param name=&quot;tangents&quot;&gt;The output tangent array&lt;/param&gt;<br>    /// &lt;param name=&quot;upVectors&quot;&gt;The output upVector array&lt;/param&gt;<br>    /// &lt;returns&gt;whether or not the operation succeeded&lt;/returns&gt;<br>    public static bool SampleSpline(Spline spline, Transform containerTransform, float interval, <br>        out Vector3[] positions, out Vector3[] tangents, out Vector3[] upVectors)<br>    {<br>        // get the length of the spline in world space<br>        Matrix4x4 transformationMat = Matrix4x4.TRS(containerTransform.position, containerTransform.rotation, containerTransform.lossyScale);<br>        float splineLength = SplineUtility.CalculateLength(spline, transformationMat);<br><br>        // ensure the interval is valid<br>        if (interval &lt;= 0 || interval &gt; splineLength)<br>        {<br>            positions = null;<br>            tangents = null;<br>            upVectors = null;<br>            return false;<br>        }<br><br>        List&lt;Vector3&gt; positionList = new List&lt;Vector3&gt;();<br>        List&lt;Vector3&gt; tangentList = new List&lt;Vector3&gt;();<br>        List&lt;Vector3&gt; upVectorList = new List&lt;Vector3&gt;();<br><br>        // loop through spline, sampling at regular intervals<br>        float tInc = interval / splineLength;<br>        for (float t = 0; t &lt;= 1f; t += tInc)<br>        {<br>            bool success = SplineUtility.Evaluate(spline, t, out float3 position, out float3 tangent, out float3 upVector);<br>            if (!success)<br>            {<br>                positions = null;<br>                tangents = null;<br>                upVectors = null;<br>                return false;<br>            }<br><br>            Vector3 newPosition = new Vector3(position.x, position.y, position.z);<br>            Vector3 newTangent = new Vector3(tangent.x, tangent.y, tangent.z);<br>            Vector3 newUpVector = new Vector3(upVector.x, upVector.y, upVector.z);<br><br>            positionList.Add(newPosition);<br>            tangentList.Add(newTangent);<br>            upVectorList.Add(newUpVector);<br><br>            if (t &lt; 0.999f &amp;&amp; t + tInc &gt; 1f)<br>                t = 1f - tInc; // ensure that very end of spline gets sampled no matter what<br>        }<br><br>        positions = positionList.ToArray();<br>        tangents = tangentList.ToArray();<br>        upVectors = upVectorList.ToArray();<br>        return true;<br>    }<br>}</pre><p>The Method SampleSpline() shown above returns an array of positions, tangents, and up vectors, representing the orientation at each sampled position. (So position[i], tangent[i], and upVector[i] all refer to the same point). Importantly, the Method takes float interval as an argument, which is the amount of space we want separating our final mesh segments.</p><p>Note the use of the <a href="https://docs.unity.cn/Packages/com.unity.splines@1.0/api/UnityEngine.Splines.SplineUtility.html">SplineUtility</a> class used, which is a helper provided within the UnityEngine.Splines namespace that we can use to get information about a spline.</p><h4>Setup the Procedural Mesh</h4><p>Next, we’ll set up a class that we can attach to a spline gameobject that will actually extrude our template mesh along the spline. The basic class definition is shown below:</p><pre>using System.Collections.Generic;<br>using System.Linq;<br>using UnityEngine;<br>using UnityEngine.Splines;<br><br>public class SplineMeshExtrude : MonoBehaviour<br>{<br>    [SerializeField]<br>    private Mesh extrusionTemplateMesh;  // the template mesh<br>    [SerializeField]<br>    private float extrusionInterval = 10f;  // the distance between mesh edges<br><br>    private MeshFilter meshFilter;<br>    private SplineContainer splineContainer;<br>    private Spline spline;<br><br>    private Vector3[] templateVertices;  // used later to generate the mesh<br><br>    private void Awake()<br>    {<br>        meshFilter = gameObject.GetComponent&lt;MeshFilter&gt;();<br>        if (!meshFilter)<br>            Debug.LogError($&quot;SplineMeshExtrude: Awake: Gameobject {gameObject.name} does not have an attached mesh filter.&quot;);<br><br>        splineContainer = gameObject.GetComponent&lt;SplineContainer&gt;();<br>        spline = splineContainer.Spline;<br><br>        Mesh generatedMesh = GenerateMesh();  // we&#39;ll implement GenerateMesh later<br>        meshFilter.mesh = generatedMesh;  // add the mesh to the MeshFitler<br>    }</pre><p>The above code just sets up everything we need to generate our mesh. It calls GenerateMesh() which we will implement later.</p><p>Note that the gameobject this script is attached to must also have the Spline and a MeshFilter attached.</p><blockquote>Note: You’ll also want to attach a MeshRenderer to this gameobject, so that you can actually see the mesh once its been generated!</blockquote><h4>Implement the Overall Mesh Generation Algorithm</h4><p>Now lets build out the overal mesh generation algorithm. This is where we’ll call the spline sampling utility we created earlier, as well as define the vertices , triangles , normals , and uv arrays required by our mesh.</p><pre>private Mesh GenerateMesh()<br>    {<br>        Mesh mesh = new Mesh();  // instantiate a new mesh<br>        // call the util to get the intermediate spline positions<br>        bool success = Util.SampleSpline(spline, transform, extrusionInterval, <br>            out Vector3[] positions, out Vector3[] tangents, out Vector3[] upVectors);<br>        <br>        // error handling<br>        if (!success)<br>        {<br>            Debug.LogError(&quot;SplineMeshExtrude: GenerateMesh: Error encountered when sampling spline. Aborting&quot;);<br>            return mesh;<br>        }<br><br>        // instantiate lists to hold our vertices, triangles, normals, and uvs<br>        List&lt;Vector3&gt; vertices = new List&lt;Vector3&gt;();<br>        List&lt;int&gt; triangles = new List&lt;int&gt;();<br>        List&lt;Vector3&gt; normals = new List&lt;Vector3&gt;();<br>        List&lt;Vector2&gt; uvs = new List&lt;Vector2&gt;();<br><br>        // explained later<br>        (int[] firstEdge, int[] secondEdge) = GetEdgeIndicies(extrusionTemplateMesh.vertices);<br><br>        // explained later<br>        templateVertices = CollapsePoints(extrusionTemplateMesh.vertices);<br>  <br>        // loop through the sampled spline positions<br>        for (int i = 0; i &lt; positions.Length - 1; i++)<br>        {<br>            // append data to each list representing a new copy of the template<br>            AppendMeshSegment(vertices, triangles, normals, uvs,<br>                positions[i], tangents[i], upVectors[i], <br>                positions[i + 1], tangents[i + 1], upVectors[i + 1],<br>                firstEdge, secondEdge);<br>        }<br><br>        // set the mesh data<br>        mesh.vertices = vertices.ToArray();<br>        mesh.triangles = triangles.ToArray();<br>        mesh.normals = normals.ToArray();<br>        mesh.uv = uvs.ToArray();<br><br>        return mesh;<br>    }</pre><p>This Method calls some other methods we have yet to implement, but the overall algorithm is clearly shown: we sample the spline, and then loop through our samples, creating copies of our template between every adjacent pair of sampled positions (which is handled by the AppendMeshSegment() method).</p><h4>Helper Methods</h4><p>Above, two helper methods were called:</p><ul><li>GetEdgeIndicies() : This method takes our template mesh vertices as an argument, and returns two lists of integers, firstEdge and secondEdge . The index of every vertex in our template mesh that is part of the first edge will be included in firstEdge — the same logic applies for secondEdge . We need these indicies separated so that we can orient both edges of the template mesh separately.</li><li>CollapsePoints() : This method takes our template mesh vertices as an argument, and returns a new array of Vector3 . We need it to get the local position of each vertex relative to a specific point on the spline — this will be more clear later.</li></ul><p>Here’s the implementation of both methods:</p><pre>private (int[] first, int[] second) GetEdgeIndicies(Vector3[] templateVertices)<br>    {<br>        // initialize lists<br>        List&lt;int&gt; firstIndicies = new List&lt;int&gt;();<br>        List&lt;int&gt; secondIndicies = new List&lt;int&gt;();<br><br>        // loop through each vertex in the template mesh<br>        for (int i = 0; i &lt; templateVertices.Length; i++)<br>        {<br>            // we can determine which edge a point is part of based<br>            // on its z-coordinate. This means that our template mesh <br>            // needs to be extruded along the z-axis!<br>            if (templateVertices[i].z &lt; 0)<br>                firstIndicies.Add(i);<br>            else<br>                secondIndicies.Add(i);<br>        }<br><br>        return (firstIndicies.ToArray(), secondIndicies.ToArray());<br>    }<br><br>// returns a new array, and does not modify the input array<br>private Vector3[] CollapsePointsOnAxis(Vector3[] points)<br>{<br>    // initialize new array of points<br>    Vector3[] collapsedPoints = new Vector3[points.Length];<br><br>    // loop through each vertex in the template mesh<br>    for (int i = 0; i &lt; points.Length; i++)<br>    {<br>        // set the z-coord to zero for each point (remove the depth)<br>        collapsedPoints[i] = Vector3.Scale(points[i], new Vector3(1, 1, 0));<br>    }<br>    return collapsedPoints;<br>}</pre><h4>Copy the Template Mesh to Fill a Spline Segment</h4><p>Finally, we need to implement the AppendMeshSegment() Method, which implements the bulk of our extrusion logic. While it might look complicated, the overall goal of this method is simple: <strong>append new vertices, normals, triangles, and uvs to the existing arrays, which represent a new copy of the template mesh, such that the copy fills a single segment between two points on the spline.</strong></p><p>Most importantly, the Method takes arguments firstPos , firstTangent secondPos , secondTangent (all Vector3) which represent the position and orientation of the two points on the spline we will fill.</p><pre>private void AppendMeshSegment(List&lt;Vector3&gt; vertices, List&lt;int&gt; triangles, List&lt;Vector3&gt; normals, List&lt;Vector2&gt; uvs,<br>        Vector3 firstPos, Vector3 firstTangent, <br>        Vector3 secondPos, Vector3 secondTangent, <br>        int[] firstEdgeIndicies, int[] secondEdgeIndicies)<br>    {<br>        // initialize arrays to hold the new verticies and normals for the segment<br>        Vector3[] newVertices = new Vector3[templateVertices.Length];<br>        Vector3[] newNormals = new Vector3[extrusionTemplateMesh.normals.Length];<br><br>        // get the rotation of the first position in world space<br>        // note that we are only considering rotation around the world up<br>        Quaternion rotation = Quaternion.LookRotation(<br>            new Vector3(firstTangent.x, 0, firstTangent.z), Vector3.up);<br><br>        // set the vertices and normals for the first edge<br>        foreach (int index in firstEdgeIndicies)<br>        {<br>            // transform vertices and normals to match firstPos<br>            newVertices[index] = (rotation * templateVertices[index]) + firstPos;<br>            newNormals[index] = normalRotation * extrusionTemplateMesh.normals[index];<br>        }<br>        <br>        // get the rotation of the second position in world space<br>        rotation = Quaternion.LookRotation(<br>            new Vector3(secondTangent.x, 0, secondTangent.z), Vector3.up);<br><br>        // set the vertices and normals for the second edge<br>        foreach (int index in secondEdgeIndicies)<br>        {<br>            // transform verticies and normals to match secondPos<br>            newVertices[index] = (rotation * templateVertices[index]) + secondPos;<br>            newNormals[index] = normalRotation * extrusionTemplateMesh.normals[index];<br>        }<br><br>        int prevVerticiesLength = vertices.Count;<br><br>        // append the newly generated vertices and normals to the existing lists<br>        vertices.AddRange(newVertices);<br>        normals.AddRange(newNormals);<br>        <br>        // append new triangle data, offseting the <br>        // index by the size of the vertex list, so that<br>        // the new indicies point to the new verticies<br>        triangles.AddRange(extrusionTemplateMesh.triangles<br>            .Select(index =&gt; index + prevVerticiesLength));<br>        // copy uvs from template mesh<br>        uvs.AddRange(extrusionTemplateMesh.uv);<br>    }</pre><p>As you can see, we set the position and rotation of the first edge to the first spline position, and the second edge to the second spline position. Also notice the simplicity of adding new triangles data. Since we’re just copying the template mesh, we can use the exact same triangles (offset to point to the new vertices, of course).</p><h3>Other Considerations</h3><p>The script shown here will work in a limited capacity, but it can be improved. Some things that can easily be added are:</p><ul><li>Use the local up at sampled spline positions to ‘twist’ the mesh</li><li>Give the option to enable flat shading (current implementation creates a smooth-shaded mesh)</li><li>Allow users to supply template meshes that are extruded along the Y or X axis (currently only allows extrusion along the Z axis).</li></ul><p>These changes have been implemented in the script I’ve made available on my GitHub <a href="https://github.com/LukasKuppers/unity-spline-extrusion/tree/main">here</a>.</p><blockquote>Note: The script on my GitHub has not been extensively tested, and probably has bugs.</blockquote><p>There are some other limitations that have NOT been addressed in my complete script:</p><ul><li>UVs are currently copied directly from template. This is fine if your template mesh uses solid colors (like mine). However, if you want to apply textures to your extruded mesh, you’ll probably need to update how UVs are set.</li><li>There’s currently no way to adjust the scale of the template mesh segments. This might be a desired feature. Fortunately, this would be quite easy to implement.</li></ul><h3>Conclusion</h3><p>I hope you found this guide useful! While the script I provided isn’t super powerful, it should be able to handle regular use cases — I found many people online wondering how to do this, so this is their answer!</p><p>Since creating roads is a very common use case of splines, I’ll also link a really useful YouTube video which shows how to create roads and intersections using Splines.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZiHH_BvjoGk%3Fstart%3D735%26feature%3Doembed%26start%3D735&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZiHH_BvjoGk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZiHH_BvjoGk%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/21e7f235537194d183181b9d745d3641/href">https://medium.com/media/21e7f235537194d183181b9d745d3641/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833a97440c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Async Events in C# and Unity using Promises]]></title>
            <link>https://medium.com/@lkuppers11/how-to-handle-async-events-in-c-and-unity-using-promises-1529011c9fe4?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/1529011c9fe4</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 21:14:54 GMT</pubDate>
            <atom:updated>2023-12-13T16:19:54.220Z</atom:updated>
            <content:encoded><![CDATA[<h4>A basic Promise implementation in C# can help avoid callback hell and maintain async code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*wXbJELmv2pevTD9GAgclxA.jpeg" /><figcaption>Credit: Unity</figcaption></figure><p>If you develop games using Unity (or even if you’re just a C# developer), you’ve probably encountered asynchronous code at some point:</p><p>You invoke a process, and want to take some action once it’s complete.</p><p>For example, I’ve recently been building a prototype for a game, and needed to create procedural animations by executing a sequence of smaller asynchronous animations.</p><h4>In this Article:</h4><ul><li><a href="#e994">The Simple Solution: Callbacks</a></li><li><a href="#1cbd">The Issue with Callbacks</a></li><li><a href="#5bd4">What are Promises?</a></li><li><a href="#f70e">Building a Simple C# Promise Implementation</a></li><li><a href="#d098">The Complete C# Promise Implementation</a></li><li><a href="#c949">Real Example in Unity</a></li></ul><h3>The Simple Solution: Callbacks</h3><p>The simplest solution to executing some code after an async operation has completed is using callback functions — Pass a function to the async operation, and have the async operation call the function once its done.</p><p>See this example for illustration:</p><pre>using System;<br><br>// our main function that calls the async function<br>public void Main()<br>{<br>  AsyncOperation(() =&gt; {<br>    // this gets called once the async operation is complete<br>    Debug.Log(&quot;async operation complete&quot;);<br>  });<br>}<br><br>public void AsyncOperation(Action callback)<br>{<br>  // execute async operation (takes some unknown amount of time)...<br><br>  // async op is done, call the callback function<br>  callback.Invoke();<br>}<br></pre><h4>The Issue with Callbacks</h4><p>While this works for simple situations, it can easily get out of control and hard to manage. For instance, it’s common to want to execute async operations in a sequence, one after the other. Here’s what this looks like if we use callbacks:</p><pre>using System;<br><br>// our main function that calls the async function<br>public void Main()<br>{<br>  // call the first async function<br>  AsyncOperation(() =&gt; {<br>    // call the second async function<br>    AsyncOperation(() =&gt; {<br>      // call the third async function<br>      AsyncOperation(() =&gt; {<br>        // continue ...<br>      });<br>    });<br>  });<br>}<br><br>public void AsyncOperation(Action callback)<br>{<br>  // execute async operation (takes some unknown amount of time)...<br><br>  // async op is done, call the callback function<br>  callback.Invoke();<br>}</pre><p>Clearly this isn’t great, and it gets worse the longer our sequence is. Also, handling failed async operations is messy.</p><h3>The Better Solution: Promises</h3><p>While there’s a number of ways to get around callback issues, the solution I’ve opted for is Promises. If you’ve written JS code, you’re probably familiar with them (as Promises are built in to JS), but if not, here’s a brief overview:</p><h4>What are Promises?</h4><p>A Promise is an object representing the eventual completion or failure of an async operation. If a function returns a Promise, it doesn’t immediately return a value, but the Promise will once the async operation is complete.</p><p>It can be easier to understand looking at an example:</p><pre>public void Main()<br>{<br>  // DownloadData is the async operation, and it returns a Promise<br>  DownloadData(&quot;&lt;some https url&gt;&quot;)<br>    .Then((data) =&gt; {<br>      // This function gets called if DownloadData is successful<br>      // the &#39;data&#39; argument is the result of the download<br>    })<br>    .Catch(() =&gt; {<br>      // This function gets called if DownloadData fails<br>      // In that case, the above .Then will not be called<br>    });<br>}</pre><p>As you can see above, the Promise object exposes functions like .Then() or .Catch(). The function passed to .Then() is called once the Promise ‘resolves’ (the async operation completes successfully), and it takes the result of the async operation as a parameter. The function passed to .Catch() is called if any errors occur during the async operation.</p><p>Also, the .Then() and .Catch() methods return promises, so promises can be chained (allowing us to execute sequences of async events!).</p><p>For a much better description of Promises, see the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN Docs</a>.</p><h4>Building A simple C# Promise Implementation</h4><p><strong>Class Setup</strong></p><p>First, we need to set up the Promise class and its properties. Notice that the class is generic — the generic type PromisedTis the type that the async operation will return. So a Promise&lt;int&gt; will pass an int to the function in the .Then() Method.</p><p>Here’s the class setup and constructor:</p><pre>using System;<br><br>public class Promise&lt;PromisedT&gt;<br>{<br>  private enum Status {<br>    PENDING, RESOLVED, REJECTED<br>  }<br><br>  private Status status;<br>  private PromisedT value;<br>  private Action&lt;PromisedT&gt; onResolved;<br>  private Action&lt;string&gt; onRejected;<br><br>  public Promise()<br>  {<br>    status = Status.PENDING;<br>    value = default(PromisedT);<br>  }<br>}</pre><p>As you can see, the Promise maintains it’s internal status, which is pending by default, and will become resolved on success, or rejected on failure.</p><p>The property value will store the returned value of the async operation on success.</p><p>The Actions onResolved and onRejected are internal functions that will be called when the Promise succeeds or fails.</p><p><strong>Resolve and Reject Methods</strong></p><p>Next, we need to expose two functions that will be used by the async operation to signal when the operation has succeeded, or failed:</p><pre>public class Promise&lt;PromisedT&gt;<br>{<br>  // everything added so far...<br><br>  public void Resolve(PromisedT successValue)<br>  {<br>    if (status == Status.PENDING)<br>    {<br>      status = Status.RESOLVED;<br>      value = successValue;<br>      onResolved?.Invoke(value);<br>    }<br>  }<br><br>  public void Reject(string message)<br>  {<br>    if (status == Status.PENDING)<br>    {<br>      status = Status.REJECTED;<br>      onRejected?.Invoke(message);<br>    }<br>  }<br>}</pre><p>As you can see, when Resovle() is called, the async operation provides the result of the operation. This gets stored internally within the Promise, and the onResolved function is invoked (if it has been set).</p><p>Similarly, Reject() is called by the async operation when it encounters an error — The message parameter is a string containing an error message.</p><p><strong>.Then Methods</strong></p><p>Now for the meat &amp; potatoes: the .Then() Method will take a callback as an argument (a function to call on resolution of the promise) and return a promise. We’ll implement two version of .Then() , one if the callback is non-async, and one if the callback is async (returns a Promise itself).</p><pre>public class Promise&lt;PromisedT&gt;<br>{<br>  // everything added so far...<br><br>  // callback returns value but is not async<br>  public Promise&lt;ConvertT&gt; Then&lt;ConvertT&gt;(Func&lt;PromisedT, ConvertT&gt; callback)<br>  {<br>    Promise&lt;ConvertT&gt; promise = new Promise&lt;ConvertT&gt;();<br>    Action&lt;PromisedT&gt; initPromiseResolution = (PromisedT val) =&gt;<br>    {<br>      ConvertT callbackValue = callback(val);<br>      promise.Resolve(callbackValue);<br>    };<br><br>    if (status == Status.PENDING)<br>    {<br>      onResolved = initPromiseResolution;<br>      onRejected = (string msg) =&gt; promise.Reject(msg);<br>    }<br>    else if (status == Status.RESOLVED)<br>      initPromiseResolution(value);<br>    else<br>      promise.Reject();<br><br>    return promise;<br>  }<br><br>  // callback is async - returns a promise<br>  public Promise&lt;ConvertT&gt; Then&lt;ConvertT&gt;(Func&lt;PromisedT, Promise&lt;ConvertT&gt;&gt; callback)<br>  {<br>    Promise&lt;ConvertT&gt; promise = new Promise&lt;ConvertT&gt;();<br>    Action&lt;PromisedT&gt; initPromiseResolution = (PromisedT val) =&gt;<br>    {<br>      Promise&lt;ConvertT&gt; callbackPromise = callback(val);<br>      callbackPromise<br>        .Then((ConvertT callbackVal) =&gt; promise.Resolve(callbackVal))<br>        .Catch((string msg) =&gt; promise.Reject(msg));<br>    };<br><br>    if (status == Status.PENDING)<br>    {<br>      onResolved = initPromiseResolution;<br>      onRejected = (string msg) =&gt; promise.Reject(msg);<br>    }<br>    else if (status == Status.RESOLVED)<br>      initPromiseResolution(value);<br>    else<br>      promise.Reject();<br><br>    return promise;<br>  }<br>}</pre><p>That might look complex, but the gist is simple:</p><p>For both functions, we’ll take a different action based on the Promise status. No matter what though, the function also creates a new Promise internally, that will be returned.</p><ul><li>RESOLVED: We immediately invoke the callback with the resolved value, and then we resolve the new Promise with the result of the callback. If the callback is itself async, we’ll call .Then() on the promise returned by the callback, where we resolve the new Promise once the callback is complete.</li><li>REJECTED : We simply call .Reject() on the new Promise and return it.</li><li>PENDING : We do everything we did for the RESOLVED case, but just do it once the promise is resolved (so we add that to the onResolved function). Also, we set the onRejected function to call .Reject on the new promise, in the case that the async operation fails.</li></ul><p><strong>.Catch Method</strong></p><p>Finally, we need to add the .Catch() method. The callback passed to .Catch() will be called only if the async operation fails (the Promise is rejected).</p><pre>public class Promise&lt;PromisedT&gt;<br>{<br>  // everything added so far...<br><br>  // callback takes error message as parameter<br>  public Promise&lt;PromisedT&gt; Catch(Action&lt;string&gt; callback)<br>  {<br>    Promise&lt;PromisedT&gt; promise = new Promise&lt;PromisedT&gt;();<br><br>    if (status == Status.PENDING)<br>      {<br>        onResolved = (PromisedT val) =&gt; promise.Resolve(val);<br>        onRejected = callback;<br>      } <br>      else if (status == Status.RESOLVED)<br>        promise.Resolve(value);<br>      else<br>        callback(&quot;Default promise rejection message&quot;);<br><br>    return promise;<br>  }<br>}</pre><p>This is more simple, but again we manage all status cases:</p><ul><li>RESOLVED : We simply resolve the new promise using the internal promise value.</li><li>REJECTED : We call the error handling callback passed to .Catch() .</li><li>PENDING : We set the onResolved and onRejected functions to handle the future possibilities of resolution or rejection. What we do for each case is the same as what we did for the RESOLVED and REJECTED cases.</li></ul><h4>The Complete C# Promise Implementation</h4><p>Here’s the complete Promise class, plus a few additional overloaded functions to make using Promises a bit easier. Note that this is not a <em>good </em>Promise implementation, and better options exist.</p><p>This implementation just shows how you can get started, and is good enough to handle simple use cases.</p><p>For a fully fledged Promise implementation in C#, see:</p><ul><li><a href="https://github.com/Real-Serious-Games/C-Sharp-Promise">https://github.com/Real-Serious-Games/C-Sharp-Promise</a></li></ul><pre>using System;<br><br>public class Promise&lt;PromisedT&gt;<br>{<br>    private enum Status<br>    {<br>        PENDING, RESOLVED, REJECTED<br>    }<br><br>    private Status status;<br>    private PromisedT value;<br>    private Action&lt;PromisedT&gt; onResolved;<br>    private Action&lt;string&gt; onRejected;<br><br>    public Promise()<br>    {<br>        status = Status.PENDING;<br>        value = default(PromisedT);<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Successfully settle the promise<br>    /// &lt;/summary&gt;<br>    /// &lt;param name=&quot;successValue&quot;&gt;The return value of the promise&lt;/param&gt;<br>    public void Resolve(PromisedT successValue)<br>    {<br>        if (status == Status.PENDING)<br>        {<br>            status = Status.RESOLVED;<br>            value = successValue;<br>            onResolved?.Invoke(value);<br>        } <br><br>    }<br><br>    /// &lt;summary&gt;<br>    /// Settle the promise to rejection state<br>    /// &lt;/summary&gt;<br>    public void Reject()<br>    {<br>        Reject(&quot;Default promise rejection message&quot;);<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Settle the promise, reporting an error<br>    /// &lt;/summary&gt;<br>    /// &lt;param name=&quot;message&quot;&gt;The error message&lt;/param&gt;<br>    public void Reject(string message)<br>    {<br>        if (status == Status.PENDING)<br>        {<br>            status = Status.REJECTED;<br>            onRejected?.Invoke(message);<br>        }<br>    }<br><br>    // callback doesn&#39;t take any args<br>    public Promise&lt;PromisedT&gt; Catch(Action callback)<br>    {<br>        return Catch((msg) =&gt; callback());<br>    }<br><br>    // callback takes error message as parameter<br>    public Promise&lt;PromisedT&gt; Catch(Action&lt;string&gt; callback)<br>    {<br>        Promise&lt;PromisedT&gt; promise = new Promise&lt;PromisedT&gt;();<br><br>        if (status == Status.PENDING)<br>        {<br>            onResolved = (PromisedT val) =&gt; promise.Resolve(val);<br>            onRejected = callback;<br>        } <br>        else if (status == Status.RESOLVED)<br>            promise.Resolve(value);<br>        else<br>            callback(&quot;Default promise rejection message&quot;);<br><br>        return promise;<br>    }<br><br>    // callback doesn&#39;t take any args or return anything<br>    public Promise&lt;bool&gt; Then(Action callback)<br>    {<br>        return Then((PromisedT val) =&gt;<br>        {<br>            callback();<br>            return true;<br>        });<br>    }<br><br>    // callback doesn&#39;t return anything<br>    public Promise&lt;bool&gt; Then(Action&lt;PromisedT&gt; callback)<br>    {<br>        return Then((PromisedT val) =&gt;<br>        {<br>            callback(val);<br>            return true;<br>        });<br>    }<br><br>    // callback returns value but is not async<br>    public Promise&lt;ConvertT&gt; Then&lt;ConvertT&gt;(Func&lt;PromisedT, ConvertT&gt; callback)<br>    {<br>        Promise&lt;ConvertT&gt; promise = new Promise&lt;ConvertT&gt;();<br>        Action&lt;PromisedT&gt; initPromiseResolution = (PromisedT val) =&gt;<br>        {<br>            ConvertT callbackValue = callback(val);<br>            promise.Resolve(callbackValue);<br>        };<br><br>        if (status == Status.PENDING)<br>        {<br>            onResolved = initPromiseResolution;<br>            onRejected = (string msg) =&gt; promise.Reject(msg);<br>        }<br>        else if (status == Status.RESOLVED)<br>            initPromiseResolution(value);<br>        else<br>            promise.Reject();<br><br>        return promise;<br>    }<br><br>    // callback is async - returns a promise<br>    public Promise&lt;ConvertT&gt; Then&lt;ConvertT&gt;(Func&lt;PromisedT, Promise&lt;ConvertT&gt;&gt; callback)<br>    {<br>        Promise&lt;ConvertT&gt; promise = new Promise&lt;ConvertT&gt;();<br>        Action&lt;PromisedT&gt; initPromiseResolution = (PromisedT val) =&gt;<br>        {<br>            Promise&lt;ConvertT&gt; callbackPromise = callback(val);<br>            callbackPromise.Then((ConvertT callbackVal) =&gt; promise.Resolve(callbackVal));<br>        };<br><br>        if (status == Status.PENDING)<br>        {<br>            onResolved = initPromiseResolution;<br>            onRejected = (string msg) =&gt; promise.Reject(msg);<br>        }<br>        else if (status == Status.RESOLVED)<br>            initPromiseResolution(value);<br>        else<br>            promise.Reject();<br><br>        return promise;<br>    }<br>}</pre><h3>Real Example in Unity</h3><p>Ok, so we have Promises, but how can we use them in Unity?</p><p>Here’s a typical example:</p><p>We have a procedural animation controller calledAnimControllerfor some character, exposing various methods, say:</p><ul><li>MoveHand(Vector3 position) — Move the characters hand to position</li><li>CloseHand() — Close the characters hand</li><li>OpenHand() — Open the characters hand</li></ul><p>These methods use Coroutines to animate, and return Promises, like this:</p><pre>public class AnimController: MonoBehaviour<br>{<br>  // other class code...<br><br>  public Promise&lt;bool&gt; MoveHand(Vector3 position)<br>  {<br>    Promise&lt;bool&gt; promise = new Promise&lt;bool&gt;();<br>    StartCoroutine(LerpHandToPos(position, promise));<br>    return promise;<br>  }<br><br>  private IEnumerator LerpHandToPos(Vector3 pos, Promise&lt;bool&gt; promise)<br>  {<br>    while (hand.transform.position != pos)<br>    {<br>      // animate hand position<br>      yield return null<br>    }<br>    promise.Resolve(true);<br>  }<br>}</pre><p>Then in some other class, we want to run these animations in sequence to carry out operations (pick up object, put down object, …):</p><p>With Promises, that could look like this:</p><pre>public void PickupObject(GameObject obj)<br>{<br>  AnimController ac = gameObject.GetComponent&lt;AnimController&gt;();<br><br>  Vector3 originalPos = hand.transform.position;<br><br>  ac.OpenHand()<br>    .Then((_) =&gt; MoveHand(obj.transform.position))<br>    .Then((_) =&gt; CloseHand())<br>    .Then(() =&gt; MoveHand(originalPos))<br>    .Catch((err) =&gt; Console.Log($&quot;Animation encountered error: {err}&quot;));<br>}<br></pre><p>Clearly, this is much cleaner than if we used callbacks to create this animation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1529011c9fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extract Authors and Title from a Reference List using JS]]></title>
            <link>https://medium.com/@lkuppers11/how-to-extract-authors-and-title-from-a-reference-list-using-js-5df291da1f2c?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df291da1f2c</guid>
            <category><![CDATA[reference-format]]></category>
            <category><![CDATA[academic-research]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[parsing]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 19:35:57 GMT</pubDate>
            <atom:updated>2023-10-17T19:35:57.190Z</atom:updated>
            <content:encoded><![CDATA[<h4>The provided function extracts authors and titles from all reference list formats</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*xG4STCO01KHHDhNtLogyOA.png" /></figure><h3>TLDR:</h3><p><a href="#0a4f">JavaScript function to extract authors and title from reference</a></p><h4>Background</h4><p>The blog site I’m building (<a href="https://sapienthink.com/">Sapien Think</a>) includes Amazon Affiliate links to works referenced in articles. At first, I tried to link to the entire reference text, but this yielded very poor search results within Amazon.</p><blockquote>ex: Kant, I. (2012). Groundwork of the Metaphysics of Morals. Cambridge University Press. doesn’t search nearly as well as Kant, I, Groundwork of the Metaphysics of Morals .</blockquote><p>To solve this, I needed to extract important information like author(s) and title from references. This would be easy if a single format was used for reference lists in my site, but that’s not the case. For example, here are some varying references:</p><ul><li>Kant, I. (2012). <em>Groundwork of the Metaphysics of Morals</em>. Cambridge University Press.</li><li>Descartes, R. <em>Meditations on First Philosophy.</em></li><li>Russell, Bertrand. “The History of Western Philosophy.” Routledge, 2004.</li><li>Russo, N. F., &amp; Epistemology, F. in. (1989). <em>Developing Philosophical Thinking Skills in Learning Experiences</em>. Theory Into Practice, 28(2), 102–105. doi:10.1080/00405848909543340</li></ul><p>How can we efficiently deal with all those varying reference types?!</p><h4>1. Separate into Sections</h4><p>First, notice the nice fact that the various parts of all the references are separated by . (a period followed by a space).</p><p>So the first thing we can do is separate the original string on this pattern:</p><pre>const extractAuthorsAndTitle = (reference) =&gt; {<br>  reference = reference.split(&#39;. &#39;);<br>};</pre><p>Now, we’ve converted our reference into an array of strings, each being an important section (author, title, date, publisher, …).</p><h4>2. Handle Bad Author Sections</h4><p>The above trick works nicely if author initials aren’t listed. However, once we encounter something like: Russo, N. F. we have issues. Our split operation will split on the initials, so the first part of our array will look like: [&#39;Russo, N&#39;, &#39;F&#39;, ...] — not desireable.</p><p>To prevent this, we can use regex to collapse a sequence of initials:</p><p>A. B. C. collapses to become A. .</p><p>Here’s the code that can do that:</p><pre>const regex = /([A-Z])\.(\s[A-Z]\.)+/g;<br>reference = reference.replace(regex, &#39;$1.&#39;);</pre><p>After applying this code, an author like Russo, N. F. becomes Russo, N. .</p><h4>3. Remove Quotation Characters</h4><p>Before we split on . , we also want to remove any &quot; characters. There are two reasons for this:</p><ol><li>Quotation marks are irrelevant to article titles</li><li>They can mess up our string splitting: hello.&quot; won’t split but hello. will.</li></ol><p>This one is pretty simple:</p><pre>reference = reference.replace(/&quot;/g, &#39;&#39;);</pre><h4>4. Remove Irrelevant Reference Data</h4><p>After all the above steps, after we’ve split the reference on . , we’re almost done. Now we just need to remove unnecessary data. This includes stuff like the following:</p><ul><li>(2006) in Paul, R., &amp; Elder, L. (2006). <em>Critical Thinking: The Nature of Critical and Creative Thought</em>. Journal of Developmental Education, 30(2), 34–35.</li><li>(Eds.) in Fieser, J., &amp; Dowden, B. (Eds.). (2020). <em>The Internet Encyclopedia of Philosophy</em>.</li><li>in. in Russo, N. F., &amp; Epistemology, F. in. (1989). <em>Developing Philosophical Thinking Skills in Learning Experiences</em>. Theory Into Practice, 28(2), 102–105.</li></ul><p>We can do this with some filtering steps after the split, like this:</p><pre>const sections = reference.split(&#39;. &#39;);<br>const filteredSections = sections<br>  .filter(str =&gt; str[0] !== &#39;(&#39;)<br>  .filter(str =&gt; str !== &#39;in&#39;);</pre><h4>5. Putting it All Together</h4><p>Finally, once we have our filtered sections, it turns out that (at least for most reference formats), the author(s) will be contained in the first array element, and the title of the work will be in the second.</p><p>Our final function looks like this:</p><pre>const extractAuthorsAndTitle = (reference) =&gt; {<br>  // process author lists with middle name initials<br>  // collapses patterns like &#39;G. W. F.&#39; to &#39;G.&#39;<br>  const regex = /([A-Z])\.(\s[A-Z]\.)+/g;<br>  reference = reference.replace(regex, &#39;$1.&#39;);<br><br>  // remove all &quot; characters<br>  reference = reference.replace(/&quot;/g, &#39;&#39;);<br><br>  // split and filter<br>  const sections = reference.split(&#39;. &#39;);<br>  const filteredSections = sections<br>    .filter(str =&gt; str[0] !== &#39;(&#39;)<br>    .filter(str =&gt; str !== &#39;in&#39;);<br><br>  return [filteredSections[0], filteredSections[1]];<br>};</pre><p>That should be able to handle most reference list formats, and it can easily be modified to handle even more edge cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df291da1f2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Clean SVG Graphics For your Website]]></title>
            <link>https://medium.com/@lkuppers11/how-to-create-clean-svg-graphics-for-your-website-dd2bb7844296?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd2bb7844296</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 02:17:52 GMT</pubDate>
            <atom:updated>2023-10-11T02:17:52.059Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quickly and Easily Create Custom SVGs for Free</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sa59HEl96W6CShVQeWpw9g.jpeg" /><figcaption>Created using the following techniques</figcaption></figure><p>I was recently building out a blog website from scratch (<a href="https://sapienthink.com/">sapienthink.com</a>), and needed some custom graphics to improve the site appearance and credibility. I didn’t just want to grab stock images off the internet, and I also wanted SVG’s, so that the graphics would scale nicely.</p><p>I found a super easy way to create nice looking custom SVGs, in extremely little time, and for free. I though I would share:</p><h3>1. Find a Base Image</h3><p>First, you’ll want to get an image that your SVG will be based on. This can be any image of your choosing — the format can any standard image format, such as jpg or png. For this example, I’ll use this png:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*bdDhXzKy39kFewzeJwNvpA.png" /></figure><h3>2. Convert The Image to Grayscale</h3><p>Next, you’ll want to make the image black and white. You can easily do this using photo editing software on your computer, or use an online tool like: <a href="https://blackandwhite.imageonline.co/">https://blackandwhite.imageonline.co/</a>. I used the default Windows photo editor to get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*xaA7fcqcRe9_g9ZXi9iyqQ.png" /></figure><h3>3. Convert to SVG</h3><p>Finally, use an online tool to convert the black and white image to SVG format. While there are many tools available, I’ve found <a href="https://convertio.co/png-svg/">https://convertio.co/png-svg/</a> does a very good job. After converting my black and white image to SVG, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3QyJ6fBtS075nOIHHBdug.png" /></figure><h3>4. Modify the Color</h3><p>While that already looks pretty cool, one last thing you can (and probably should) do is change the color to fit your color scheme.</p><p>One way to do this is simply edit the fill color in the SVG.</p><p>Just open the SVG with a text editor (such as Notepad), and change the fill attribute from #000000 to some valid Hex color. For example, I used #256E85 . See the modified fill attribute highlighted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*wRQ9Dq_KH0MftxH4VZg4rQ.png" /></figure><p>After changing the color, the SVG looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcFgymtf_nMR8ZGgDx8MqA.png" /></figure><h3>Considerations</h3><p>If you used a high quality image, you might notice that the SVG file is quite large (which isn’t exactly optimal for use in a webpage). You can rescale the original image using an online tool to shrink the SVG size.</p><p>Also, You might not want your SVG to have so much detail. Again, in this case, just rescale the original image, so that the SVG will present fewer details, and have a smoother appearance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2bb7844296" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I don’t Grind LeetCode for Interview Prep]]></title>
            <link>https://medium.com/@lkuppers11/why-i-dont-grind-leetcode-for-interview-prep-7a8128a4025f?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a8128a4025f</guid>
            <category><![CDATA[job-interview-tips]]></category>
            <category><![CDATA[programing]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[job-interview-preparation]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 01:59:54 GMT</pubDate>
            <atom:updated>2023-10-17T18:47:41.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I don’t use LeetCode for Interview Prep</h3><h4>No. I’m not crazy, I just value my time.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BWfMcH9oGDy8aWP4" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>LeetCode gets about <a href="https://www.similarweb.com/website/leetcode.com/#overview">20 million visitors per month</a> — I’m not one of them. That’s right. I don’t grind Leetcode questions before technical interviews. For that matter, I’ve never read <em>Cracking the Coding Interview</em> either! Let me tell you why.</p><h4><strong>Covered in this article:</strong></h4><ul><li><a href="#656b">Why I don’t use Leetcode</a></li><li><a href="#047e">My interview success without LeetCode</a></li><li><a href="#b01e">Why you still might want to use LeetCode</a></li></ul><p><strong>TLDR:</strong> <a href="#a08d">Conclusion</a></p><h3>Why I don’t use LeetCode</h3><p>Plenty of the conversations about LeetCode that I’ve had with my classmates and colleagues have gone the same way. I confess that I don’t grind coding questions in preparation for technical interviews; and I watch as genuine confusion washes across the faces of those around me. Usually people think one of two things: That I’m crazy (stupid), and am ruining my chances of having successful coding interviews, or that I’m crazy (smart) and somehow am gifted enough to know every coding problem off the top of my head. I’m definitely not a genius but probably not stupid either.</p><p>Here’s the thing: <strong>I don’t believe that flawless performance on technical interviews increases your chances of getting an offer</strong>. Unfortunately, I couldn’t find any official stats on how using LeetCode impacts interview success rates, so we’re stuck with my anecdotal evidence.</p><p>Consider why technical interviews exist — to gauge the problem solving and communication abilities of the applicant. Arguably, LeetCode can help with problem solving skills, but it cannot help with communication skills. Interviewers can tell if you have a solution memorized; if you immediately present an optimal solution after getting a problem, it isn’t very impressive. In a lot of cases, grinding LeetCode demonstrates memorization abilities over true problem solving ability, and this is going to be obvious to the interviewer.</p><p>When I take coding interviews, I don’t have the problem memorized, so I need to work through it the best I can, live. Seeing fresh problems gives me the chance to ask insightful questions, and explain my reasoning as I try to come to a solution. The interviewer gets to see how I handle novel problems, which is the skill they really want to see on display. Even if I get stumped, I can demonstrate my process of analyzing and working through a problem.</p><h3>My interview success without LeetCode</h3><p>Ok, so that all sounds good in theory, but how has it worked out? I confess, I’m not an industry vet. I’ve just graduated university, and have three interviews under my belt (Albeit at competitive companies like SAP and Amazon). With that being said, I’ve never failed a coding interview.</p><p>But that doesn’t mean I always come up with perfect solutions. I’ve been stumped many times, and needed hints from the interviewer. But that’s just the thing — interviewers don’t care if you know the perfect solution. I’ve always vocally worked through problems, explaining my reasoning, and asking questions along the way. As far as I can tell, this has been the source of my success in technical interviews. Actually working to solve the problem is better than knowing the answer beforehand, even if you don’t get the best solution.</p><h3>Why you still might want to use LeetCode</h3><p>I don’t grind leetCode for interview prep, but that doesn’t mean I don’t have any skills at all with algorithm-style questions. I’ve graduated university with a computer science degree. I’ve taken difficult data structures and algorithms courses — I know the fundamentals. If you’re a university CS grad and have already studied CS fundamentals, I don’t think LeetCode will help you that much.</p><p>However, if you don’t know data structure/algorithm fundamentals, then Leetcode could still provide some serious value. I would recommend studying with LeetCode if you don’t know basic data structures and associated algorithms (and their time/space complexities), or if you’re not familiar with different algorithm methods, like greedy algorithms, linear programming, etc.</p><h3>Conclusion</h3><p>In summary, if you already have CS fundamentals nailed down, I don’t think grinding Leetcode is worth the time investment. Just imagine what other sort of projects you could sink your time into instead of Leetcode. <strong>Even if grinding LeetCode gives some competitive edge, I don’t think it’s enough to justify the time commitment</strong>.</p><p>With that being said, those with less fundamental CS knowlege could still greatly benefit from studying Leetcode, as it can introduce you to fundamental concepts in an interactive way.</p><p>Just remember — technical interviews are your chance to demonstrate your real-time problem solving and communication skills, and memorizing solutions takes that chance away.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a8128a4025f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Processing Payments in Firebase with Stripe]]></title>
            <link>https://medium.com/firebase-developers/processing-payments-in-firebase-with-stripe-e90c816f02d0?source=rss-2808fede0568------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90c816f02d0</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[firebase-extensions]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Lukas Kuppers]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 22:59:58 GMT</pubDate>
            <atom:updated>2025-04-03T03:02:53.076Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple guide to using the Run payments with Stripe extension in a Firebase project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UF8vyvpPEYkBrhfO2NuC5w.jpeg" /></figure><p>In this article I will show how to quickly process payments in a Firebase project using Stripe and the <a href="https://extensions.dev/extensions/invertase/firestore-stripe-payments">firestore-stripe-payments </a>extension. The extension docs encourage users to install the <a href="https://github.com/invertase/stripe-firebase-extensions/blob/next/firestore-stripe-web-sdk/README.md">JS package</a>, but I took a different approach which I will go through in the guide below.</p><p><strong>Covered in this guide:</strong></p><ul><li><a href="#6b8b">Install and configure the extension</a></li><li><a href="#4aac">Get Stripe products in your Web app</a></li><li><a href="#99ba">Redirect users to a Stripe checkout session</a></li><li><a href="#e8ee">Get active subscriptions for the current user</a></li><li><a href="#649f">Redirect users to a Stripe customer portal session</a></li><li><a href="#a8cb">Handle payment events on the backend</a></li></ul><p><strong>Not covered in this guide:</strong></p><ul><li>Making mobile payments</li><li>Setting up authentication for a Firebase app</li><li>Handling trials</li><li>Other payment aspects (taxes, custom metadata, multiple prices)</li></ul><h4>Background</h4><p>If you’re serious about monetizing your Firebase app, you’ve probably looked into getting some sort of payment system set up. The <a href="https://extensions.dev/extensions/invertase/firestore-stripe-payments">Run Payments with Stripe</a> extension is a great solution.</p><blockquote>Note: Ownership of the Stripe extension has been transferred to Invertase. That means that you need to use the Invertase version of the Run Payments with Stripe extension, as the Stripe version will no longer receive maintenance updates!</blockquote><p>When setting up the Stripe payments extension personally, I found it difficult to navigate the documentation. Hopefully I can help you avoid this pain by walking you through the basic process of how to get Stripe payments working in a Firebase app. In addition, you might find <a href="https://github.com/stripe-samples/firebase-subscription-payments">this example</a> project useful for getting Stripe working. Also, you can view the live version of the app I was building with Firebase and Stripe <a href="https://webtocsv.com/">here</a> —it might come in handy.</p><h4>1. Install and configure the extension</h4><p>I’m going to assume you already have a Firebase project, and know the basics of Firebase.</p><ol><li>Setup a <a href="https://stripe.com/">Stripe</a> account — you can create a new account there and turn on test mode.</li><li>Install the <a href="https://extensions.dev/extensions/invertase/firestore-stripe-payments">firestore-stripe-payments</a> extension in your project. (Note: you need to upgrade to the Blaze plan in Firebase)</li><li>Configure the extension — Everything here is pretty self-explanatory, just follow the instructions. You can always change the config later. Also, when just getting started out, you can keep events disabled.</li></ol><blockquote>Note: If your restricted API key and webhook were obtained in Stripe test mode, you’ll need to update these values when you go live in Stripe.</blockquote><p>In general, configuring the extension is quite easy, but I’ll highlight three critical steps:</p><ol><li>Copy the provided Cloud Firestore security rules into your projects security rules (Firestore Database -&gt; Rules):</li></ol><pre>match /databases/{database}/documents {<br>    match /stripe-customers/{uid} {<br>      allow read: if request.auth.uid == uid;<br><br>      match /checkout_sessions/{id} {<br>        allow read, write: if request.auth.uid == uid;<br>      }<br>      match /subscriptions/{id} {<br>        allow read: if request.auth.uid == uid;<br>      }<br>      match /payments/{id} {<br>        allow read: if request.auth.uid == uid;<br>      }<br>    }<br><br>    match /stripe-products/{id} {<br>      allow read: if true;<br><br>      match /prices/{id} {<br>        allow read: if true;<br>      }<br><br>      match /tax_rates/{id} {<br>        allow read: if true;<br>      }<br>    }<br>  }</pre><p>2. Configure the Stripe webhook as outlined in the provided docs. Nothing will work if this isn’t setup properly. And again, you’ll need to re-enter the Stripe webhook secret when switching Stripe from test to live mode.</p><p>3. Make sure Firebase Authentication is enabled for your project. Users should need to sign in before they can make payments.</p><h4>2. Get Stripe products in your Web app</h4><p>You’re going to need to fetch product info in your frontend app, even if you won’t be displaying product info from Stripe, because you need the Stripe price ID to initiate payment sessions.</p><p>Here’s how you can get all the active products (and their prices) you created in Stripe. Note that db is the Firestore object obtained using getFirestore():</p><pre>import { query, collection, where, getDocs } from &#39;firebase/firestore&#39;;<br><br>// create a query object<br>const q = query(<br>  collection(db, &#39;products&#39;), <br>  where(&#39;active&#39;, &#39;==&#39;, true)<br>);<br><br>const querySnapshot = await getDocs(q);<br><br>// for each product, get the product price info<br>const productsPromises = querySnapshot.docs.map(async (productDoc) =&gt; {<br>  let productInfo = productDoc.data();<br><br>  // fetch prices subcollection per product<br>  const pricesCollection = collection(productDoc.ref, &#39;prices&#39;);<br>  const priceQuerySnapshot = await getDocs(pricesCollection);<br><br>  // assume there is only one price per product<br>  const priceDoc = priceQuerySnapshot.docs[0];<br>  productInfo[&#39;priceId&#39;] = priceDoc.id;<br>  productInfo[&#39;priceInfo&#39;] = priceDoc.data();<br>  return productInfo;<br>});<br><br>// &#39;products&#39; is an array of products (including price info)<br>const products = await Promise.all(productsPromises);</pre><h4>3. Redirect users to a Stripe checkout session</h4><p>Once you’ve fetched product info, you can redirect users to a stripe payment page: You will NOT be using payment links from the Stripe dashboard! You would probably put this code in a function that gets triggered on a button click, or something like that.</p><p>Observe that the code is creating a new checkout session in Firestore. Then, the Stripe extension detects this and creates a payment link for us, where we can redirect the user.</p><blockquote>Note: You can customize the look of Stripe pages <a href="https://dashboard.stripe.com/settings/branding">here</a></blockquote><pre>import { addDoc, collection, onSnapshot } from &#39;firebase/firestore&#39;;<br><br>let checkoutSessionData = {<br>    price: &#39;price_1GqIC8HYgolSBA35zoTTN2Zl&#39;, // price ID from products fetch<br>    success_url: window.location.origin, // can set this to a custom page<br>    cancel_url: window.location.origin   // can set this to a custom page<br>};<br><br>// if payment is a one-time payment (as opposed to subscription)<br>// append mode: &#39;payment&#39; to the checkout session data<br>if (isOneTime) {<br>    checkoutSessionData[&#39;mode&#39;] = &#39;payment&#39;;<br>}<br><br>const checkoutSessionRef = await addDoc(<br>  // currentUser is provided by firebase, via getAuth().currentUser<br>  collection(db, `customers/${currentUser.uid}/checkout_sessions`), <br>  checkoutSessionData<br>);<br><br>// The Stripe extension creates a payment link for us<br>onSnapshot(checkoutSessionRef, (snap) =&gt; {<br>  const { error, url } = snap.data();<br>  if (error) {<br>    // handle error<br>  }<br>  if (url) {<br>    window.location.assign(url);  // redirect to payment link<br>  }<br>});</pre><h4>4. Get active subscriptions for the current user</h4><p>In the frontend, you might want to modify the content you display to the user based on their subscription / whether or not they’re subscribed at all. You can quickly get subscriptions like this:</p><pre>import { query, collection, where, getDocs } from &#39;firebase/firestore&#39;;<br><br>// create a query object to the current users active subscriptions<br>const q = query(<br>  // currentUser is provided by firebase, via getAuth().currentUser<br>  collection(db, &#39;customers&#39;, currentUser.uid, &#39;subscriptions&#39;), <br>  where(&#39;status&#39;, &#39;in&#39;, [&#39;trialing&#39;, &#39;active&#39;])<br>);<br><br>// fetch the active subscriptions<br>const querySnapshot = await getDocs(q);<br>if (querySnapshot.empty) {<br>  // user doesn&#39;t have any active subscriptions<br>}<br>// assuming user only has one active subscription max<br>const subscription = querySnapshot.docs[0].data();</pre><h4>5. Redirect users to a Stripe customer portal session</h4><p>If you have subscriptions in your app, you’ll want subscribed users to be able to manage their subscription (change payment info, cancel, etc). You can redirect users to a Stripe customer portal session like this:</p><pre>import { getFunctions, httpsCallable } from &#39;firebase/functions&#39;;<br><br>// firebaseApp is object created using initializeApp()<br>// may need to change server location<br>const functions = getFunctions(firebaseApp, &#39;us-central1&#39;);<br>const createPortalLink = httpsCallable(<br>  functions, <br>  &#39;ext-firestore-stripe-payments-createPortalLink&#39;);<br><br>// request Stripe to create a portal link, and redirect user there<br>createPortalLink({<br>    returnUrl: window.location.origin // can set this to a custom page<br>}).then((result) =&gt; {<br>    window.location.assign(result.data.url);<br>}).catch((error) =&gt; {<br>    // handle error<br>});</pre><h4>6. Handle payment events on the backend</h4><p>You might want to have some custom function triggered when a successful payment goes through. For example, in my app (a public REST API), I wanted to give the user API tokens when they made a payment. To do this, you’ll need Cloud Functions set up for your project.</p><p>The Stripe Firebase extension publishes event arc events that get triggered during different phases of the payment lifecycle. To enable these events, you need to check enable events in the Stripe extension config, and select the exact events you want enabled in the dropdown. (Note: make sure to click Save after making changes to the extension config!).</p><p>You can access a log of events that have occurred in the Stripe dashboard by going to Developer-&gt;Events. If you click on an event, you can see all the data that will be available to you if you use that event. Events that I ended up using are:</p><ul><li>com.stripe.v1.checkout.session.completed — a successful payment occurred</li><li>com.stripe.v1.customer.subscription.deleted — a users subscription ended</li></ul><p>To handle events, insert something like following into functions/index.js . As an example, I am handling the checkout.session.complete event:</p><pre>const {onCustomEventPublished} = require(&#39;firebase-functions/v2/eventarc&#39;);<br><br>// other stuff in your firebase functions<br><br>// eventarc events (for Stripe payments extension)<br>exports.onCheckoutSessionCompleted = onCustomEventPublished(<br>  &#39;com.stripe.v1.checkout.session.completed&#39;, <br>  (event) =&gt; {<br>    // handle event<br>    // get the same JSON ojbect you see in the Stripe dashboard<br>    const eventData = event.data;<br><br>    // for example, check if the payment was a one time payment:<br>    if (eventData.mode === &#39;payment&#39;) {<br>      // one time payment was succesful, handle it...<br>    }<br>  });</pre><h4>Wrapping Up</h4><p>If you got this far, thanks for reading — I hope this guide helps you build your awesome app.</p><p>Here are some other potentially useful links:</p><ul><li><a href="https://github.com/stripe-samples/firebase-subscription-payments">Example repo for a firebase project using Stripe</a></li><li><a href="https://stripe-subs-ext.web.app/">Live demo site of the above repo</a></li><li><a href="https://github.com/invertase/stripe-firebase-extensions/blob/next/firestore-stripe-payments/README.md">Official docs for the Stripe Firebase extension</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90c816f02d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebase-developers/processing-payments-in-firebase-with-stripe-e90c816f02d0">Processing Payments in Firebase with Stripe</a> was originally published in <a href="https://medium.com/firebase-developers">Firebase Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>