<?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 Ahsen Khan on Medium]]></title>
        <description><![CDATA[Stories by Ahsen Khan on Medium]]></description>
        <link>https://medium.com/@ahsen35813?source=rss-d4b61cc81dbd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gxU5W1RHUwexZaJ4</url>
            <title>Stories by Ahsen Khan on Medium</title>
            <link>https://medium.com/@ahsen35813?source=rss-d4b61cc81dbd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:43:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahsen35813/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[How to get started using Unity3D Machine Learning Agents]]></title>
            <link>https://ahsen35813.medium.com/how-to-get-started-using-unity3d-machine-learning-agents-2f5a456fd434?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5a456fd434</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unity3d]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 18:17:04 GMT</pubDate>
            <atom:updated>2023-12-29T18:40:06.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_-0bpr6iPdexjgmb5OIBw.png" /></figure><p>A few years ago I started learning about Unity’s Machine Learning package, and how to use it to create AI that can act intelligently. I followed a tutorial from the Unity website, about creating and training ML hummingbirds to collect nectar from flowers. If you want to see it, click here: <a href="https://learn.unity.com/course/ml-agents-hummingbirds">https://learn.unity.com/course/ml-agents-hummingbirds</a>. Now, I am going to go through the basics of how to get started with Unity ML Agents hopefully so that you can do the same after reading this article as opposed to spending days learning from the tutorial. Some programming experience is recommended.</p><p>Keep in mind, this is a general overview of how to create a machine learning project. There are no specific instructions on how to make a certain project. The aim of this article is to give you a good understanding of the general process, but you will most likely need to do your own research on particular implementation details, especially if any information here is out of date at the time of reading. For the same reason, imitation learning, optimizing model rewards, and some other in depth topics will not be covered in this article.</p><h3>Step 1 : Downloads</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9cy-4B-L3B9EsW5_7p05Q.png" /></figure><p>First of all, we need to set up the basic project. First, download and install Unity if you have not done so already. You can access the download for Unity Hub here: <a href="https://unity.com/download">https://unity.com/download</a>. Make sure to create an account first. There is some confusing licencing stuff too, but you will figure it out eventaully.</p><p>You first need to install Unity Hub, and then inside of Unity Hub, sign into your Unity account and activate a licence for your device. Then click on the ‘installs’ tab. Make sure you go into settings (the gear icon in the top right corner) and set the install location to the folder where you want to install the actual Unity application. Then, click ‘Add’ and select the version of Unity that you want (preferably the latest LTS version). On the next page, you can add ‘Modules’ which is support for exporting to various platforms. I would recommend at the very least to have support for building to the platform that you are on (e.g If you are on macOS, add in the “Mac Build Support” module). WebGL is nice to have as well. You can host WebGL builds on Github pages to allow anyone to access it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLVBUvPpyW4TmPLDSHBiSQ.png" /><figcaption>The most recent LTS (long term support) version is probably your best choice.</figcaption></figure><p>Installing the module will take quite a while, so come back to it in a bit. Make sure that you have set a download location! I made this mistake the first time I tried installing modules, and the download mysteriously disappeared immediately after being installed, every single time…</p><p>Once you’ve got your modules set up, click on the Projects tab and create a new project. Choose 3D or 2D depending on what you’re hoping to do. Don’t use HDRP or URP, because those use more performance intensive and better looking rendering methods. For ML training, it’s best to have very simple graphics to minimize the amount of processing power spent on those. It is possible to upgrade the project later if you choose. Name your project, and choose where you want to save it. The project will be saved in a folder with the name of your project. I would recommend creating a folder dedicated to just Unity project. Click ‘Create’ and Unity should prepare the project and open it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zu0nOYURyQohP8lRqlkQQ.png" /></figure><p>When the project is open, you will need to instal the ML Agents package from Unity’s package manager (Window&gt;Package Manager). Once that is installed, the project is set up for machine learning, and you can begin the fun part!</p><h3>Step 2 : Setup</h3><p>Create your universe. Decide what you want to create, and what the agent needs to do. For a first project, I would recommend something simple like balacing a ball on a flat surface (2 inputs : pitch and roll) or driving a car around a track (2 inputs : forward/back and right/left).</p><p>There are two main ways you can go about this. You can create the game world first, and all the human controls.</p><p>The other option is to integrate the AI into the world immediately from the start. This is pretty much required for very complex agents like a multilegged robot, which would be incredibly difficult to control manually.</p><p>This first half a step should not be neglected. I am compressing pretty much all of game dev into half a step. Do not underestimate how long this could take.</p><p>Now, you need to add the ML components to the agent to turn it into an agent. You must add Behaviour Parameters, Decision Requester, and an agent script. The agent script should be your own script, where you will write your own code for the agent in the coding section below. In this script, you must change the default script’s MonoBehaviour to derive from Agent instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*1YcE4H8uQ2-ds1JsFdXh0w.png" /><figcaption>Before (top) and after (bottom)</figcaption></figure><p>Now you are ready for the next step.</p><h3>Step 3 : Code</h3><p>The next step is to write all the code for the AI. For this example, wrote some code for an <a href="https://01000001-01101011.github.io/self-driving-car/">ML racecar</a>. I will not include any code, because there is an abundance of examples on the internet already. One more will have little benefit.</p><p>Here’s a general overview of the process: First, the environment is initialized. Then the agent is spawned. The agent needs to collect observations of its environment, and then the neural network processes what it needs to do, and decides what actions to perofrm. This repeats every training step, until the training episode time runs out, or you call EndEpisode()to immediately end the training episode (for example, if an AI car crashes into a wall, or falls off the edge of the world)</p><p>What you need to do is override a few functions. These functions are Heuristic (manual control), ActionReceived (convert actions to real behaviour), Initialize (essentially the same as Start() after the agents start training), Episode Begin (respawn agents when their episode ends, for example), and Collect Observations (give the agent info about its environment).</p><p>The first one is <strong>Initialize</strong>, which runs at the very start of the program. Here you can initialize variables, spawn in agents, etc.</p><pre>public override void Initialize()</pre><p>Then you have the <strong>Heuristic</strong>. This lets you use your own pretrained neural network (your brain :P) to control the AI.</p><pre>public override void Heuristic(in ActionBuffers actionsOut)</pre><p>In my agent for example, I did something like this. vertical and horizontal are values from the arrow keys to control the wheels, and brake is for the brakes.</p><pre>var continuousActionsOut = actionsOut.ContinuousActions;<br>continuousActionsOut[0] = verticalInput;<br>continuousActionsOut[1] = horizontalInput;<br>continuousActionsOut[2] = brakeInput;</pre><p>These values are then sent to <strong>OnActionReceived</strong>, which converts those actions into real behaviour.</p><pre>public override void OnActionReceived(ActionBuffers actions)</pre><p>In my case, I just extract the control values and then use them to control the car.</p><pre>vertical = actions.ContinuousActions[0];<br>horizontal = actions.ContinuousActions[1];<br>brake = actions.ContinuousActions[2];<br>// These values are then used within FixedUpdate() for physics stuff</pre><p>During training, <strong>Heuristic</strong> is not used at all. The neural network sends information to the action buffer instead of you.</p><p>Another important one is <strong>OnEpisodeBegin</strong>. This is called for every agent every time its training episode ends when the time runs out, or EndEpisode() is called.</p><pre>public override void OnEpisodeBegin()</pre><p>Here you can respawn the agents, reset a score, or anything you want. The sky’s not the limit. Only processing power!</p><pre>public override void CollectObservations(VectorSensor sensor)</pre><p>Here, you can add ‘observations’ to the agent. If you are using the ray perception component on your agent, it will already use those without having to add anything here. However, you may find it useful to provide the AI with more information about its environment, such as its position, rotation, speed, etc. It’s best to keep it simple, to avoid overloading the agent with too much information.</p><p>To give the agent custom information, you need to add the following code:</p><pre>sensor.AddObservation(yourData);<br>sensor.AddObservation(moreData);<br>sensor.AddObservation(usefulData);</pre><p>Inside sensor.AddObservation(), you can pass a Vector3, an int, or a float.</p><p>Those are almost all the most important functions. If the code above does not work, check online for other people having the same problems. Given the current pace of AI development, it is likely that the code in this article will stop working eventually for future versions of Unity ML-Agents.</p><p>The <em>most</em> important function is AddReward(float). This single function is the most powerful determinant for how well your model will perform. Correctly balancing reward is a surprisingly complex topic, so much so that I may write another article going into depth about how to optimize it. However, the main idea is as follows: When the agent does something good, reward it. When the agent does something undesirable, punish it (using negative reward). The agent will do everything it can to maximize that score. Treat your agent as an extremely clever toddler and be careful not to punish the agent too much. Too much punishment, and it might learn that the best way to maximize reward is to sit still and do nothing.</p><p>Tuning this will take a while. For now, make your best guess on how the agent should be rewarded.</p><p>Onto the next step!</p><h3>Step 4 : Python environment</h3><p>In order to set up your python environment, you need to use the terminal, or CMD on Windows. For this article I will use macOS commands, which are similar for Linux. Some terminal experience is recommended, but ml-agents was actually one of the very first things I used terminal for.</p><blockquote>Optionally, you can chooose to do the commands in a sandbox, separating the packages you install from the rest of your system. To do so, first install miniconda, then “conda create -n environmentName python=3.7” to create a new environment, and enter it with “conda activate environmentName”. Do this before beginning the steps below. You can exit with “conda deactivate”. Any packages you install inside the conda environment will only exist in there and will not interfere with the rest of your system. This is not required, but can be useful.</blockquote><p>Now the very first thing to do is to choose a folder on your computer in which to store the training files. Once you have decided this folder, create a new file there called someRandomName.yaml. Now in this file, you need to set up some parameters for your agent. These are too extensive to go over in detail, so I will instead <a href="https://github.com/Unity-Technologies/ml-agents/blob/main/docs/Training-Configuration-File.md">link to the documentation</a> explaining what they all do. An example of how your file might look is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*JqAOusB6R8RSazGuOePqSA.png" /></figure><p>The name of your model here is very important. This <strong>must</strong> match the name of the agent’s “Behaviour Name” in the Behaviour Parameters component inside Unity. The python in the terminal will use the computer’s network to connect with the agent inside Unity, and the terminal will do the difficult part of optimizing the neural network, while Unity simulates the results.</p><p>In my experience, the most critical parameters to understand are hidden_units and num_layers. I strongly recommend <a href="https://www.youtube.com/watch?v=aircAruvnKk">this video</a> by 3Blue1Brown for some background understanding of how neural networks work.</p><p>Next, install ml-agents in the terminal with pip3 install mlagents.</p><blockquote>Note: You may need to later reinstall the mlagents python package or Unity package or both to find the versions that work together.</blockquote><p>Now running the training program is a bit trickier. In the terminal, navigate to the folder you chose, which contains your someRandomName.yaml file. This is done using the cd command.</p><p>If the path to the yaml configuration file is /users/me/path/to/AI-Stuff/someRandomName.yaml, then the command you need would be one of the following:</p><pre>cd /users/me/path/to/AI-Stuff<br>cd ~/path/to/AI-Stuff</pre><p>where the tilde (~) functions as the path to your user account’s directory.</p><p>Now we can finally start training with</p><pre>mlagents-learn ./someRandomName.yaml --run-id agent_01</pre><p>agent_01 is the name of the training session, and you can change this to train different versions of the AI with different names and save previous ones for future reference. This will now create a new folder in your selected folder with the name that you provided in -run-id . If you stop it for any reason, you can resume training of the same model by simply adding --resume on the end of the previous command (you can access command history by pressing the up arrow on your keyboard).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*HqPPdeR1tTRLenIqOIKkig.png" /><figcaption>You will hopefully see something like this</figcaption></figure><p>Once the program is ready to start training, press play in the Unity editor. If all goes well, your agent(s) will now be behaving chaotically :)</p><h3>Step 5 : Optimize</h3><p>Training takes time. I typically leave my computer running overnight to train the model, and sometimes more than a day.</p><p>If you have just one agent in your scene, it will run at a very high speed, trying to make the most of the processing power available, but it can only do so much. To speed things up, create several copies of the agent and it’s environment spaced apart so that the agents cannot interact with each other. If your environment is static, like training a race car for example, you can use a single environment and have all the cars be invisble to each other and not collide with each other using Unity’s physics layers. If you want the agents to compete with each other, then you can put all of them in a single environment, but then you must be very careful about how many agents you put into one environment.</p><p>With more agents in your world, training will be quicker since all of the agents share the same neural network brain, and learn from each others’ experiences. There is a balance between not enough and too many agents, which differs based on the complexity of your system and available processing power.</p><p>To see how your agent is doing, open a new terminal window (activate the conda environment again for this window if you’re using it) and navigate to the same folder using cd. Then input tensorboard --logdir TheModelName and press enter. Now, go the link provided. This will show you a graph of all the agents trained so far and in progress. There are several buttons and sliders to fiddle with the display.</p><p>After a while, it is possible that your AI is doing exactly what you want it to! This is the ideal scenario. However, it is more likely that the agent has figured out a loophole to farm rewards. Some of my experiences include agents applying negative braking to accelerate faster and doing donuts to maintain speed near the centre of the lane. Another time, a robotic arm found out that the best way to get rewards was to keep it’s hand close to the target but not touch it in order to rapidly gain points. Another agent figured out how to do ridiculous acrobatics on one leg to stand as tall as possible, using the other one to improve stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hgf4hxs-rYAw3vNkSrFlhQ.gif" /><figcaption>AI will find the loopholes and exploit them to the max</figcaption></figure><p>Once this happens, fix the reward system and train again. Keep fine tuning the rewards and retraining the agent until you are happy with the result. This can take several days of work. Be patient :)</p><p>That’s all for now. There is a lot more to AI, even just within Unity3D ml-agents which I did not cover in this general overview. It will take time to master the basics. A first project could take anywhere from a few hours to a few weeks to set up. I strongly recommend doing your own research to improve your future projects. As mentioned above, I may write another article explaining in depth some methods for optimizing reward functions. Good luck!</p><p>Below are some demos I created a while ago for you to compete against the trained AI model in an arcade style race around a simple track.</p><p><a href="https://01000001-01101011.github.io/ai-test/">Original</a> : Better graphics, tire smoke, controllable camera.</p><p><a href="https://01000001-01101011.github.io/self-driving-car/">Performant</a> : Easier to control given the automatic camera. Highly optimized graphics for low end devices (got 35 fps on a 10 year old PC!) and a slightly different track to show that the agent can generalize to a new track it has never seen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5a456fd434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some interesting Raymarching concepts]]></title>
            <link>https://blog.devgenius.io/some-interesting-raymarching-concepts-8e38aa67e1ef?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e38aa67e1ef</guid>
            <category><![CDATA[raymarching]]></category>
            <category><![CDATA[shadertoy]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 13:39:17 GMT</pubDate>
            <atom:updated>2024-06-29T00:47:02.179Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will go into some depth about raymarching, beyond the basics. If you’re just starting on the topic, see my first <a href="https://ahsen35813.medium.com/learning-python-by-building-a-custom-3d-renderer-2c75b21361d0">article about the subject</a>. Like before, I will avoid providing language specific code and instead will keep it as generic as possible.</p><h3>Concept 1: Lighting</h3><p><strong>Shading</strong></p><p>The very basics of shading are actually <em>very</em> simple. In order to calculate simple shading based on normals, usually the dot product is used. Essentially what the dot product does is give you the magnitude of the ‘sameness’ of vectors. If you have a random normalized vector a and put it into a dot product like so: dot(a, a), then the result of the operation will be exactly 1. If you put in dot(a, -a) then the result will be -1. If the vectors are pointing in the same direction, the result is 1. Opposite returns -1 and right angles result in a returned value of 0, regardless of the directions they are pointing in space. If the vectors are not normalized, then the output is affected by the product of the lengths of the input vectors, since the dot product works by multiplying individual components together like so:</p><pre>dot(vec3 a, vec3 b)<br>{<br>    return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.n * b.n)<br>}</pre><p>This would be where n would be further dimensions. Surprisingly, most 3D graphics concepts and functions can quite easily be expanded to dimensions beyond normal 3D space, even though they are quite tricky to understand in higher dimensions.</p><p>So now that you understand dot products, you can use them!</p><blockquote>Side note: Dot products are almost always a part of graphics and math libraries, so you’ll probably never have to implement it yourself, but I find it very helpful to understand <strong><em>everything</em> </strong>you’re coding, from the bare math to the end product. In graphics programming there’s rarely an easy Stack Overflow answer to problems you might be having. It’s very valuable to understand everything so you can fix it yourself, and also implement it in lower level languages where you don’t have as much easy access to libraries.</blockquote><p>Shading is as easy as taking the dot product of of the surface normal and the direction of the light. light = dot(lightDir, normal). It’s practically free compared to the cost of casting rays. You could also do light = dot(lightDir — hitPos, normal) to get the shading from a point light, but then you’re responsible for properly implementing the light falloff :P</p><p>You also might want to clamp the values of the shadows. The back side, which is pointing away from the light, will have a light value of -1 unless you clamp it to 0. For example, light = max(0.0, light). This probably won’t be a problem immediately, but you might as well do it properly from the start ¯\_(ツ)_/¯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*G_xdfG0uRkUbv0J08BUmZw.png" /><figcaption>A basic implementation of shading with gamma correction</figcaption></figure><blockquote>Side note: The raw dot product produces light in gamma colour space. You can approximate linear with light = pow(light, 1/2.2). This tends to look much more realistic. If you want a more accurate but slightly more expensive conversion, use light = pow(light, 1/2.4) * 1.055 - 0.055. If performance is a really big concern, you can just use light = sqrt(light) to get a close enough approximation</blockquote><p><strong>Shadows</strong></p><p>Shadows are a bit more complex. To determine whether or not a point is in shadow, you need to cast another ray from the pixel hit point to the light source. If you hit something on the way, then the point is in shadow. If you get to the source of the light (in the case of a point light), or don’t hit anything at all (in the case of a directional light), then the hit surface will be in the light!</p><p>One challenge here is that if you just use the typical ray function to search for shadows, chances are the ray will just hit the surface it is being emitted from and display shadows on a surface that is in the light. This typically results in an annoying noisy shadow. There’s multiple solutions to this issue:</p><ol><li>Add a small amount of the surface normal to the hit position (the shadow ray’s origin). shadowRay.origin = cameraRay.hit.pos + cameraRay.hit.normal * 0.1. While this technically works for most cases, it can cause light leaking and general imprecision. And if you make the coefficient of the added normal really small it will be more accurate but also <em>much</em> more inefficient because there will be a lot of steps taken at both the origin <em>and</em> the hit point.</li><li>The better solution is to divide the distance function’s return value by the current length of the shadow ray, clamped to 1. For example, df/min(rayDepth, 1.0) Think about what this does. When the length of the ray is really tiny, the returned distance is larger and the ray takes a big step away from the surface. Then it can quickly escape the computationally expensive area and once it is past a certain length, it simply progresses as normal. <em>This is also required for soft shadows.</em></li></ol><p>This is the basic implementation of shadows which works in both raytracing and raymarching. Very standard, not very exciting.</p><p><strong>Soft Shadows</strong></p><p>This is where we begin to see some of the amazing benefits of raymarching! In raytracing, the method for determining soft shadows and ambient occlusion is the same; just cast rays in all directions and combine them to get the average amount of light that reaches that area given the environment. In raymarching, ambient occlusion and soft shadows are implemented separately and this allows for the renderer to run in realtime, while producing an incredibly high quality image with far fewer samples, or just one!</p><p>In raymarching, it is a lot easier to get information about the scene. The technique for soft shadows is to keep track of how close a ray gets to hitting a surface. Now the problem with that is that if the ray <em>starts</em> on a surface, it’s just going to always pretend that it almost hit something, no matter where it starts from! For that reason, you need to follow method #2 in the shadows section of this article. Divide the distance function’s return value by the length of the shadow ray. When a ray is emitted from a surface, it will now effectively ignore the surface’s distance.</p><p>The closer the ray comes to hitting something, the darker the shadow should be. This gives us a nice soft shadow like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXb56z2XqLxWFdBKQuDhGA.png" /><figcaption>Soft Shadow</figcaption></figure><p>If you want better efficiency, depending on your situation, you may instead want to use the specific formulas for sphere soft shadows rather than raymarching it, but that’s beyond the scope of this article.</p><blockquote><em>Side note:</em></blockquote><blockquote>If you’re experiencing little flickers of light or outlines on your objects like so, you might want to increase the number of steps each ray is allowed to take</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63B2wQA_wSlNDHu05jNrSg.png" /><figcaption>128 steps</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f50LNIdu5_t0PQMWKEaNJQ.png" /><figcaption>256 steps</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnzuUEFSYkiQpXHEVU_IQA.png" /><figcaption>1024 steps; no more fireflies</figcaption></figure><p><strong>Ambient Occlusion</strong></p><p>Ambient occlusion is yet another thing that is rather difficult and underperforming during raytracing. In raymarching, we are able to just input a point in space and its normal to get the ambient occlusion of that point instantly.</p><blockquote>I’d say, almost every developer has [their] own version of SSAO. In my case, I basically write a new one from scratch for every demo or shot in a demo<br> — Inigo Quilez</blockquote><p>This is actually one part that it’s not too important to understand. One version of ambient occlusion that I implemented was to take a very small frequency normal and compare it with a lower frequency normal using the dot() function. This actually worked decently well and was very cheap, but there are much better methods. I wanted to avoid providing specific code, but here’s the ambient occlusion code I use now.</p><pre>float ao(vec3 ro, vec3 norm, float k)<br>{<br>    float res = 0.0;<br>    float f = 0.1;<br>    for(int i = 1; i&lt;6; i++)<br>    {<br>        vec3 rp = ro + f*float(i)*norm;<br>        res+=(1.0/pow(2.0,float(i)))<br>            *(f*float(i)-DF(rp, false, vec3(0)));    <br>    }<br>    return k*res;<br>}</pre><p>WARNING: If you use this code, you’ll have to clamp and invert the output. Applying it directly to the scene would have some unexpected results.</p><p>DF() is the distance function. Everything else should work as is in Shadertoy.</p><p>One time I hacked together my own ambient occlusion code by sampling the same point’s normal repeatedly, with decreasing precision, and set the ambient occlusion equal to the difference between them. It worked fairly well. Ambient occlusion is very easy with raymarching. I imagine another method would be to use the distance from the scene for every object <em>except</em> for the object you just hit as the ambient occlusion value. (EDIT: I ended up trying it out <a href="https://www.shadertoy.com/view/mt2BRt">here</a>. It could be better, but it has potential to be useful.)</p><p>If you want improved efficiency, depending on your situation, you may instead want to use the specific formulas for sphere, box, and triangle ambient occlusion rather than raymarching them, but that’s beyond the scope of this article.</p><p>Some more useful information: <a href="https://iquilezles.org/articles/multiresaocc/">https://iquilezles.org/articles/multiresaocc/</a></p><p>Now with all the lighting done, your scene might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*a8fQN7DhfzHMzdbMCrrJCg.png" /><figcaption>Not very exciting… yet</figcaption></figure><p>If you wish, you can also adjust the intensity of the shadows. Since all the lighting is now in a single value between 1 and 0, it is quite easy to remap it to adjust the intensity of the shadows. If you remap the light from 0–1 to 0.1–1, it will help the scene look more realistic by accounting for the ambient light.</p><h3>Concept 2: Fog</h3><p>Fog is quite easy to implement. The only data you need to implement fog is the rendered colour of a pixel, and the depth at that pixel. Fog can be applied after almost all of the other rendering, but before post processing.</p><p><strong>Linear fog</strong></p><p>This is the simplest type of fog to implement. For this, all you need is this little bit of code:</p><pre>fog = depth/maxDepth</pre><p>once you have this fog factor, simply interpolate between the original colour of the pixel and the colour of your fog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKvuSu5M7dnbRMZXApGN_g.png" /></figure><p>This works very quickly and is very controllable, but it doesn’t look great.</p><p>You can also try playing around with curves in a graphing software like Desmos and use the fog factor from above to define the fog amount! It’s not realistic, but it works quite well. Below is what I got if I use the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*YPpLh0AvH--t3LwgMDXUvw.png" /><figcaption>Experimenting in Desmos</figcaption></figure><pre>fog = depth/maxDepth;<br>fog = 1.0 + pow(fog-1.0, 3.0);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*NX85i5_GWgGdDNvwy8f5PQ.png" /><figcaption>Cubic fog</figcaption></figure><p>Pow is usually quite slow, so you can make it faster by expanding the code into:</p><pre>fog = 1.0 + (fog-1.0)*(fog-1.0)*(fog-1.0);</pre><p>This results in some inaccurate, but cheap fog which conveniently blocks 100% of the light precisely where the camera frustum ends.</p><p><strong>Exponential fog</strong></p><p>Exponential fog is a bit trickier to implement, but follows the same principle. For the fog factor, instead of a straight line, we get a smooth curve from this formula:</p><pre>fog = 1.0 - pow(2.0, -fogDensity * fogDensity * depth * depth);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hibxo1KhztylK1uqDk1wsg.png" /><figcaption>Proper exponential fog</figcaption></figure><p>The difference in quality from the proper formula is immediately apparent (at least for picky graphics developers like me). This fog gets closer and closer to full fog, but never quite gets there. This one requires a bit more fine tuning, but you get a far nicer result.</p><p>However, even this is still inaccurate. Real fog density changes based on altitude. This can be done with some more complex formulas (which may or may not involve calculus)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXXHMWnfPiLAAOW8FqvY-A.png" /><figcaption>Source: Inigo Quilez</figcaption></figure><p>Fog can also have varying density and move around. This can also be faked quite nicely with the addition of noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*d9T0k1BoTZcpsOEB3Vp_Vg.png" /><figcaption>Source: SimonDev (<a href="https://www.youtube.com/watch?v=k1zGz55EqfU&amp;t=136s">https://www.youtube.com/watch?v=k1zGz55EqfU</a>)</figcaption></figure><p>Real life fog also glows in strong light. For example, fog in front of a light source appears different from fog elsewhere. This can also be simulated fairly easily</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v9pGt5-ImLJLMArfO39OJg.png" /><figcaption>Source: Ingio Quilez</figcaption></figure><p>These concepts are beyond the scope of this article, but I may elaborate on them in the future. For now, here are some very nice resources which explain everything I have shown.</p><p><a href="https://iquilezles.org/articles/fog/">Inigo Quilez</a></p><p><a href="https://www.youtube.com/watch?v=k1zGz55EqfU&amp;t=136s">https://www.youtube.com/watch?v=k1zGz55EqfU</a></p><h3><strong>Concept 3: Assigning object colours</strong></h3><p>Assigning colours to objects is actually not very complicated in theory, but it can be annoying to implement. I will not provide <em>any </em>code<em> </em>at all for this one, because it would only cause more confusion. The following explanation may be confusing too, so feel free to skip ahead.</p><p>The way I do it is to create a global variable for the current material of the pixel, called currentMat, which is a struct containing material data such as colour, roughness, and metallic. Then in the distance function, I have a boolean input called updateMaterial. While marching rays for the raycasts, this boolean input is set to false. After I hit a surface, I call the distance function again, with updateMaterial set to true. This sets currentMat to the material of the closest surface.</p><p>Without this boolean toggle, performance is significantly reduced, since the material is determined hundreds of times along each ray, rather than only once at the end, as is needed.</p><p>As you probably know by now, in order to add an object to a distance function (df), you simply need to return the min of the existing df and the new object’s df. Inside the distance function, I use a variable called minDist to keep track of the smallest distance so far out of all the sub functions. For every sub function (individual object df), I compare minDist to the new object, and keep the smallest value.</p><p>For each material, <em>if</em> the new value of minDist is smaller than before, then I set the value of currentMat to the material I want for the previous object. This way, the same material can be shared among several objects, as long as you set the material afterwards.</p><p>You could also create a tree of min() functions instead of using minDist, but it is very annoying to manage. If you have a very small number of objects that you are managing manually, it may allow you to do fewer material checks, but I still would not recommend it.</p><p><strong>TL;DR: The material can be set based on whichever object is closest to the ray’s hit point.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gl7qXyRaq7m6Me3nuOc21w.png" /><figcaption>Before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95dYNSoq9Tbr88EDGufBaw.png" /><figcaption>After</figcaption></figure><p>Actually using the material is very easy! All you have to do is multiply the light (shading + shadow + ambient occlusion) with the colour of the object.</p><pre>output = colour * light</pre><h3>Concept 4: Reflections</h3><p>The scene currently doesn’t look great. The shading is very flat, and not very interesting. In order to improve it, you can add reflections.</p><p>There are two separate reflections that I will add. One is the reflection of the sun, and the next step is reflections of the environment.</p><p>Phong lighting is a commonly used model for lighting which works quite nicely. This Wikipedia page explains it well: <a href="https://en.wikipedia.org/wiki/Phong_reflection_model">https://en.wikipedia.org/wiki/Phong_reflection_model</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*Fv0neFosDTepueE6aF0VYA.png" /><figcaption>Source: Wikipedia (Link provided above)</figcaption></figure><p>We have already calculated the diffuse component, and the shadow intensity feature functions as the ambient component. All we need now is to calculate the specular reflections, and add them to the image.</p><p>[ WARNING, HACKS INCOMING ]</p><blockquote>While hacks generally should be avoided when trying to create realistic renders, it’s not too critical when it comes to creating simple demo scenes and just learning about the concepts</blockquote><p>The specular component can be calculated by taking the dot product of the reflection vector and the negative light direction. So specular = dot(-lightDir, reflect(incomingVector, surfaceNormal)).</p><p>Provided that the original direction vector is normalized, the reflection vector can be calculated by taking the multiplying the normal with two times the dot product of the normal and original direction vector, and adding that to the original direction. This becomes</p><pre>reflection = dirV + dot(normal, dirV) * 2 * normal</pre><p>An important point to note about specular reflections is that the smoother the object is, the smaller and weaker the specular highlights appear. In order to do this, you can increase the power of the specular value depending on the smoothness of the surface. With a roughness of 0, the specular highlight would be very small, which requires a very large power. With a roughness of 1, then the specular highlight would be the normal size, which requires a power of 1.</p><p>I am not aware of the proper way to do this, and this is a rough approximation of reality anyways. One way to get an appropriate value is to use a reciprocal function (1/x), or a quadratic (x²). The reciprocal function has a risk of division by zero, and can get out of control quite easily, so I used a quadratic formula. Then this returned value is plugged into the power of the specular.</p><p>The roughness value of 1 needs to return 2 (specular¹ looks weird, specular² is best for the smallest value), and a roughness of 0 should return a large number, like 500. (specular⁵⁰⁰ will create a small highlight).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*-jHDBSGRH15JtcpULEkt5w.png" /><figcaption>Desmos is awesome!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*QqGV9qCuXKi29Rs0K3RVmQ.png" /><figcaption>High roughness</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*xjcfxyZW6we0uW-FXOFZtQ.png" /><figcaption>Medium roughness</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*lYq6yVmQKve8nwr_hRfteA.png" /><figcaption>Low roughness</figcaption></figure><p>Now to get reflections of the world around the object, you need to cast a new ray, starting from the point on the surface that was hit, in the direction of the reflection. The ray cast you need is similar to what we did for soft shadows. For rough objects, you might want to randomize the reflection vector a little bit, and maybe take more samples. I will leave the colour management of reflections as an exercise for the reader. There’s too much to cover in this article, and I frankly don’t know the proper way to do it myself. Maybe ask ChatGPT!</p><p>I hope you learned something from this article, and will use raymarching in the future! Raymarching is quite fascinating, because it gives you far more information than rasterization and raytracing, in a single render pass.</p><p>Also, recently some work has been done with neural radiance fields (<a href="https://nvlabs.github.io/instant-ngp/">NeRFs</a>) which allows you to create SDFs (signed distance functions) using a similar technique, for complex shapes, which can then be rendered with raymarching. This rendering technique has become much more popular now than it used to be just a few years ago, and understandably so. What a time to be alive!</p><p>SDFs are very versatile for creating complex 3D scenes, like fractals for example, which are very difficult to do with other methods. You can turn the math into an image directly, as opposed to creating a mesh first. This is incredibly powerful. Raymarching is excellent for efficient real time <a href="https://www.shadertoy.com/view/4slGD4">procedural</a> <a href="https://www.shadertoy.com/view/MdX3Rr">generation</a>, <a href="https://www.shadertoy.com/view/MdfGRr">rendering</a> <a href="https://www.shadertoy.com/view/ltlSWf">complex</a> <a href="https://www.shadertoy.com/view/MlsfR4">dynamic</a> <a href="https://www.shadertoy.com/view/4ds3zn">fractals</a>, and advanced lighting effects, almost for free. With raytracing and rasterizing, the more precision you want, the more it costs. With raymarching, you can render <a href="https://www.shadertoy.com/view/NtSGWG">infinite fields</a> of objects and incredibly <a href="https://www.shadertoy.com/view/Xtt3Wn">detailed</a> <a href="https://www.shadertoy.com/view/4s3SRN">fractals</a> for almost no additional cost. You can also very easily <a href="https://www.shadertoy.com/view/3llfRl">distort objects</a> by tampering with <a href="https://www.shadertoy.com/view/tsBXW3">space-time</a>, which is tricky with other methods. It’s very unique.</p><p>There are several amazing things you can do with raymarching. If you want to see what an expert can do with raymarching, check out this video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBFld4EBO2RE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBFld4EBO2RE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBFld4EBO2RE%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/0589538052f7ae9cea1ba55a4b8ae86f/href">https://medium.com/media/0589538052f7ae9cea1ba55a4b8ae86f/href</a></iframe><p>Inigo Quilez has created this amazing video explaining his process of creating this landscape (below) in detail.</p><p><a href="https://www.shadertoy.com/view/4ttSWf">Shadertoy</a></p><p>He uses some of the features of raymarching mentioned in this article, and a lot of other things as well which I did not cover. To learn more sophisticated techniques, check out his website! <a href="https://iquilezles.org/articles/">https://iquilezles.org/articles/</a> It is the best resource for learning about raymarching, regardless of your skill level.</p><p>This video provides a general intuitive explanation of the concepts covered here, with nicer visuals.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBNZtUB7yhX4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBNZtUB7yhX4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBNZtUB7yhX4%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/97a655ce51866d551632b795b1d054a1/href">https://medium.com/media/97a655ce51866d551632b795b1d054a1/href</a></iframe><p>You may find the code I used to demonstrate the basic concepts <a href="https://www.shadertoy.com/view/ctf3Wf">here</a>.</p><p>Happy coding! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e38aa67e1ef" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/some-interesting-raymarching-concepts-8e38aa67e1ef">Some interesting Raymarching concepts</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Python by building a custom 3D renderer]]></title>
            <link>https://studentsxstudents.com/learning-python-by-building-a-custom-3d-renderer-2c75b21361d0?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c75b21361d0</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[raymarching]]></category>
            <category><![CDATA[enjoy-writing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 15:50:28 GMT</pubDate>
            <atom:updated>2024-03-12T19:39:02.775Z</atom:updated>
            <content:encoded><![CDATA[<p>This article tells the story of my learning experience with both Python, and the concept of raymarching. Python is a well known high level programming language. Raymarching is a unique method of rendering 3D scenes (as well as other dimensions). It is very different from rasterizing and raytracing, which are the traditionally used methods.</p><h4>What is raymarching?</h4><p>Raymarching is a unique method of rendering scenes, which falls somewhere between rasterization and raytracing. Traditionally, rasterization is used for rendering 3D scenes in real-time. Raytracing is usually used for creating photorealistic renders, but is not real-time. With recent advances in technology and some clever coding, raytracing is gradually becoming real-time as well. I will not go into detail about these methods, but they are both very interesting topics to learn about.</p><p>Raymarching is somewhere in between rasterizing and raytracing, and is a fascinating technique. It works by shooting out rays into the scene, like raytracing, but can easily run in real-time, like rasterization. This is due to the fact that unlike common methods, most raymarching programs do not make use of any triangle meshes to represent 3D shapes. Instead, they use mathematical functions known as distance functions. To define a 3D shape for raymarching, all you need is a mathematical formula that can take an arbitrary point in space and return a single floating point value indicating the distance to the closest point on the shape. This allows for fascinating programs that are nearly impossible with polygon based renderers, such as rendering complex, infinitely detailed 3D fractals.</p><p>Raymarching also has many bonus features that you can get for free, such as infinite smoothness (unlike spheres approximated by a triangle mesh for example), ambient occlusion, object glow, and soft shadows. <em>Yes, free soft shadows!</em></p><p>In this article, and future ones, I will not show specific code. I’ll be explaining the general concepts so that they can be understood and implemented in any language at all. It is very important to understand the concepts of raymarching properly in order to make and debug one. If you just want to copy someone else’s code, google it. There are hundreds of examples on <a href="https://www.shadertoy.com/">Shadertoy</a>. I will only be explaining the basic concepts in this article.</p><h4>How does it work?</h4><p>To represent a ray in 3D space, you need a vector for the origin, and a normalized vector for the direction of the ray. To define a point on the ray, you also need a float. A point on the ray would be defined as vec3 p = origin + (dirV * depth).</p><p>In order to “march” the ray forward, you first need to get the distance to the scene, using the distance function, at point p. The distance function for a scene is simply found by returning the minimum of all the individual distance functions. The value of the distance function (I will refer to it as d) means that a sphere of radius d can be placed at the point and not touch anything. You can safely move in all directions in 3D space by d amount and not hit anything.</p><p>Now you can march the ray forward by d, and then do it again for the new ray position. You can do this over and over again until d is smaller than a certain value, and then you will know that you hit something. This method might seem like a lot of work, but it is actually faster than doing lots of square root calculations per pixel like you have to for raytracing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*c2hGVaAljWE4nFxgemrLCA.png" /><figcaption>How distance fields allow you to explore a scene with a direct tradeoff between quality and speed</figcaption></figure><p>Check out this great video for a visual explanation of how it works!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCp5WWtMoeKg%3Fstart%3D79%26feature%3Doembed%26start%3D79&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCp5WWtMoeKg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCp5WWtMoeKg%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/21e3cdb6fd2c769bdb9544cc92447eef/href">https://medium.com/media/21e3cdb6fd2c769bdb9544cc92447eef/href</a></iframe><p><a href="https://www.shadertoy.com/view/wlSGWy">Shadertoy</a></p><p>And here are some nice interactive demos:</p><ul><li><a href="https://www.shadertoy.com/view/lslXD8">Shadertoy</a></li><li><a href="https://www.shadertoy.com/view/ssfSRr">Shadertoy</a></li><li><a href="https://www.shadertoy.com/view/4dKyRz">Shadertoy</a></li></ul><p>and a 3D visualization:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0J8tKGjEE5Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0J8tKGjEE5Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0J8tKGjEE5Q%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/5f9a1e0488a1e9816aa6c5edb1534c32/href">https://medium.com/media/5f9a1e0488a1e9816aa6c5edb1534c32/href</a></iframe><p>There are far more resources on raymarching nowadays than there were just a couple years ago!</p><h4>Distance functions</h4><p>There are a ton of distance functions for various primitives available here: <a href="https://iquilezles.org/articles/distfunctions/">https://iquilezles.org/articles/distfunctions/</a>. This site is an amazing resource for computer graphics.</p><p>It is helpful to understand how exactly these distance functions work, but it is not really necessary to make a raymarcher. All you need to know is that at the surface of an object, the distance function returns 0, and anywhere else in space, it will give you the distance to the nearest point on the surface.</p><p>A sphere is the simplest distance function. It works by calculating the distance from the centre point of the sphere to the given point, and then subtracting the radius of the sphere. So when the distance from the centre point is equal to the radius, the function returns 0, defining the surface of the sphere.</p><p>Other distance functions work in similar ways to define more complex shapes</p><h3>The Code</h3><p>First of all, <strong>raymarching in Python is a terrible idea.</strong> Python is extremely slow, and you won’t be able to get any of the benefits of raymarching unless you use OpenGL or some other graphics library to utilize the GPU. I did not, and my program was incredibly slow. I did this project because I wanted to learn Python by building a complex project that I was familiar with, but I would strongly recommend that you do not use Python.</p><p>If you want to build a raymarching program easily, I would recommend that you use <a href="https://www.shadertoy.com/">Shadertoy</a>, which lets you program fragment shaders. A fragment shader basically defines what single pixel should do, and then that code is run simultaneously for each pixel by the GPU.</p><h4>Python setup</h4><p>I decided that I would only use the bare minimum of libraries. In the end, I only imported math, and pygame to display the render progress. Python doesn’t have any vector variables, so I used tuples to represent vectors and colours. I had to define my own vector operations, such as multiplication, division, addition, subtraction, length, and normalize (multiplication and division functions are in the format vec*vec, so they function as multiplication, division and dot product).</p><p>Then I set up a pygame display, and a loop that would effectively let me write shader code and run it on the CPU, one pixel at a time. I also set up a system that would update the pygame display for every row on the screen that was rendered, and then save the final image.</p><h4>Raymarching</h4><p>Then I followed the steps above. The origin of the ray is the camera position. The direction vector is defined by the x and y coordinates of the screen, with z set to 1 (I’m not rotating the camera). It’s a very simple method to create an unmoving perspective camera.</p><p>I placed a distance function of a Menger sponge in front of the camera, and then output the depth of each ray to the screen in grayscale.</p><p>Once that was working, I added some lighting.</p><h4>Lighting</h4><p>For lighting, there are two things you need: shading and shadows. For shading, you can just take the dot product of the direction of the sun and the normal of the surface that you hit. I did not actually do this for my Python raymarcher (I think; it has been a while since I made it). For shadows, you simply send out another ray towards the light. If you hit something, the pixel is in shadow. If you don’t, then then it’s illuminated. Then you can multiply shadows with shading to combine the two. In raymarching you can get soft shadows very cheaply too, but that’s a subject for a future article.</p><p>You can also get glow for free! It’s possible to use the number of steps you took to define the glow. Another option is to keep track of the closest you get, and then apply glow if you don’t hit anything. The latter only works well when you are only rendering a single object floating in space. The former works everywhere, and has some interesting (maybe more realistic?) effects such as making horizons and flat faces viewed from a tangent glow very brightly.</p><p>Putting all these concepts together, I got this image from my raymarching Python program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*s9CbCZ-oAx85dKGE9t5j7A.png" /><figcaption>Menger sponge; the output of the raymarching program</figcaption></figure><p>And here’s my code for generating this image: <a href="https://replit.com/@01000001/Raymarching">https://replit.com/@01000001/Raymarching</a></p><p>What I have created here is just the beginning of what is possible with raymarching. The possibilities of procedural rendering with raymarching are limitless. I hope you learned something new from this article! If you didn’t, don’t worry; you will learn eventually. Raymarching is a very intimidating subject to get into, but a very rewarding one.</p><p><em>P.S. Please don’t build a raymarcher in Python. It’s unnecessarily difficult and terribly inefficient</em></p><p>If you enjoyed this article, you may also like <a href="https://blog.devgenius.io/some-interesting-raymarching-concepts-8e38aa67e1ef">this one</a>, going more in depth on some more advanced techniques without elaborating on the basics.</p><p>Here are some resources that I found particularly helpful</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCp5WWtMoeKg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCp5WWtMoeKg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCp5WWtMoeKg%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/ddb0514c59f178a0496370b3897cfda7/href">https://medium.com/media/ddb0514c59f178a0496370b3897cfda7/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsvLzmFuSBhk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsvLzmFuSBhk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsvLzmFuSBhk%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/2db30f9834a4f72f26462ee505dccb7f/href">https://medium.com/media/2db30f9834a4f72f26462ee505dccb7f/href</a></iframe><p><em>If you start learning raymarching, eventually this site will be the most useful resource you can find anywhere.</em></p><p><a href="https://iquilezles.org/articles/">Inigo Quilez</a></p><p><strong><em>We’re providing opportunities for the next generation of student thinkers, inventors, and learners, to publish their thoughts, ideas, and innovation through writing.</em></strong><br><em>Our writers span from all areas of topics — from </em><a href="https://studentsxstudents.com/"><em>Growth to Tech, all the way to Future and World</em></a><em>.</em><br><em>So if you feel like you’re about to jump into a rabbit hole of reading these incredible articles, don’t worry, we feel the same way. ;)</em><br><em>That’s why </em><a href="https://studentsxstudents.com/"><em>studentsxstudents</em></a><em> is the place for getting your voice heard!</em><br><em>Sounds interesting? </em><a href="https://studentsxstudents.com/for-students-by-students-becoming-a-contributor-and-expanding-your-impact-f6da9189fa78"><em>Why not join us on this epic journey</em></a>?</p><p><a href="https://studentsxstudents.com/">students x students</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c75b21361d0" width="1" height="1" alt=""><hr><p><a href="https://studentsxstudents.com/learning-python-by-building-a-custom-3d-renderer-2c75b21361d0">Learning Python by building a custom 3D renderer</a> was originally published in <a href="https://studentsxstudents.com/">students x students</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods of impersonating people]]></title>
            <link>https://ahsen35813.medium.com/methods-of-impersonating-people-3a7e1f40f540?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a7e1f40f540</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deepfakes]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Sun, 02 May 2021 18:43:11 GMT</pubDate>
            <atom:updated>2023-06-20T15:47:51.033Z</atom:updated>
            <content:encoded><![CDATA[<p>And how harmful it could potentially be.</p><p>The idea for this article came a few months ago, when I watched <a href="https://www.youtube.com/watch?v=mUfJOQKdtAk&amp;t=124s">this</a> video from Two Minute Papers. I was amazed by how convincing the deepfaked videos were, and immediately realized the terrifying possibilities that this opens up since this is completely free to use for anyone around the world. This model is very powerful and works for way more than just humans too! I felt this was an important issue everybody should know about, so I wrote this short article about a few simple experiments I did.</p><p>Here’s the link to the Google Colab for the first AI algorithm:</p><p><a href="https://colab.research.google.com/github/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb#scrollTo=GCDNKsEGLtR6">Google Colaboratory</a></p><p>The first experiment I did was just with the default sample data. I created this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*3kWLyS964EuzfKeXmtu-_A.gif" /><figcaption>My first experiment with AI and Google Colab</figcaption></figure><p>This was the first time I had ever used Google Colab and also the first time I tried to use this kind of AI algorithm. As you can see, it’s not perfect, but it works astonishingly well considering the only input for the Mona Lisa was an image. It’s far from perfect though; As you can see near the end of the GIF, the Mona Lisa’s face gets distorted when Trump rotates his head.</p><p>It is a very big deal what is going on beneath the hood of this software. It is generating what it thinks the other side of the face looks like, in addition to copying mouth and eye movements with astonishing accuracy.</p><p>You can even animate statues!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CoXWkyKaL3fVJSTGdCGe4Q.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1mjWYIGgXZJyKdL1qa6kAg.gif" /><figcaption>Obama and his statue</figcaption></figure><p>As you can see, the software can recognize features from other things too. Also, a feature of the software is that you can use relative or absolute displacement for the animation. Absolute displacement modifies the features of the image to match the input video exactly, whereas relative displacement maintains the placement of the features relative to their original position.</p><p>In the future, it would be crucial to be able to identify these deepfakes. An important point that you may be able to use to identify these, is the reflection. As you may be able to see, the reflection in the real video is accurate, yet the reflection on the forehead of the statue is treated as just a texture moving with the head. I’m sure that future improved software will be able to fake reflections as well. A recent image inpainting algorithm is able to fake reflections even in mirrors, so accurate reflections in deepfakes are not far off.</p><p>Next, I experimented with a different software, called Wav2Lip. This sofware takes in a video, and an audio file, and it will sync up the video to match whatever is being said in the audio file. This requires a video of the person to animate, but only needs audio for driving the deepfake. A good voice actor could easily create very convincing deepfakes.</p><p>Here’s the code that I used:</p><p><a href="https://colab.research.google.com/drive/1tZpDWXz49W6wDcTprANRGLo2D_EbD5J8?usp=sharing">Google Colaboratory</a></p><p>And here’s what I managed to create:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_n9tL8QaVZI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_n9tL8QaVZI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_n9tL8QaVZI%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/1264bc320bc5c62cff780acb0429af58/href">https://medium.com/media/1264bc320bc5c62cff780acb0429af58/href</a></iframe><p>Deep fake technology is very powerful and must be treated with caution. That concludes this short article, and I hope you found it interesting and helpful.</p><p>P.S. This article was published about 4 months late, and therefore may be very outdated. Deep fake technology has probably advanced a lot more in the past few months.</p><p><strong>2023 Update:</strong></p><p>Now, there’s a <a href="https://www.youtube.com/watch?v=F6HSsVIkqIU">new AI system</a> that has been developed that allows a three second clip of someone’s voice to be used as training, to generate speech from text. Deepfakes now are <a href="https://www.youtube.com/watch?v=iyiOVUbsPcM">indistinguishable from reality</a>. Truly a scary time we live in today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a7e1f40f540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Security Threats of Emails]]></title>
            <link>https://studentsxstudents.com/the-security-threats-of-emails-553488dedfb?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/553488dedfb</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[mailchimp]]></category>
            <category><![CDATA[email]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 16:18:13 GMT</pubDate>
            <atom:updated>2021-03-04T17:36:02.891Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>This article is about the security threats of emails, and what anyone online can find out about you, if they have your email address.</p><p>I recently had a very eye-opening conversation with another person who also uses a mailing service called Mailchimp for their newsletter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sITGVy179ms5tuZ4kznQ7g.png" /><figcaption>My conversation with someone about Mailchimp data</figcaption></figure><p>As you can see, a person who signs up to your newsletter is stored in the Mailchimp database, and their latitude/longitude coordinates are then available to the person that the newsletter belongs to. Of course, after this, I had to try it out myself to find out how dangerous this could really be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzdokKcBMd6dNLnz9iMTeA.png" /><figcaption>Audience page, where you can see your contacts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlgJ16yO7Gc8Bgtd7fn3BQ.png" /></figure><p>The first step was to go to the audience page in Mailchimp, where I can see all my newsletter subscribers and contacts. I clicked “Export Audience” and it created a .zip file for me to download containing a CSV file, which contains data about my contacts.</p><p>This file contained a lot of information! It told me when they first opted into the email, and their IP address when they did so, and also when and where they confirmed their subscription.</p><p>The latitude and longitude coordinates given by the CSV file were quite accurate. My main email’s coordinates were 40 km off, but my other email address was off by just 4 km. Strangely enough, when I inputted the IP address in the CSV file into an online website that finds the coordinates of an IP address, it was accurate to about 500 meters, rather than 40 km.</p><p>At least adding a contact requires a confirmation email before their location and IP address information is added to their profile… right?</p><p>Nope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*qgJfb4moeilHhX6h1f6bxA.png" /></figure><p>All you have to do is click this check box and Mailchimp will <em>not</em> send a confirmation email.</p><p>With this knowledge, I decided to try to hack myself, and behave like an innocent curious person at the receiving end.</p><p>In Mailchimp, it’s incredibly easy to add a new contact. You simply go to the “Add contacts” page and fill out the details. I put just the email address in and left everything else on the default settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbDkqkHDAcSTK_FPXh4f4w.png" /></figure><p>Of course, I clicked the check box “This person gave me permission to email them” because I am pretending to be an illegal, unethical hacker trying to locate someone (myself).</p><p>Making sure to make this experiment as scientific as possible, I re-exported my contact list after every step. First, I checked after adding the contact. Nope, no location info. Then I checked again after sending an email. Still no info. Finally, I opened the email for 3 seconds and then closed it again. When I re-exported my contacts this time, it had the IP address in it! I put that IP address into <a href="https://tools.keycdn.com/geo">this</a>, and it was just 4 km off from my real location.</p><p>My hypothesis was correct! If you send an email to anyone in the world, if they open the email at all while connected to the internet, even if they don’t click anything in the email, their IP address gets sent back to Mailchimp and can be viewed by the person who sent the email.</p><p>Also, an important thing to note. I do not have a paid version of the account, so I couldn’t send an email via the Mailchimp inbox. I instead sent a “test email” of my newsletter to the email address, after adding that email address as a contact. Another loophole in the Mailchimp code!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vlelLV-dFF881-xd.jpg" /></figure><p>In conclusion, the internet is not safe. Nowadays, the simple act of opening an email can reveal your personal information to a hacker, even if you are being cautious to avoid malware. If an email appears suspicious, don’t even open it! If a teenager like me can do this at home with completely free software that anyone can access and use, imagine what real hackers and government can do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553488dedfb" width="1" height="1" alt=""><hr><p><a href="https://studentsxstudents.com/the-security-threats-of-emails-553488dedfb">The Security Threats of Emails</a> was originally published in <a href="https://studentsxstudents.com/">students x students</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monthly Newsletter 09/10/2020]]></title>
            <link>https://ahsen35813.medium.com/monthly-newsletter-09-10-2020-7ea33bda7a3a?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea33bda7a3a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[fusion-360]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Sat, 10 Oct 2020 13:57:36 GMT</pubDate>
            <atom:updated>2020-10-10T17:25:48.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Adventure with Machine Learning #1</h3><p>In this newsletter will be talking about my adventures with creating my first AI algorithm from scratch in Unity3D.</p><p>I had always wanted to create an AI algorithm, but had no idea how they worked. Then, when I saw a video in which the person created an AI robot, which was controlled by an array of numbers. At this, I suddenly had an idea on how I could create my own machine learning algorithm, with the knowledge I had. At this time, I had no idea how neural networks worked, so I decided to start on this project.</p><p>I wanted to create an unsupervised learning algorithm, so that I could let the algorithm teach itself, rather than looking at the output and telling it what it did wrong, every iteration. So I decided to create an agent which would be trained to make its way around a track as fast as possible. I chose this because I knew I could create checkpoints along the track to automatically set the agent’s reward/punishment, and I also wanted a program that could be placed in a different environment and perform similarly well.</p><p>For days, I wrote down small snippets of code that I would need for the algorithm, on paper, whenever I had an idea about it. Soon, I had 3–5 post-it notes on my desk, so I decided to start working on this project.</p><p>First, I modelled the track in Fusion 360, and exported it as a .obj for Unity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Py_X5s5lkahas8haEkhi4g.png" /></figure><p>After that, I created the code for the AI. There are few steps for how the AI works.</p><ol><li>First of all, the main code looks for any saved information of previous AI training. If none is found, the array (named “current”) is defaulted to 0, 0, 0, 0, 0, 0, 0. The first digit in the array is reserved for the agent’s score, and the rest control how it behaves.</li><li>Then, a random one of those numbers is selected, and for one agent (alpha), that digit is increased by the set increment value, and the other agent (beta), has its digit decreased by the increment.</li><li>The two agents then go through the track, and are rewarded depending on how many checkpoints they go through, and punished if they go through checkpoints backwards (I used a function called Vector3.dot to figure out the side of the checkpoint the player was on).</li><li>After 20 seconds, the agent with the lower score is deleted and the “current” array is set to the controller array of the agent with the higher score.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJyVzDqAfSHzcfF468SMKw.png" /><figcaption>Alpha agent on the right, Beta agent on the left</figcaption></figure><p>This worked, and I was happy with how it turned out. The agents gradually got better at going around the track, but I noticed a tendency to only turn right (The agents start at the short straight bit of the track, and go clockwise). As I had previously hoped to later test the agents on different tracks, I tried to fix this issue. I moved the starting point to a different place on the track where the first turn is a left turn, but this reduced the performance of the agents. I eventually gave up on this, and it continued to be an issue. However, as you will see later, this tendency to turn right did not prevent the agents from successfully making a left turn!</p><p>I wasn’t satisfied with this track, and I wanted something different. I didn’t want to create a new track in Fusion 360 and then place the checkpoints manually, every time I wanted to try something new, so I chose to use <a href="https://assetstore.unity.com/packages/tools/utilities/b-zier-path-creator-136082#description">Sebastian Lague’s Bézier Path Creator</a> tool to place small units of track, each with a checkpoint, along a path to form a track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0KdOQgO4n343qxq54GW6Q.png" /><figcaption>Bézier Path Creator asset on the Unity Asset Store by Sebastian Lague</figcaption></figure><p>This worked perfectly for my needs, as you can see here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1DUFVBYipBOr2Lpg1dyHg.png" /><figcaption>A track created using Bézier Path placement</figcaption></figure><p>The walls of the track are a little bit rough, because I used boxes for the walls of the units. I wanted to keep the visual and collider geometry as simple as possible since it was going to be copied into the world hundreds of times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfTF3lxx3nFEaCfLYuXvpA.png" /><figcaption>One track unit. Green lines signify the outline of a collision box</figcaption></figure><p>After playing around with this for a bit, I decided on a track design, and then let the algorithm run. It was better than I was hoping for!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYyNgw5JrRQA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYyNgw5JrRQA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYyNgw5JrRQA%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/a21b1d7f1c215ea097b68e47291e3b1f/href">https://medium.com/media/a21b1d7f1c215ea097b68e47291e3b1f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3c1UMZVNxbg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3c1UMZVNxbg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3c1UMZVNxbg%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/77e3ce1e8071562fa0f96ada34ac4287/href">https://medium.com/media/77e3ce1e8071562fa0f96ada34ac4287/href</a></iframe><p>The above video demonstrates the AI’s performance, after 130 iterations of training.</p><p>Interesting behaviour I noticed:</p><ul><li>The AI seemed to not like turning left. Instead, it figured out a way to turn left by spinning right! I found this very interesting, because the AI only ended up using three of its 6 inputs properly. The weights for the other inputs were 0 or almost 0.</li><li>The green rays allow the AI to shift left or right, without turning (my intention was to give the AI some way to centre itself on the track). At one point in the training, the algorithm figured out how to exploit this feature to get an extra boost off the wall.</li></ul><p>This project was very interesting, and I enjoyed the process, including all the problem solving. It was defenitely worth it to see the program figure out how to navigate a track on its own!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*rYGD_7ck0mvwwUeD7nbf5Q.gif" /><figcaption>A full lap</figcaption></figure><p>For next time:</p><ul><li>I will try to have more agents for faster and more accurate learning.</li><li>I will experiment with a more optimized method of generating the track, such as removing the floor pieces of the units.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea33bda7a3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nanosensors]]></title>
            <link>https://ahsen35813.medium.com/nanosensors-11235813-39333fdd4c13?source=rss-d4b61cc81dbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/39333fdd4c13</guid>
            <category><![CDATA[nanosensors]]></category>
            <category><![CDATA[nanotechnology]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ahsen Khan]]></dc:creator>
            <pubDate>Sun, 08 Mar 2020 20:19:27 GMT</pubDate>
            <atom:updated>2020-03-09T18:55:52.929Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>A microscopically small technology making a big impact</h4><p>Nanosensors are a good example of a useful nanotechnology. It is already being used in important fields such as medicine, water distribution, agriculture, the food industry, the military, and more. Nanosensors are tiny sensors which are able to measure temperature at the nanoscale (for example, the temperature of individual cells), detect the presence of certain substances or bacteria, and measure tiny amounts of electromagnetic radiation. Nanosensors are usually sensors with at least one of their dimensions around 100 nanometers. In comparison, a human hair is usually between 50,000 and 100,000 nanometres thick. Nanosensors are not necessarily microscopic, but they observe something that is at the nanoscale.</p><h4>Why they’re important</h4><p>Nanosensors can detect much smaller changes and can detect particles and temperature changes that other technologies cannot. They can measure things at the scale of individual cells and even molecules.</p><figure><img alt="A picture of a nanosensor" src="https://cdn-images-1.medium.com/max/600/1*dg6MOfHM2xr-XwrKNefdlQ.jpeg" /><figcaption>An example of a nanosensor</figcaption></figure><ul><li>Nanosensors can detect <strong>much smaller changes</strong></li><li>Nanosensors have <strong>less impact</strong> on the thing being measured</li><li>They are <strong>faster</strong> to detect things.</li><li>They are much <strong>smaller</strong> and can fit into smaller spaces and/or get closer to the subject for <strong>higher accuracy</strong>.</li><li><strong>Low power consumption</strong> due to their small size</li></ul><h4>Applications of nanosensors</h4><p>There are a lot of different nanosensors which can do different things under different conditions. Although it may seem unlikely, there are a lot of applications for nanosensors in various different fields.</p><ul><li>Nanosensors are being developed to detect early signs of cancer and many of them have already been quite successful</li><li>Nanosensors can be used in water treatment facilities to monitor the quality of their water in real time</li><li>Nanosensors can be used to monitor nutrient quality and moisture of soil for plants in agriculture</li><li>They can also evaluate the quality of food</li><li>Nanosensors can be used by security at airports to detect explosives or toxic chemicals</li><li>Nanosensors in hospitals could be used to check for bacteria and contamination</li></ul><p>As you can see here, nanosensors are already being used in surprisingly important places which you might not have expected, such as cancer detection and security.</p><h4>A possible application to current problems</h4><p>In researching nanotechnology, I realized that nanosensors could also be used to detect COVID-19 quickly. This could be applied to public spaces, to be able to check where it is necessary to clean, and also could be used at airports and borders to quickly check if anyone has the virus. This could speed up the process for doctors to check patients for COVID-19, and could even be affordable enough for people to check at home so that they know if they need to go to the hospital. Either a carbon nanotube nanosensor or a nanocantilever could work for this application.</p><h4>How they work</h4><p>There are a few different types of nanosensors which work in slightly different ways.</p><ul><li>One type of nanosensor uses <strong>semiconductor nanowires</strong>. When a certain molecule of a substance bonds to it, its conductivity changes, which can be measured. The change in conductivity depends on the substance bonding to the nanowire. If for example, nitrogen dioxide gas lands on the sensor, the conductivity is decreased, whereas if carbon monoxide lands on the sensor, the conductivity in increased. This way, nanosensors can be calibrated to identify individual molecules of substances in the air for example.</li></ul><figure><img alt="2 Carbon Nanotubes On A Human Hair" src="https://cdn-images-1.medium.com/max/602/1*zlRT98eevJzHXDn8vUv4yA.jpeg" /><figcaption>2 Carbon Nanotubes on a Human Hair</figcaption></figure><ul><li>Another type of nanosensor uses <strong>carbon nanotubes</strong>. Similar to above, their conductivity changes depending on the molecule that bonds to it, which can be measured.</li><li>This type of carbon nanotube sensor can also be used to detect <strong>bacteria and viruses</strong>. An antibody is attached to the nanotube, and when the corresponding bacteria or virus bonds to the nanotube, the conductivity changes and can be measured. Scientists believe this could be very effective for detecting bacteria in hospital environments.</li><li><strong>Nanocantilevers</strong> are another type of nanosensor being developed to detect <strong>individual molecules</strong>. The nanocantilever oscillates at its resonant frequency, so when a particle lands on it, its weight and therefore its resonant frequency changes and this can be measured. It can be coated in antibodies to bond only to specific bacteria and viruses as well for detecting bacteria.</li></ul><figure><img alt="An example of nanocantilevers" src="https://cdn-images-1.medium.com/max/800/1*4nRDj8retYPUCFwv6eJbIQ.jpeg" /><figcaption>An example of some nanocantilevers</figcaption></figure><ul><li><strong>Nano thermometers</strong> are yet another type of nanosensor. These are molecules which fluoresce for a certain period of time, depending on the temperature in a high viscosity environment like inside a cell. These “nano thermometers” are so small that they can be used to measure the temperature of <strong>individual cells</strong>!</li></ul><p>As you can see here, there are a lot of different types of nanosensors. which can detect and measure a wide range of different things. All of these sensors are very tiny and are capable of measuring things at the nanoscale. Scientists are constantly developing new types of nanosensors, and making the current ones more efficient, more sensitive, and cheaper.</p><h4>How nanosensors are built (nanofabrication)</h4><p>There are three main ways currently to make nanosensors. These include top-down, bottom-up, and self-assembly. Each method has its own benefits and drawbacks.</p><ul><li>The <strong>top-down</strong><em> </em>method involves starting with a larger portion of solid material and etching out the nanosensor. This is similar to how a CNC machine works. It starts with a solid block of material and cuts away the parts which are not required.</li><li>The <strong>bottom-up</strong> method involves assembling the nanosensor, piece by piece, with individual atoms and molecules. This is very similar to how a 3D printer works, by placing down material where it is required to gradually form the desired object.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*jUUpGPYRIafS9q3_zU1NIg.png" /><figcaption>Top-Down vs. Bottom-Up Nanofabrication</figcaption></figure><ul><li>On of the most effective methods however, is the <strong>self-assembly</strong> method. This uses a few pre-assembled parts such as molecules which then automatically assemble themselves into a nanosensor very quickly and cheaply. The pre-assembled parts are usually made with the bottom up method.</li></ul><h4>The problems with nanofabrication</h4><p>All these methods for creating nanosensors are great, but there are many problems. Both the top-down and bottom-up methods are difficult to use to mass produce nanosensors. The bottom-up method is very time consuming and expensive, requiring extremely precise tools. The top-down method is a bit cheaper but not as precise.</p><h4>Potential Ideas to improve nanofabrication</h4><p>The self-assembly method is currently a much more efficient method. It can be used to produce large numbers of nanosensors quickly. Another potential way to improve nanofabrication could also be to combine the top-down and bottom-up processes. If you were to carve a rough shape with the top-down method (which is cheaper), then the bottom-up method can be used to add the finer details on top (minimizing the amount of work needed by the bottom-up method, which is more expensive). This can be compared to carving out a rough shape of a model from clay, and then refining the model by adding more bits of clay where needed. This is often the most efficient way in the case of clay, so this could possibly work for nanofabrication too. This would both keep the cost lower, but keep all the tiny details required for nanosensors.</p><p>I hope you enjoyed this article, and thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39333fdd4c13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>