<?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 Simon Trushkin on Medium]]></title>
        <description><![CDATA[Stories by Simon Trushkin on Medium]]></description>
        <link>https://medium.com/@trushkinsimon?source=rss-0cb2fe441de9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*X3p6ee1Z2CcChFz6</url>
            <title>Stories by Simon Trushkin on Medium</title>
            <link>https://medium.com/@trushkinsimon?source=rss-0cb2fe441de9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:21:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trushkinsimon/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[Semi-Procedural landscape with BabylonJS]]></title>
            <link>https://medium.com/@trushkinsimon/semi-procedural-landscape-with-babylonjs-e9373bc3091d?source=rss-0cb2fe441de9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9373bc3091d</guid>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[babylonjs]]></category>
            <dc:creator><![CDATA[Simon Trushkin]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 22:17:06 GMT</pubDate>
            <atom:updated>2024-11-05T22:17:06.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qeAaqtxqQ7SC2eprGUDwJg.png" /></figure><p>In this article, I will share methods and techniques for generating infinite terrain using texture masks, without complex noise or other operations that require significant device resources. This approach will allow for impressive visual results while freeing up resources for other content in the scene.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwjJQjU-F770%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwjJQjU-F770&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwjJQjU-F770%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/0a8397fe6cbaf42cb70772fe0c5d88b1/href">https://medium.com/media/0a8397fe6cbaf42cb70772fe0c5d88b1/href</a></iframe><p>The method is based on four important stages, which we will go through one by one.</p><ul><li>Develop a base for the landscape (optional). The initial mesh.</li><li>Make the landscape move along with the user.</li><li>Create a material that will define the relief and appearance of the landscape (by relief, we mean changes in landscape elevation depending on the user’s position).</li><li>Solve the issue of physical interaction between the landscape and the user.</li></ul><p>If you’re ready, put on your spacesuits — we’re heading to Mars!</p><h4>Canvas</h4><p>Even though we are creating a semi-procedural landscape, we will not be generating geometry in real-time near the user, as this requires significant computational resources, not to mention implementation complexity. Instead, we will use a pre-prepared template, which can be created in Blender or any other 3D editor of your choice. There are several options that may suit your case, varying in implementation complexity and final result.</p><p><strong>Option 1: Cutting corners!</strong></p><p>Let’s create a basic mesh in BabylonJS using theMeshBuilder.CreateGround function. We’ll pass the name, properties, and scene into the function. The properties can vary depending on your needs, for example:</p><pre>let ground = BABYLON.MeshBuilder.CreateGround(<br>  &quot;ground&quot;, {<br>    subdivisions:subdivisions,<br>    width: dimensions,<br>    height: dimensions<br>}, scene);</pre><p>The simplicity of this approach is very appealing — you can implement it in just one minute!</p><p>However, this solution won’t allow you to create LODs (Levels of Detail) for the landscape or to cull the invisible geometry behind the user.</p><p>The LOD mechanisms, which I’ll describe later, cannot be applied in this case, so this solution is suitable for scenes where the user moves within a very limited field of view (for example, dense fog) or where there are no strict requirements for geometry detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*4KYP7nBGJvT_hrWxZGL--g.png" /><figcaption>Example of a mesh in the first approach to creating geometry.</figcaption></figure><p><strong>Option 2: Compromise</strong></p><p>Let’s create a canvas for the landscape in a 3D editor. This approach opens up many more possibilities. I’ve highlighted two options when using a 3D editor.</p><p>The first option, which supports LODs, is a square grid with decreasing detail as it approaches the edges of the geometry.</p><p>You need to create a plane and increase the polygon count as you get closer to the “center” — the point where the camera will be located. Both the size and the number of detail levels (LODs) are set by you. Experiment to achieve the best result for your case!</p><p>You can determine a suitable configuration empirically.</p><p>Choose a geometry step. Use the cell size of one of the LODs as the step (we only need one step, not one for each LOD). This value will be needed later when we move the landscape along with the user. It’s convenient to use the cell size of the 3rd or 4th LOD. For smooth functioning without glitches, choose the cell sizes of the lower LODs so that the side of the smaller cell divides evenly into the side of the larger cell.</p><p>For example, if the cell size in LOD0 is 5cm x 5cm, then the LOD1 size should be 10 x 10 or 15 x 15, and the LOD2 size should be 20 x 20 or 30 x 30, respectively. For distant LODs, this rule can be ignored, as shaking won’t be noticeable due to the large distance.</p><p>On distant LODs, where cell sizes are significantly larger, the impact of cell size selection becomes less noticeable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*q_L97ylV5dK3_tc5dqCLAQ.png" /><figcaption>Example of a mesh in the second approach to creating geometry.</figcaption></figure><p><strong>Option 3: Speed</strong></p><p>For the third option, we’ll trim the invisible part of the mesh. This will reduce the polygon count, increasing performance and reducing the file size.</p><p>In this option, we’ll need to abandon the rectangular grid and use a grid of equilateral triangles instead.</p><p>Why use equilateral triangles? Since we want to trim the geometry that the user cannot see, we’ll need to rotate it. An equilateral triangle is very convenient for this because, at a 60° angle, it allows a wide enough field of view where points will always align with the coordinates of the previous step when the landscape shifts due to rotation (the rotation occurs in 60° increments). This eliminates terrain jitter caused by height changes at points due to potential misalignment of coordinates between steps.</p><p>Steps for constructing such geometry in the illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bAtJrMP91K8g2uuqskyFA.png" /><figcaption>Steps for constructing the geometry</figcaption></figure><ol><li>First, create a regular hexagon. This can be done using a circle primitive. Delete the face without removing the vertices, extrude them, and merge the extruded vertices at the center so that you end up with 6 triangles.</li><li>Delete the top 3 triangles.</li><li>Subdivide the surface a few times so that its detail level matches the last LOD.</li><li>Then, select the area that should correspond to the previous LOD and subdivide it the required number of times.</li><li>Repeat this process as many times as needed to create the desired number of LODs.</li><li>Create 2 planes that match the FOV you plan to use (ensuring that when the surface rotates 60 degrees relative to the user, it remains in view).</li><li>Extrude these planes to form 2 “boxes.”</li><li>Use a Boolean modifier to trim the surface.</li><li>Shift the surface slightly back (behind the user) so that when the user looks down, there is always surface beneath their feet.</li></ol><p>Experiment with the number of LODs, the step between them, angles, and other parameters to achieve a suitable version.</p><p>In this case, we’ll need to select 2 steps, as the size of the equilateral triangle is not the same along both axes; the height of an equilateral triangle is greater than its side length.</p><p><strong>Option 4: Hardcore</strong></p><p>In hardcore mode, I suggest generating the terrain using the principles described in options 2 and 3 through code. The advantage of this method is that you don’t need to load geometry into the scene, which significantly increases loading speed. However, creating such an algorithm is a complex task. Additionally, since we’re working in a browser, almost always in a single thread, it’s usually preferable to favor memory over CPU and reduce computational load.</p><p>Now that we have our canvas, let’s move forward.</p><h3>Let’s get the canvas moving!</h3><p>The next step is to make the created mesh move along with the user so that it follows us wherever we go. It will act as a sort of canvas on which we’ll project the terrain.</p><p>For the simplest option (“Cutting corners”), the implementation is easy:</p><pre>const stepX = 0.1;<br>const stepZ = 0.1;<br><br><br>scene.onBeforeRenderObservable.add(()=&gt;{<br>  ground.position.x = Math.round(camera.position.x/stepX)*stepX;<br>  ground.position.z = Math.round(camera.position.z/stepZ)*stepZ;<br>})</pre><p>Here, stepX and stepZ are the cell sizes. In the case of the simple geometry option, the steps will be the same.</p><p>A<strong> </strong><a href="https://www.babylonjs-playground.com/#RSYE1Q"><strong>Playground</strong></a> with an example of the simplest implementation.</p><p>For the “Compromise” option, you can use the same logic. However, remember to be more careful in choosing the cell size!</p><p>For the option where the surface rotates along with the user, we need to use different steps for X and Z, so be sure to calculate them accordingly. We’ll also use a multiplier so that, when switching steps, the surface moves a sufficient distance, making the transition seamless for both near and far parts of the landscape. You’ll need to determine the step and multiplier yourself based on the geometry you’ve prepared.</p><p>In my case, the multiplier was such that with each step, the surface moved by 64 sides of the triangle in the first LOD. By using the multiplier, you can reduce the frequency of steps, minimizing the distraction caused by the seam between LOD 0 and LOD 1, as it won’t happen too often.</p><p>Offset with a step of size surfaceStepX:</p><pre>const cameraPosX = this.scene.activeCamera!.globalPosition.x;<br>const roundedPosX = Math.round(<br>  cameraPosX/this.surfaceStepX<br>);<br>model.rootNode.position.x = roundedPosX*this.surfaceStepX;</pre><p>Offset with a step of size surfaceStepZ:</p><pre>const cameraPosZ = this.scene.activeCamera!.globalPosition.z;<br>const roundedPosZ = Math.round(<br>  cameraPosZ/this.surfaceStepZ<br>);<br>model.rootNode.position.z = roundedPosZ*this.surfaceStepZ||0;</pre><p>We also need to add rotation:</p><pre>const rotationY = this.scene.activeCamera!.absoluteRotation.toEulerAngles().y;<br>const snapAngle = Math.PI / 3;<br>model.rootNode.rotation.y = Math.round(rotationY / snapAngle) * snapAngle;</pre><p>Now we have a canvas that moves with the user, onto which we’ll apply the terrain surface.</p><p>Let’s proceed with creating the materials.</p><h3>Time to pick up the brush.</h3><p>To create the surface material, I’ll be using <a href="https://nodematerial-editor.babylonjs.com/">BabylonJS NodeMaterial</a>, as it’s a very convenient tool that offers extensive flexibility.</p><p>We need to create a base relief. This is simply a black-and-white texture that will define the roughest and most prominent features of the terrain (mountains, ravines, and other large relief elements). I used a precomputed procedural noise texture. You can use something similar or relief data generated in external software or actual height maps. Once we’ve chosen the texture to work with, we can move on to the material editor.</p><p>To project the relief onto the canvas, we need to bind the relief texture to world coordinates and then adjust the surface geometry based on this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bteqmaVMwgK1PRq_" /></figure><p><strong>Frame 1:</strong></p><p>We obtain global coordinates and then convert them into texture coordinates using a remap block. This way, the texture will project onto an area sized -500 to 500. In your case, these values may be different, as it’s specific to each setup.</p><p><strong>Frame 2:</strong></p><p>Next, we adjust the texture contrast and set the strength with which our texture affects the relief using the same remap block. If the output from the texture ranges from 0 to 1 and the relief fluctuates by only a meter, the remap operation amplifies these fluctuations, perhaps from -32 to 32.</p><p><strong>Frame 3:</strong></p><p>We then add the Y-value data from the texture to the current Y-value of the geometry. At this stage, you may already have enough detail in your relief for your needs. But we’ll go further — otherwise, why would we need LODs for the canvas? 😄</p><p>The base relief is created. Now let’s add more detail!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uS5t4IPevK81tQT-dk_iAQ.png" /></figure><p><strong>Frame 1 and 2:</strong></p><p>Simply create the textures. Don’t forget to set higher values for the <em>u</em> and <em>v</em> scale in sourceTexture if needed. In my case, I set it to 128.</p><p><strong>Frame 3:</strong></p><p>This is a mask for different texture zones. For instance, we don’t want the stone relief to apply in areas with sand. Therefore, the texture in frame 3 serves as a kind of router to distribute textures (both color textures and relief textures). It has several color channels that serve for zoning.</p><p><strong>Frame 4:</strong></p><p>Used to increase or decrease the contrast in parts of the mask for stone and cliff relief.</p><p><strong>Frame 5:</strong></p><p>Gradients control the influence of the stone textures and relief on the overall terrain.</p><p><strong>Frame 6:</strong></p><p>Multiplication blocks remove stones or cliffs where they shouldn’t appear, according to the mask channel.</p><p><strong>Frame 7:</strong></p><p>Blocks of addition add the elevated details of the relief to the main terrain.</p><p>Use a similar approach with a color mask to define the correct texture for each zone.</p><p>The main material for the canvas is ready! You can add an ImageProcessingNode or FogNode if needed. You could even create a PBR block to add shadows or effects like dust. In my version, I made a dust effect using SimplexPerlin3D that changes over time. A <a href="https://www.babylonjs-playground.com/#RSYE1Q#3">Playground</a> with a simple material implementation.</p><p>I also recommend darkening deep ravines for a more realistic look.</p><p>If there’s a sun in your scene, you can bake shadows into the textures and make them seamless, then blend them with the shadow from the character or active objects. This will help you save a significant amount of computing resources.</p><p><strong>Attention!</strong><br>Be cautious when selecting resolutions for relief textures, as this greatly impacts performance. Setting high-resolution textures doesn’t always improve image quality, but it will definitely degrade performance. Pay special attention to this if you need support for mobile devices or VR headsets. For such devices, it’s best to create a lighter version of both the canvas geometry and the material.</p><h3>Colliding.</h3><p>Now we have the terrain, and it moves with us. The next task is to enable movement across this surface with collision detection. Since the terrain geometry is modified in the shader, we can’t simply enable <em>check collisions</em> because we lack information about the geometry points altered in the VertexShader. Therefore, we’ll need to create a small piece of geometry directly under the user that will have simplified terrain geometry and move along with the user. Essentially, we need to implement a second “canvas” whose terrain will be modified not by the shader but directly through VertexData.</p><p>To begin, let’s create a mesh for the collider.</p><pre>let mesh = MeshBuilder.CreateGround(&#39;collider&#39;,{width:1,height:1, subdivisions:1, updatable: true}, this.scene);<br>mesh.isVisible = false;<br>mesh.checkCollisions = true;</pre><p>Note: During debugging, if the collider mesh suddenly disappears, set its property alwaysSelectAsActiveMesh to true.</p><p>Now, let’s load the primary relief texture (the same one we used in the material).</p><pre>const texture = new Texture(&#39;yourURL&#39;,this.scene);</pre><p>And let’s add an event listener for the texture loading.</p><pre>texture.onLoadObservable.addOnce(()=&gt;{<br>})</pre><p>When the texture loading event is triggered, we’ll proceed as follows. First, let’s read the texture pixels. This can be done quite easily:</p><pre>texture.readPixels()</pre><p>The function is asynchronous, so don’t forget to use await or .then. The code described below should be executed after the readPixels operation completes.</p><p>Once we have the texture pixels, place them into a regular number[] array for easier handling.</p><p>Now, let’s make the collider move along with us.</p><pre>this.scene.onBeforeRenderObservable.add(()=&gt;{<br>  mesh.position.x = Math.round(camera!.globalPosition.x);<br>  mesh.position.z = Math.round(camera!.globalPosition.z);<br>})</pre><p>The collider needs to be positioned directly under the camera. With a collider size of 1 meter, we should round the camera’s position to the nearest appropriate value to position it correctly.</p><p>Now that we have a movable collider, we need to set its elevations and depressions to match those of the main terrain.</p><p>For each point in the geometry, find the corresponding pixel, which will indicate how much to raise or lower that specific point.</p><p>To do this, we first need to retrieve the geometry data of the collider mesh.</p><pre><br>this.scene.onBeforeRenderObservable.add(()=&gt;{<br>  mesh.position.x =Math.round(<br>    camera!.globalPosition.x/this.colliderStep<br>  )*this.colliderStep||0;<br><br>  mesh.position.z =Math.round(<br>    camera!.globalPosition.z/this.colliderStep<br>  )*this.colliderStep||0;<br><br>  const positions = mesh.getVerticesData(VertexBuffer.PositionKind)!;<br>  const numberOfVertices = positions.length/3;<br>})</pre><p>Now, let’s iterate through the points and apply the necessary transformations.</p><pre>this.scene.onBeforeRenderObservable.add(()=&gt;{<br>  mesh.position.x = Math.round(<br>    camera!.globalPosition.x/this.colliderStep<br>  )*this.colliderStep||0;<br><br>  mesh.position.z = Math.round(<br>    camera!.globalPosition.z/this.colliderStep<br>  )*this.colliderStep||0;<br><br>  const positions = mesh.getVerticesData(VertexBuffer.PositionKind)!;<br>  const numberOfVertices = positions.length/3;<br>  <br>  for(let i=0;i&lt;numberOfVertices;i++){<br>      let px = this.findPixel(<br>          numberArray,<br>          textureSize,<br>          groundSize,<br>          positions[i*3]+mesh.position.x,<br>          positions[i*3+2]+mesh.position.z<br>      );<br>  <br>      const normalizedPixelValue = ScalarMath.Map(px[0],0,255,0,1);<br>  <br>      positions [i*3+1] = ScalarMath.Map(<br>          normalizedPixelValue,<br>          0,<br>          1,<br>          -elevationMin,<br>          elevationMax<br>      );<br>  }<br>  mesh.updateVerticesData(VertexBuffer.PositionKind,positions);<br>  mesh.refreshBoundingInfo();<br>})</pre><p>Let’s look at the findPixel function. Its purpose is to find the pixel on the texture that corresponds to the provided geometry point. Since calling readPixel gives us raw texture values without interpolation, the transitions between pixels will be abrupt, creating a kind of stepping effect. This would make movement across the surface a less pleasant experience.</p><p>Therefore, in the findPixel function, besides locating the needed pixel, we’ll also perform linear interpolation to smooth out the steps and create a smoother movement experience.</p><pre>protected findPixel(<br>    textureData: number[],<br>    textureSize: number,<br>    planeSize: number,<br>    x: number,<br>    y: number<br>): number[] {<br>    // Convert coordinates to texture space<br>    let xCrd = ScalarMath.Map(x, -planeSize, planeSize, 0, textureSize);<br>    let yCrd = ScalarMath.Map(y, -planeSize, planeSize, 0, textureSize);<br><br>    // Determine integer and fractional parts for linear interpolation<br>    const x0 = Math.floor(xCrd);<br>    const y0 = Math.floor(yCrd);<br>    const dx = xCrd - x0;<br>    const dy = yCrd - y0;<br><br>    // Function to get pixel color, considering array boundaries<br>    const getPixel = (x: number, y: number): number[] =&gt; {<br>        const clampedX = Math.max(0, Math.min(textureSize - 1, x));<br>        const clampedY = Math.max(0, Math.min(textureSize - 1, y));<br>        const index = (clampedY * textureSize + clampedX) * 4;<br>        return textureData.slice(index, index + 4);<br>    };<br><br>    // Get color values for neighboring pixels<br>    const topLeft = getPixel(x0, y0);<br>    const topRight = getPixel(x0 + 1, y0);<br>    const bottomLeft = getPixel(x0, y0 + 1);<br>    const bottomRight = getPixel(x0 + 1, y0 + 1);<br><br>    // Linear interpolation<br>    const interpolate = (a: number[], b: number[], t: number) =&gt;<br>        a.map((v, i) =&gt; v * (1 - t) + b[i] * t);<br><br>    // Interpolate by x between top and bottom pixels<br>    const top = interpolate(topLeft, topRight, dx);<br>    const bottom = interpolate(bottomLeft, bottomRight, dx);<br><br>    // Interpolate by y between the results<br>    const result = interpolate(top, bottom, dy);<br><br>    // Round values to get integer results<br>    return result.map(value =&gt; Math.round(value));<br>}</pre><h3>Conclusion:</h3><p>This is one of the methods for generating semi-procedural landscapes. We explored several approaches to creating the canvas geometry, each varying in implementation complexity and quality. We implemented canvas movement along with the user, eliminating terrain jitter and avoiding geometry recalculation. We created a material that defines the relief and appearance of the canvas. Finally, we successfully solved the challenge of creating a collider that allows smooth movement across this terrain!</p><p>🎉🎉🎉</p><p>That’s it! Now you can experiment and add various objects to your scene. Include sounds to bring the atmosphere to life. Immerse users in your worlds, creating an unforgettable experience.</p><p>Feel free to ask questions or suggest improvements — I’d love to hear your thoughts! You can find more <a href="https://www.linkedin.com/feed/update/urn:li:activity:7174051994410569729/">articles</a> and our Web3D <a href="https://www.linkedin.com/company/clickon3d">projects</a> on my LinkedIn.</p><p>Thanks!</p><p>Live Demo: <a href="https://demo.do.clickon.pro/mars/">https://demo.do.clickon.pro/mars/</a></p><p><a href="https://forum.babylonjs.com/u/simon/summary">I’m on forum</a></p><p><a href="https://www.linkedin.com/in/simon-trushkin/">My page at LinkedIN</a></p><p><strong>Simon Trushkin — Senior Technical Artist, ClickON</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9373bc3091d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>