The performance of Three.js Transform Controls is hindered by lag

After adding transform controls to a sphere in my scene to enable movement, I also included orbit controls for panning around. Initially, everything worked smoothly without any lag. However, once I started moving the sphere, significant lag became apparent. Even after deselecting the sphere and no longer actively moving it, the lag persisted when using orbit controls alone.

  • Why does the lag persist even after ceasing to use the transform controls?
var renderer, scene, camera, controls;

init();

var geometry = new THREE.SphereGeometry( .025, 5, 5 );
var material = new THREE.MeshPhongMaterial( {color: 0xffffff} );
var sphere = new THREE.Mesh( geometry, material ); 
addControls(sphere,"translate");
scene.add(sphere);

render();

function addControls(object, type) {

   var transformControl = new THREE.TransformControls( camera,    renderer.domElement );

   transformControl.addEventListener( 'change', render );
   transformControl.addEventListener( 'dragging-changed', function ( event ) {

       controls.enabled = ! event.value;

   } );

   transformControl.attach( object );
   transformControl.setMode( type );
   transformControl.setSpace( "local" );
   scene.add( transformControl );

}

function init() {

   // Renderer
   renderer = new THREE.WebGLRenderer({ antialias: true });
   renderer.setSize(WIDTH, HEIGHT);
   renderer.setPixelRatio(window.devicePixelRatio);
   renderer.setClearColor(0xffffff);
   document.body.appendChild(renderer.domElement);

   // Camera
   camera = new THREE.PerspectiveCamera(100, WIDTH / HEIGHT, 0.1, 1000);
   camera.position.set(500, 0, 0);

   // Orbit Controls
   controls = new THREE.OrbitControls(camera, renderer.domElement);
   controls.maxDistance = 5;

   // Scene
   scene = new THREE.Scene();

}


function render() {

   renderer.render(scene, camera);
   requestAnimationFrame(render);

}

In an attempt to eliminate the lag, I experimented with removing the transform controls from the scene by incorporating the following within addControls():

window.addEventListener( 'keypress', function ( event ) {

   transformControl.detach( object );
   transformControl.dispose();
   scene.remove(transformControl);

} );

Despite successfully removing the transform controls after moving the sphere, the lag persisted. My expectation was that while there might be lag during movement, it would dissipate when the object was stationary. However, the lag continued even when solely utilizing orbit controls.

How can I mitigate or reduce this persistent lag issue?

  • How can I minimize this lag?

Answer №1

Welcome to the StackOverflow community.

The issue arises due to the stacking of calls to the requestAnimationFrame function every time there is a change event on your controls. This leads to a situation where the render function is repeatedly called, causing an exponential increase in the number of function calls. Consequently, this results in lag even after removing the transform controls.

To resolve this problem, it is recommended to separate your render function from the animate loop.

function animate() {

  requestAnimationFrame( animate );

  render();

}

function render() {

  renderer.render( scene, camera );

}

By decoupling the render function from the animation loop, changes to the transform control will only affect the rendering of the scene without interfering with the animation loop.

Here is a JSFiddle Example demonstrating the solution

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

Guide on transferring a JWT token to a Node.js backend

Recently, I developed a node.js server featuring a login system and am focused on safeguarding my routes. Despite creating middleware to authenticate each protected route, I keep encountering an "Authentication failed" message after logging in. How can I e ...

Refreshing the DeckGL HexagonLayer upon changes to the data array/Initiating a reload for the DeckGL HexagonLayer

I am currently using DeckGL along with React to showcase data on an OpenStreetMap. My goal is to incorporate filters to allow for different views of the data I possess. The main issue I encounter is the inability to refresh the layer representing the data ...

Show and Arrange Various Key-Object Data pairs

I'm facing a challenge with mapping and displaying a JSON file in a different structure. I need help figuring out how to map the data properly. Here's the JSON file: var data = { "megamenu": [ { "name": "level1.2", "link": "#", ...

There seems to be a glitch with the functionality of the HighStocks Tooltip

I've implemented a modified version of the example from highcharts: $(function () { $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) { // Create the chart $('#co ...

The functionality of sending form data via Express.js router is restricted

In my current project, I am developing a basic CRUD functionality in express. My goal is to utilize the express.Router() to transmit form data via the HTTP POST method. The form structure on the browser appears as follows: form.png The process was flawle ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

The screen suddenly turns black just moments after starting the video

Currently, I am utilizing the Youtube JavaScript API to embed videos on my webpage and control a playlist. However, I keep encountering an error where the video turns black right after loading the title, play icon, and loading icon. Initially, it seems lik ...

Error: The function $.ajax(...).done(...).fail(...).complete does not exist

Out of nowhere, I started encountering the error message below: TypeError: $.ajax(...).done(...).fail(...).complete is not a function Below is my code snippet: this.sendRequest = function (type, extension, data, successCallback, successMsg, failMsg, ...

Unable to delete a row from a dynamically generated table using jQuery

I am currently working on a project that involves creating a table based on results from a servlet. The table includes checkboxes, and when a checkbox is checked, a button at the bottom of the table should appear. This button calls a remove function to del ...

Cipher/decipher URL Redirect Parameter

While sending the return URL as a query string parameter, it looks like this: http://localhost:50316/TripNestFinal/Login.aspx?ReturnUrl=~/Account/AccountSettings.aspx However, I am seeking a way to encode ~/Account/AccountSettings.aspx in a manner that wi ...

Tips on aligning three divs horizontally within a container while maintaining a height of 100%

UPDATE: The alignment has been corrected by adding floats. However, the height still doesn't fill 100%. Check out the new look: Image Link In my footer container, I want to arrange 3 columns (colored green, white, and red for clarity). Currently, the ...

Load an external script once the page has finished loading by leveraging the power of $(document).ready() in conjunction with $.getScript()

Is it possible to load a script in the header of a website instead of at the bottom? I've been trying but it's not working as expected. Here is an example of what I'm attempting: HTML file: <!DOCTYPE html> <html lang="en"> < ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

Starting service upon startup in Angularjs

I am looking to retrieve configuration data from the server and store it in the global scope within my AngularJS application. My app operates in multiple modes such as development and production, with different external services being used depending on the ...

Navigating a dynamic table by looping through its generated tr elements

I am currently working with a dynamically created tr table that includes individual rows of data and a fixed total sum at the bottom. The total sum does not change dynamically. var tmp = '<tr id="mytable"> <td id="warenid">'+data1.id ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

Guide to ensuring modal box only appears once all criteria are satisfied

On my website, I have a form that requests the user's personal information. After filling out the form, a modal pops up with a "Thank you for signing up" message. The issue is that even if all fields are left blank and the button is clicked, the modal ...

Utilizing i18n for moment formatting techniques

As I switch from moment to date-fns, I came across this code that involves moment, which I don't quite understand. However, I do comprehend the map function. this.events[0].dates.map(date => moment(date).format(this.$i18n.locale)) I set up an e ...

Is there a way to assign innerHTML values to table cells using PHP?

I'm currently building a website that relies on a database to store information. I have created an array to hold the values retrieved from the database, and now I need to populate a table with these values. Each cell in the table has a numerical ID ra ...

Ways to verify whether the checkboxes within a gridview have been selected

enter code hereMy Gridview has five checkboxes in each row with options 'NO', 'YES', 'NA', 'NA/U', and 'REPEAT'. I am looking to enable a button if any of the checkboxes among 'NO', 'YES&apos ...