<?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 Deepankar Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Deepankar Agrawal on Medium]]></description>
        <link>https://medium.com/@deepankar11093?source=rss-50a7f191204b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CywMlfoRWB2-PwLyjHz-6w.png</url>
            <title>Stories by Deepankar Agrawal on Medium</title>
            <link>https://medium.com/@deepankar11093?source=rss-50a7f191204b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 09:32:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepankar11093/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[Authentication In GRPC]]></title>
            <link>https://medium.com/vernacular-ai/authentication-in-grpc-888a18015fae?source=rss-50a7f191204b------2</link>
            <guid isPermaLink="false">https://medium.com/p/888a18015fae</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[Deepankar Agrawal]]></dc:creator>
            <pubDate>Thu, 05 Mar 2020 07:22:35 GMT</pubDate>
            <atom:updated>2020-03-05T07:22:35.905Z</atom:updated>
            <content:encoded><![CDATA[<p>In gRPC, there are a number of ways you can add authentication between client and server. It is handled via Credentials Objects.</p><p>There are two types of credential objects:</p><p>1. <strong>Channel Credentials:</strong> These are handled on the channel level, i.e when the connection is established and a channel is created.</p><p>2. <strong>Call Credentials:</strong> These are handled on per request level, i.e for every RPC call that is made.</p><p>These Credential objects can also be combined to create <strong>CompositeChannelCredentials</strong> with one Channel Credential and one Call Credential object.</p><p>Now let us see how we can use these credential objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*MiTB7tc3V6K_DyYN1SseHw.png" /></figure><h4><strong>Client-Side TLS/SSL Authentication</strong></h4><p>gRPC provides a way to establish a connection without any secure connection i.e just like HTTP.</p><pre>// client.go</pre><pre>conn, _ := grpc.Dial(“localhost:5000”, grpc.WithInsecure())</pre><pre><br>// server.go</pre><pre>lis, err := net.Listen(“tcp”, “:5000”)</pre><pre>s := grpc.NewServer()</pre><pre>s.Serve(lis)</pre><p>For secure communication, we will create <strong>TransportCredentials</strong> which is a type of ChannelCredential object.</p><pre>// client.go</pre><pre>creds, _ := credentials.NewClientTLSFromFile(certFile, “”)</pre><pre>conn, _ := grpc.Dial(“localhost:5000”, grpc.WithTransportCredentials(creds))</pre><pre>// server.go</pre><pre>lis, _ := net.Listen(“tcp”, “localhost:50051”)</pre><pre>creds, _ := credentials.NewServerTLSFromFile(certFile, keyFile)</pre><pre>s := grpc.NewServer(grpc.Creds(creds))</pre><pre>s.Serve(lis)</pre><p>You can read more about generating own ssl certificates <a href="https://www.linuxjournal.com/content/understanding-public-key-infrastructure-and-x509-certificates">here</a>.</p><p>In the case where you don’t own the client, it means you are creating a gRPC API for public use, you cannot give your certificate to everyone using your client. In that case, we rely on well known <a href="https://en.wikipedia.org/wiki/Certificate_authority">Certificate Authority</a> like LetsEncrypt, Amazon, etc. to generate a certificate. So let us change our client code a little.</p><pre>// client.go</pre><pre>config := &amp;tls.Config{</pre><pre>  InsecureSkipVerify: false,</pre><pre>}</pre><pre>conn, err := grpc.Dial(address, grpc.WithTransportCredentials(credentials.NewTLS(config)))</pre><pre>// server code remains the same</pre><p>In this case what happens is that grpc loads the certificates of well-known Certificate Authorities from the OS and sends it to the server, hence no need to manually provide a certificate.</p><h4><strong>Token-Based Authentication / OAuth2</strong></h4><p>Many a time we want to differentiate a client by issuing them different tokens. TLS Authentication is a good way to secure your connection but it does not tell us from which client the request is coming from. We will send the token in request metadata just like HTTP Headers.</p><blockquote>gRPC has google.golang.org/grpc/metadata package to send and receive metadata with a RPC request.</blockquote><pre>// client.go</pre><pre>// add metadata to request context</pre><pre>md := metadata.Pairs(“Authorization”, “Bearer xxx-xxx-xxx”)</pre><pre>ctx := metadata.NewContext(context.Background(), md)</pre><pre>// use this context to call rpc</pre><pre>_, err = client.CallRPC(ctx, requestObject)</pre><p>We will use <strong>UnaryInterceptor</strong> on the server which acts as middleware and checks for the token for all the requests.</p><pre>// create a middleware</pre><pre>func AuthInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {</pre><pre>  meta, ok := metadata.FromContext(ctx)</pre><pre>  if !ok {</pre><pre>    return nil, grpc.Errorf(codes.Unauthenticated, “missing context metadata”)</pre><pre>  }</pre><pre>// Take care: grpc internally reduce key values to lowercase</pre><pre>if len(meta[“authorization”]) != 1 {</pre><pre>return nil, grpc.Errorf(codes.Unauthenticated, “invalid token”)</pre><pre>}</pre><pre>if meta[“authorization”][0] != “xxx-xxx-xxx” {</pre><pre>return nil, grpc.Errorf(codes.Unauthenticated, “invalid token”)</pre><pre>}</pre><pre>return handler(ctx, req)</pre><pre>}</pre><pre>// pass this when creating server</pre><pre>server := grpc.NewServer(</pre><pre>   grpc.UnaryInterceptor(AuthInterceptor),</pre><pre>)</pre><p>But above code only works for non-streaming RPCs. For Streaming RPCs you can implement <strong>StreamInterceptor</strong>. Instead of implementing it again you can use <a href="https://github.com/grpc-ecosystem/go-grpc-middleware">this</a> package.</p><p>I hope this article helps you with authentication in gRPC.</p><p>If you are interested in working with cutting-edge technologies, come work with <a href="https://vernacular.ai/">Vernacular.ai</a>. Apply <a href="https://angel.co/company/vernacular-ai/jobs">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888a18015fae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vernacular-ai/authentication-in-grpc-888a18015fae">Authentication In GRPC</a> was originally published in <a href="https://medium.com/vernacular-ai">Skit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing your Own 2D Game engine]]></title>
            <link>https://medium.com/@deepankar11093/implementing-your-own-2d-game-engine-389c242a75a9?source=rss-50a7f191204b------2</link>
            <guid isPermaLink="false">https://medium.com/p/389c242a75a9</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[collision-detection]]></category>
            <category><![CDATA[game-engine]]></category>
            <dc:creator><![CDATA[Deepankar Agrawal]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 20:38:39 GMT</pubDate>
            <atom:updated>2019-01-29T23:08:21.488Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, you would think that when there are so many game engines out there why would you want to implement your own. Well it may be that you don’t like any of them, or just thinking of starting a game and implementing your own engine might be a good idea, then please don’t do it and this article might not be for you. But if you (like me), want to learn the nitty-gritty of a physics engine, this could be a good exercise.</p><p>Here is the demo of the end result and you can find the code <a href="https://github.com/deep110/LucidEngine">here</a> on my GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*uT1N3BbT3ojHwAgRzGOhBA.gif" /></figure><p>In this article, I won’t be providing any code snippets since you can find that in the GitHub link I have provided above, but more of an explanation of how things are pieced together.</p><p>First, we will start with some basic assumptions:</p><p>1. All bodies are <a href="https://en.wikipedia.org/wiki/Rigid_body">rigid bodies</a> means they cannot deform on impact.</p><p>2. Colliding shapes of rigidbodies are <a href="https://en.wikipedia.org/wiki/Convex_polygon">convex</a>, non-convex shapes should be bounded by a convex shape for collision detection purposes.</p><p>2. Physics simulation runs at a constant frame rate i.e usually 60 fps.</p><p>3. Whatever I will be describing has been implemented for 2D but most of the general idea is applicable for 3D as well. Also, the processes I have described is what I have implemented, different game engines tend to use different models or optimizations.</p><h4><strong>Overview</strong></h4><p>For a physics engine to function properly it should perform three basic things:</p><p>1. It should be able to predict translational properties like position, velocity, acceleration and rotational properties like orientation, angular velocity, torque at any given point of time.</p><p>2. It should be able to detect which bodies are colliding.</p><p>3. It should be able to properly resolve the impulses generated due to those collisions.</p><h4><strong>Calculating Properties</strong></h4><p>For calculating the properties we basically use Newton’s Law of motion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*CGd5iN0zKlkiuEoTj4EfnQ.png" /></figure><p>and,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*A63KojJaJzMhnvhTRyg_Vg.png" /></figure><p>where,</p><blockquote><em>F = force applied</em></blockquote><blockquote><em>v = Velocity</em></blockquote><blockquote><em>m = mass of body</em></blockquote><blockquote><em>x = position</em></blockquote><blockquote><em>dt = time elapsed since last execution (1\60 if 60 fps)</em></blockquote><p>To solve these differential equations for games, we widely come across these three integrators:</p><ol><li><a href="https://en.wikipedia.org/wiki/Euler_method"><strong>Explicit Euler method</strong></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*SCbcJBULlHwqUXZFXSckMQ.png" /><figcaption>Euler Integration</figcaption></figure><p>It is the most basic method to solve this first order differential equation. It is just adding the curve values at small intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*jngZqMzQ63qgMgA3hv4REw.png" /></figure><p>2. <a href="https://en.wikipedia.org/wiki/Backward_Euler_method"><strong>Implicit (Symplectic) Euler</strong></a></p><p>The difference here is we solve the problem using right <a href="https://en.wikipedia.org/wiki/Riemann_sum">Reimann sum rule</a> instead of left sum rule. For those who are not going to read Wikipedia, reimann sum is used to calculate the area of the region by breaking it into small shapes. In Euler methods region is a rectangle.</p><p>For example, to get the position at time t, we will need velocity at time t+1, so instead of starting with zero velocity, we compute velocity first and then position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*LDaM2RGG6Ggdf_yYNHJyTg.png" /></figure><p>3. <a href="https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods">Runge-Kutta (RK) 4th Order Method</a></p><p>I won’t be going into much explanation about what it does, but it gives better accuracy than euler methods but is computationally expensive. Actually, Euler methods are just a special case of RK.</p><p>Implicit Euler gives us more accurate results than explicit Euler and is much closer to RK4. <a href="https://gafferongames.com/post/integration_basics/">Here</a> is a more detailed comparison of all three methods and is explained why implicit Euler is okay for game engines.</p><p>So using implicit Euler we will get:</p><pre>v += (1/m * F) * dt</pre><pre>x += v * dt</pre><p>If we take rotation into account,</p><pre>ω += (1/I * τ) * dt</pre><pre>θ += ω * dt</pre><p>where,</p><blockquote>I = Moment of Inertia</blockquote><blockquote>θ = orientation</blockquote><blockquote>ω = angular velocity</blockquote><blockquote>τ = Torque</blockquote><h4><strong>Calculate colliding pairs of rigidbodies</strong></h4><p>At each loop, it is necessary for the engine to know which pair of rigidbodies are colliding, so that the collision can be solved and bodies do not pass each other.</p><p>Naively if we iterate on all N bodies, we will need to check `<strong>N*(N-1)/2</strong>` possible combinations which are a lot. Suppose N = 100, we will need to check 4950 body pairs which can take way too much than the frame duration (i.e just 1/60s or 16ms). In most of the games, there are more objects present than that at any given point of time.</p><p>So first we use a process called <strong>BroadPhase calculation</strong> to narrow down the number of collisions to check. Its purpose is to generate a list of pair of rigid bodies that may be colliding.</p><p>* It is implemented through <a href="https://en.wikipedia.org/wiki/Space_partitioning">Space Partitioning</a> Algorithms.</p><p>* The basic idea is that you divide the whole region into grids (in volumes for 3D) and assign every rigidbody to a position in the grid.</p><p>* Now, the body is added to each cell it is overlapping, so at last, we iterate through the grid and make a pair of overlapping bodies. Objects are stored in data structures like <a href="https://en.wikipedia.org/wiki/K-d_tree">k-d tree</a><strong> </strong>or <a href="https://en.wikipedia.org/wiki/BSP_tree">BSP tree</a> for efficiency. It generally reduces the iterate time from O(N²) to logarithmic times.</p><p><a href="http://buildnewgames.com/broad-phase-collision-detection/">Here</a> is a nice blog explaining the broadphase implementation in more detail, like the choice of grid size, etc. My demo was just for a small scope, so I have not implemented this part.</p><p>Then we proceed to <strong>NarrowPhase calculation</strong> i.e which actually determines which bodies are colliding. The aim of Narrowphase is to calculate three things for every pair of colliding bodies:</p><p>1. <strong><em>Collision Normal</em></strong>: Direction of bodies they are colliding</p><p>2. <strong><em>Penetration Depth</em></strong>: How much bodies have overlapped each other</p><p>3. <strong><em>Contact Points</em></strong>: Points of contact where they are overlapping</p><blockquote>It can be implemented using <a href="https://en.wikipedia.org/wiki/Hyperplane_separation_theorem">Separating Axis Theorem</a>.</blockquote><blockquote>The basic principle is: <em>If two bodies are not colliding, there will be a certain axis for which their projections will not overlap.</em></blockquote><p>For a general convex polygon there could be a lot of axes to check, but for simplification purposes, I have just taken the shape of the colliders to be <strong><em>Circle</em></strong> and <strong><em>Axis-Aligned Bounding Box (AABB)</em></strong> i.e just a rectangle. Now for collision checks, we will like to implement four combinations (not taking rotation into account):</p><p>* <strong>Circle-Circle</strong>:</p><p>For this, the test is easy — Distance between circles should be less than the sum of their radii</p><pre>// distance must be less for overlap</pre><pre>isColliding = distance(circle1, circle2) &lt;= circle1.radius + circle2.radius</pre><p>* <strong>Circle-AABB</strong></p><p>We will first find the nearest point of contact on AABB between AABB and circle.</p><pre>positionDiff = AABB.pos — circle.pos</pre><pre>// on x-axis take the point which is near, the bounds or diff</pre><pre>nearestPoint.x = clamp(-AABB.width/2, AABB.width/2, positionDiff.x)</pre><pre>// same for y-axis</pre><pre>nearestPoint.y = clamp(-AABB.height/2, AABB.height/2, positionDiff.y)</pre><pre>// distance between nearest point on rectangle and circle’s center should</pre><pre>// be less than circle’s radius</pre><pre>isColliding = distance(circle1, nearestPoint) &lt;= circle.radius</pre><p>* <strong>AABB-Circle</strong></p><p>Same procedure as above</p><p>* <strong>AABB-AABB</strong></p><pre>positionDiff = AABB2.pos — AABB1.pos</pre><pre>// find overlap values</pre><pre>xOverlap = AABB1.width/2 + AABB2.width/2 — abs(positionDiff.x) // x-axis overlap</pre><pre>yOverlap = AABB1.height/2 + AABB2.height/2 — abs(positionDiff.y) // y-axis overlap</pre><pre>// for bodies to be colliding both axis must overlap</pre><pre>isColliding = xOverlap &gt; 0 &amp;&amp; yOverlap &gt; 0</pre><p>For a convex polygon, its implementation will be more complex, there is a good <a href="https://gdcvault.com/play/1017646/Physics-for-Game-Programmers-The">video</a> in GDC Vault explaining the process. Also, you can go through the <a href="https://github.com/erincatto/Box2D">Box2D</a> code for the same. It is next in my list for implementation.</p><h4><strong>Impulse Resolution</strong></h4><p>Impulse resolution means when bodies collide, we need to stop them from moving inside each other. The first thing that comes to mind is that we can apply a force to them, but force does not instantaneously change the velocity. For this, we directly change the velocity of the bodies or say we applied an impulse (i.e you can think of it as a large force in almost zero time).</p><p>Each rigidbody apart from dynamic properties also has some physical properties which we group into <strong>Material</strong>.</p><p>- <strong>Mass (m)</strong>: how much the body weigh</p><p>- <strong>Coefficient of restitution (e)</strong>: how rough is the surface</p><p>- <strong>Coefficient of Static friction (μₛ)</strong>: friction coefficient for stationary objects</p><p>- <strong>Coefficient of dynamic friction (μd)</strong>: friction coefficient for moving objects</p><p>For a pair of bodies, we calculate equivalent coefficients.</p><p>* Equivalent coefficient of restitution is `<strong>e = min(e1, e2)</strong>`.</p><p>* Equivalent coefficients of friction are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*zF_eMHqtEWNMKLUtOx2YPA.png" /></figure><p>During the time of contact we will consider two impulses acting on them:</p><p>1. Normal Force (Normal to the plane of contact)</p><p>2. Frictional Force (Tangential to the plane of contact)</p><p>Impulse (j) is calculated using <a href="https://en.wikipedia.org/wiki/Momentum#Conservation"><strong>Momentum Conservation</strong></a> and <a href="https://en.wikipedia.org/wiki/Coefficient_of_restitution"><strong>Newton’s law of restitution</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*3HIxlIHZq6ICwIWVWqAuag.png" /></figure><p><strong>Normal Impulse</strong></p><p>Let us define some variables,</p><pre>vA, uA = final and initial velocity of body A</pre><pre>vB, uB = final and initial velocity of body B</pre><pre>jA = change in momentum of A</pre><pre>jB = change in momentum of B</pre><pre>n = normal vector in direction of collision normal (n.n = 1)</pre><p>According to Newton’s law of restitution,</p><pre>e = relative final velocity / relative initial velocity</pre><p>Since momentum is conserved, change in momentum of Body A will be opposite to the change in momentum of body B i.e <strong>jA. n = -jB. n</strong>. Taking a dot product with `<strong>n</strong>` since we are interested only in normal direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*QhyuGYmDCJ5ddl7se0_WXw.png" /></figure><p>So our aim is to calculate <strong>j</strong> in terms of initial velocity since we don’t know the final velocities of bodies after the collision. We will just rearrange the terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*o-44C-VXV4x06uplAMYSlQ.png" /></figure><p>Whew, that’s a lot of equations, but don’t worry that’s just rearranging the terms to get what we need, you can work it out yourself.</p><p>If you want to rotational motion into account, it&#39;s easy, like linear momentum, angular momentum is also <a href="https://en.wikipedia.org/wiki/Angular_momentum#Conservation_of_angular_momentum">conserved</a>. Let us define more terms so that further equation can be clear.</p><pre>L = angular momentum</pre><pre>p = linear momentum</pre><pre>I = Moment of Inertial about Center of Mass (COM)</pre><pre>r = radius vector perpendicular to COM</pre><p>Some basic definitions,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*aGViNLqlTeTAn2E_bWxTtA.png" /></figure><p>When considering the change in linear momentum also add angular momentum giving us the final equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*U2clI5_Dqf1YLQ49Nts2kA.png" /></figure><p><strong>Frictional Impulse</strong></p><p>Frictional Impulse is applied perpendicular to collision normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*fXKACE1FpradVcstMGDG1w.png" /></figure><p>Frictional impulse can be calculated by just substituting normal vector with the tangential magnitude of relative velocity and in opposite direction.</p><p>Replace `n` with `t`:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*gCmj5dxPmlx7yo9QSLoeKg.png" /></figure><p>Now we just need to calculate `<strong>t</strong>`. For that, we will get the normal component of relative velocity and subtract from total relative velocity to get tangential component (Vector Math). A negative sign is used since friction is always opposite to the direction of motion.</p><pre>t = -[Vᴬᴮ − (Vᴬᴮ⋅n)∗n]</pre><p>But wait there is a catch, friction acts differently for static and dynamic objects, that is why two coefficients of friction. How to use them can be determined using <a href="https://en.wikipedia.org/wiki/Friction#Dry_friction"><strong>Coulomb’s Law</strong></a>.</p><pre>jf &lt;= μ * jn</pre><p>Let us understand this definition, if our solved <strong>jf</strong> (representing the force of friction ) is less than static coefficient (μₛ) times the normal force (<strong>jn</strong>), then we can use our <strong>jf</strong> magnitude as friction. If not, then we must use our normal force times dynamic coefficient(μd) instead.</p><pre>if (abs(jf) &lt; μ<strong>ₛ</strong>jn) {</pre><pre>// no change</pre><pre>} else {</pre><pre>   jf = μd * jn</pre><pre>}</pre><p>Hopefully, you can now begin to understand the basics of writing a game engine, and again you can find the code <a href="https://github.com/deep110/LucidEngine"><strong>here</strong></a>. I have tried to include most of the topics that are absolutely required to implement a working demo. Now you can read up articles for specific topics to understand them more and how it will benefit your implementation.</p><p><strong>Image and Other Credits</strong></p><p>* Wikipedia</p><p>* <a href="https://www.researchgate.net/figure/Spatial-partition-of-a-2D-scene-using-a-quadtree-subdivision_fig2_236611845">ResearchGate</a></p><p>* <a href="https://gamedevelopment.tutsplus.com/tutorials/collision-detection-using-the-separating-axis-theorem--gamedev-169">GameDevTuts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=389c242a75a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>