Creating dynamic cylinder mesh objects in THREE.js with constantly evolving dimensions, positions, orientations, and colors

In my THREE.js animation, I am striving to render a minimum of 100 cylinders at a speed exceeding 30 frames per second.

Approach 1

Some experts suggest creating a pool of mesh objects during Initialization and reusing them throughout the Animation process. However, this might not work for me as my cylinder geometries vary in length between frames, making it challenging to use Scale due to their non-alignment with principal axes (x, y, or z).

Approach 2

An alternative method is to generate 100 NEW mesh objects every frame. Nonetheless, if these objects are not deleted after rendering each frame, there could be a significant memory drain issue.

    for (var iii=1; iii<=10; iii++)
    {    
        if (MyCylinders[iii])     scene.remove(MyCylinders[iii]);

        // Creating new cylinder
        cylinder = new THREE.Mesh(new THREE.CylinderGeometry(2, 2, 500 * Math.random(), 100, 100, false), new THREE.MeshBasicMaterial({color: '#880066'}));
        cylinder.overdraw = true;
        cylinder.rotation.x = Math.PI * 0.5 * Math.random();
        cylinder.rotation.y = Math.PI * 0.5 * Math.random();
        cylinder.rotation.z = Math.PI * 0.5 * Math.random();
        cylinder.position.x = 200*Math.random();
        cylinder.position.y = 200* Math.random();
        cylinder.position.z = -200* Math.random();

        MyCylinders[iii] = cylinder;
        scene.add(MyCylinders[iii]);
    }

Frequent creation and deletion as shown in this example http://jsfiddle.net/errp5/5/ can significantly impact the frame rate.

Query

Is there a better approach to achieve this goal?

RESPONSE

Method 1 combined with judicious use of Scale and Rotation is deemed more effective for creating a pool of reusable mesh objects.

Refer to the working demo here:- http://jsfiddle.net/KjxZp/2/

Snippet of code:

var desired_cylinder_length = 195 + 5 * Math.random();
      //... Loop
      for (var iii = 1; iii <= Num_Rays; iii++) {
          cylinder = MyCylinders[iii];

          //... apply new scale and rotation to cylinder
          cylinder.scale.y = desired_cylinder_length;
          cylinder.overdraw = true;

          cylinder.rotation.x += (0.005) * Math.PI * Math.random();
          cylinder.rotation.y += (0.005) * Math.PI * Math.random();
          cylinder.rotation.z += (0.005) * Math.PI * Math.random();

          MyCylinders[iii] = cylinder;
          MyCylinders[iii].geometry.verticesNeedUpdate = true

Answer №1

The issue with using the Scale function is that not all objects are properly aligned to one of the main axes (x, y, or z).

But don't worry, there's a solution for that.

let geometry = new THREE.CylinderGeometry(1, 1, 1);
geometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0.5, 0));

let mesh = new THREE.Mesh(geometry);
mesh.scale.y = Math.random() * 100;

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

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

Encountered an error while trying to deploy Node.js on Heroku: TypeError - Unable to access property 'split' of null

Seeking insight into the following error message: My application is built on Node.js and uses Atlas as its database. However, when attempting to deploy it on Heroku, I encounter the following error in the logs: TypeError: Cannot read property 'spl ...

Displaying image behind bootstrap modal using Lightgallery js

Can anyone help me with an issue I'm having with previewing images using lightgallery js? The image is showing up behind the modal window. https://i.sstatic.net/FncZB.png I'm not sure why this is happening Here's the javascript code I am ...

Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution: <ng-container *ngIf="user.images.length > 0"> <div *ngFor="let image of images"> <img *ngIf="i ...

tool for uploading and validating multiple file types

I have a file upload control for uploading multiple files. Here is an example: <ajaxToolkit:AsyncFileUpload ClientIDMode="Static" name="aa[]" BackColor="Azure" ForeColor="Black" OnClientUploadError="uploadError" OnClientUploadStarted="abc" ...

Evaluating the functionality of download links using Nightwatch.js

My goal is to create an automated test using Nightwatch.js to validate the functionality of software download links. Instead of downloading the files, I simply want to confirm that the links are returning a 200 HTTP response, indicating that they are direc ...

Upon clicking submit, the form merely reloads the page instead of navigating to the specified routes

I've been grappling with this issue for a while now and just can't seem to find the root cause. My goal is to make a POST request to /accountRoutes/editFinalMark. I have provided the code for the route and the corresponding controller below. < ...

Error: 'socket' is inaccessible before it has been initialized, specifically in the context of electron

Trying to configure an electron app where a message is sent to the server, and the server places the value on the read-only textarea. However, upon starting the app, the following error appears in the devtools console: Uncaught ReferenceError: Cannot acc ...

Utilizing an AJAX call to communicate with a PHP function script within a REST (Paypal) module successfully functions with jQuery, however it encounters issues when trying

I've been struggling with a mental block for hours, trying to figure this out. In a Paypal REST success section, I'm attempting to call a function. Prior to moving it to the REST section, I tested it with a regular button onclick event, and it w ...

Instructions for creating an automated photo carousel

I'm currently using an image slider and everything is working fine so far. When I click on the next or previous arrow, the images change accordingly. However, I also want the images to change automatically after a certain time interval. I've trie ...

The design of RESTful web applications with a client-server architecture

I need clarification on how client-server architecture should function for a modern web application with a RESTful backend. For a web app, the client is typically the browser while the server is the web server. Programatically speaking, there are componen ...

How to use jQuery to retrieve the height of the elements inside a specific container

I'm uncertain if it's feasible, but I am looking to determine the total height of the content within a specific container. Imagine I have <div id="container" style="min-height:100vh"> <div class="child"> <p>Some text ...

Guide on mocking a function inside another function imported from a module with TypeScript and Jest

I have a function inside the action directory that I want to test: import { Action, ActionProgress, ActionStatus, MagicLinkProgress } from '../../interfaces' import { areSameActions } from '../actionsProgress' export const findActionPr ...

Troubleshooting Highcharts container selection problem on Nexus 7 running version 4.2.1

Having a problem with Highcharts on my Nexus 7. When I touch the chart, the entire thing gets selected with a blue overlay, but this doesn't happen on other devices like the Nexus 4. Even when I try accessing demos from Highcharts website, the issue ...

Arranging objects in JavaScript arrays

There is an array containing elements with two properties each: const players = [{id: 15, score: 567}, {id: 4, score: 789}, {id: 27, score: 123}, {id: 1, score: 654}]; The task at hand is to sort the a ...

Simultaneously removing and inserting components with Meteor.js

I have a straightforward set of items that is displayed like this {{#each items}} {{> item}} {{/each}} My code defines that only the three most recent items are shown return Items.find({}, {sort: {timestamp: -1}, limit: 3}) Whenever a new item i ...

How can I retrieve an array of collections from multiple parent documents in Firebase and pass them as props in Next.js?

I need to access all the collections within the documents stored in a collection named users. This is how I currently retrieve all the user information: export async function getServerSideProps() { const snapshot = await firebase .firestore() .collection ...

What is causing the angular ng-repeat table to not sort correctly?

Currently, I am facing an issue with a table that is being populated by Angular: I have provided the code here so you can see the problem in action: http://plnkr.co/edit/qzY4r2XWq1UUJVrcqBsw?p=preview When I click on the a elements, the sort order change ...

New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, o ...