Having trouble deciphering the logic behind my bug detection process in the Three.js Verlet Cloth Simulation on GPU

I'm facing difficulty grasping the logic I am working on with Three.js and the GPUComputationRenderer developed by yomboprime.

(https://github.com/yomboprime/GPGPU-threejs-demos/blob/gh-pages/js/GPUComputationRenderer.js)

My goal is to create a simple Verlet Cloth Simulation. So far, here is the logic that I have managed to implement (summarized):

1) Position-Fragment-Shader: This shader utilizes the old and current position texture to calculate the new position as shown below:

vec3 position = texture2D( texturePosition, uv ).xyz;
vec3 oldPosition = texture2D( textureOldPosition, uv ).xyz;
position =  (position * 2.0 - oldPosition + acceleration * delta *delta )

t = checkConstraints(position);
position += t;
gl_FragColor = vec4(position,1);

2) Old-Position-Shader: This shader simply stores the current position for the next step.

vec3 position = texture2D( texturePosition, uv ).xyz;
gl_FragColor = vec4(position,1);

While this setup works well, it restricts the ability to compute constraints more than once in a single step since each vertex is processed independently without considering the positional changes of other vertices in the first iteration.

What I aim to achieve is separating the constraint calculations from the verlet computation. Currently, the approach looks something like this:

1) Position-Shader (texturePosition)

vec3 position = texture2D( textureConstraints, uv ).xyz;
vec3 oldPosition = texture2D( textureOldPosition, uv ).xyz;

position =  (position * 2.0 - oldPosition + acceleration * delta *delta );
gl_FragColor = vec4(position, 1 );

2) Constraint-Shader (textureConstraints)

vec3 position = texture2D( texturePosition, uv ).xyz;

t = checkConstraints(position);
    position += t;
gl_FragColor = vec4(position,1);

3) Old-Position-Shader (textureOldPosition)

vec3 position = texture2D( textureConstraints, uv ).xyz;

gl_FragColor = vec4(position,1);

Unfortunately, this logic is not functioning properly. Even when excluding constraint calculations and passing values unchanged, the addition of any acceleration in the Position Shader leads to position values spiraling out of control.

Where could I be making an error?

Answer №1

This specific illustration does not relate to verlet cloth directly, however, I believe the fundamental concept could be beneficial to you. I have a demo that utilizes the GPUComputationRenderer for implementing spring physics on a point cloud. It might be possible for you to customize it according to your requirements.

To enhance your understanding, acquiring more details is crucial. You will require fixed references to the original shape of the cloth (akin to a flat board) along with the forces acting on those points (such as gravity, wind, structural integrity, etc.), which determine the current position of each point. These references to the initial shape combined with the forces are essential for enabling the cloth to retain its shape over time instead of tearing apart easily.

As an example, presented here is my spring physics shader utilized by the GPUComputationRenderer to calculate the positions of points in my visualization. The tOffsets store the coordinates that maintain the cloth's memory of its original configuration - these values do not change. This DataTexture is added to the uniforms at the beginning of the program. Various forces like mass, springConstant, gravity, and damping remain constant within the shader. The tPositions contain the vec4 coordinates that undergo changes (two of them representing the current position, while the other two capture the velocity):

<script id="position_fragment_shader" type="x-shader/x-fragment">   
  // This shader focuses solely on the mathematical calculations to move the various points. The addition of sprites and point opacity is handled in the subsequent shader.
  uniform sampler2D tOffsets; 
  uniform float uTime;

  varying vec2 vUv;

  float hash(float n) { return fract(sin(n) * 1e4); }

  float noise(float x) {
      float i = floor(x);
      float f = fract(x);
      float u = f * f * (3.0 - 2.0 * f);
      return mix(hash(i), hash(i + 1.0), u);
  }

  void main() {
      vec2 uv = gl_FragCoord.xy / resolution.xy;

       float damping = 0.98;

       vec4 nowPos = texture2D( tPositions, uv ).xyzw;
       vec4 offsets = texture2D( tOffsets, uv ).xyzw;
       vec2 velocity = vec2(nowPos.z, nowPos.w);

       float anchorHeight = 100.0;
       float yAnchor = anchorHeight;
       vec2 anchor = vec2( -(uTime * 50.0) + offsets.x, yAnchor + (noise(uTime) * 30.0) );

       // Newton's law: F = M * A
       float mass = 24.0;
       vec2 acceleration = vec2(0.0, 0.0);

       // 1. Applying force due to gravity:
       vec2 gravity = vec2(0.0, 2.0);
       gravity /= mass;
     acceleration += gravity;


       // 2. Implementing the spring force
       float restLength = yAnchor - offsets.y;
       float springConstant = 0.2;

       // Vector from anchor to point position
       vec2 springForce = vec2(nowPos.x - anchor.x, nowPos.y - anchor.y);
       // Length of the vector
       float distance = length( springForce );
       // Extension represents the difference between the current distance and restLength
       float extension =  distance - restLength;

       // Calculating springForce based on Hooke's Law
       springForce = normalize(springForce);
       springForce *= (springConstant * extension);

       springForce /= mass;
       acceleration += springForce;

       velocity += acceleration;
       velocity *= damping;
       vec2 newPosition = vec2(nowPos.x - velocity.x, nowPos.y - velocity.y);
       // Updating the new position
       gl_FragColor = vec4(newPosition.x, newPosition.y, velocity.x, velocity.y);
   }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

capturing the HTML title and storing it in a JavaScript variable

Is there a way to retrieve the title "Some Name" in the JS file and have it be populated by the hyperlink's title attribute, which is set to "sometitle" in the HTML code? JS var randomtext={ titleText:"Some Name",} HTML <a class="css" title="so ...

Angular.js, Yeoman, and Grunt are essential tools for front-end

I've been working on developing an AngularJS application using Yeoman. Everything was going smoothly until I decided to implement some unit tests. Whenever I try to run my unit tests using grunt, I keep encountering the following error: Warning: Tas ...

Inquiries prior to projecting rays

As I delve into the world of Interaction with Three.js, several questions arise in my mind. 1) Can you shed some light on what exactly Viewport Coordinates are? 2) In what ways do they differ from client Coordinates? 3) How did we come up with this form ...

"Trouble with script: external JavaScript file failing to run

The issue lies in the fact that the specified external JavaScript file is not being executed: <script src="//www.google-analytics.com/cx/api.js?experiment=YOUR_EXPERIMENT_ID"></script> Even when I try to directly access the URL, it downloads ...

The DOMException occurred when attempting to run the 'querySelector' function on the 'Document' object

Currently, I am engaged in a project that was initiated with bootstrap version 4.3.1. I have a keen interest in both JavaScript and HTML coding. <a class="dropdown-item" href="{{ route('user.panel') }}"> User panel </a& ...

Utilizing eval properly in JavaScript

One method I am using is to load a different audio file by clicking on different texts within a web page. The jQuery function I have implemented for this purpose is as follows: var audio = document.createElement('audio'); $(".text_sample ...

One common issue that arises is the failure of a Javascript function to execute when trying to display a div that is initially hidden using the CSS

I have a div on my website that is initially hidden using this css rule: .menu-popup{ display:none; border:1px solid #FFF; padding:8px; width:100%; height:100vh; position:fixed; top:60px; overflow:hidden; } When I click a ...

Is it feasible to retrieve and view local storage data within an Electron application?

I created an electron application that enables users to drag and drop elements like divs on the screen, saving their positions in localstorage as a class. The purpose is to ensure that any modifications made by the user persist even after reloading or re ...

Arrange JSON data in ascending order based on the dates, starting with the most recent date, by utilizing jquery

I'm in need of assistance on sorting a list of articles from an external json file based on their creation date. Can anyone provide guidance? Currently, I am fetching the data using AJAX and displaying only 6 results, but I'm facing difficulties ...

The state of my React components keeps disappearing

Within my code, I have implemented a click event on the InterestBox to trigger updates in its appearance and alter the state of its parent container. However, despite inspecting the element using React Developer Tools and attempting API requests, the stat ...

Instructions for creating a circular image using the Next.js image component in Next.js version 13

Currently, I'm attempting to replicate an image similar to https://i.sstatic.net/EF5Nd.jpg using the latest version of next.js (version 13) with the next.js image component. However, I am encountering a slight issue where the image appears to be takin ...

Steps to execute a download function in jQuery for retrieving an audio file

I am facing a challenge in creating a download button that should, upon clicking, locate the URL of the current playing song and initiate the download process. However, pressing the button currently opens the file location instead of downloading it. I am a ...

Aligning an element perfectly at the top within a column

I have two columns side by side. The column on the left contains HTML that I cannot control. On the right side, I need to display a comment box that should align with the text clicked on the left hand side. Is it possible to position an element absolutely ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

Loading two scripts in sequence, the first utilizing the "src" attribute while the second is an inline script

The HTML code below shows two script elements being added to the body of a webpage. <html> <body> <script> const first = document.createElement("script"); first.setAttribute("src", "./remote.js"); first.async = false; const second = doc ...

Is it feasible in ES6 Javascript to access properties or methods of the superclass in a child class without the necessity of utilizing the "this" keyword?

Exploring Javascript ES6: Accessing Parent Class Properties in Child Class class Animal { constructor() { this.sound = 'roar' this.species = 'lion' } } class Lion extends Animal { constructor() { ...

Use an if-else statement in jQuery with selectors to determine if a specific div element has been added to it

What if you have a main div and append one of these sub-divs to it? For example: <div class ="append"> <div id ="one"></div> <div id ="two"></div> </div> Then in jQuery, could you do something like this: if ($(.a ...

In what ways can the content of <tr> be switched?

Hey there! I've written a cool little script for toggling the content of a table. The content is hidden inside a <div> with the class "hiddenDiv". In order to reveal it, there is a <span> with the class "toggle" that contains a link. Click ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Storing the .NET Framework viewmodel in its own individual Javascript file

I have a question about structuring my design for SoC (Separation of Concerns). I currently have the following files: testController.cs testViewModel.cs testView.cshtml testScript.js Currently, I generate data in the controller, populate the testViewMod ...