Removing vertices in ThreeJS: A step-by-step guide

When it comes to adding new vertices to a three.js mesh, the process is simple with mesh.geometry.vertices.push(new THREE.Vector3(x, y, z)). But removing them? That's where things get tricky.

Since "geometry" is an array, one might think that removing vertices can be done by using:

mesh.geometry.vertices.splice(vertexIndex, 1)

mesh.geometry.verticesNeedUpdate = true;

However, attempting this method often results in errors within three.js, specifically the message: "Uncaught TypeError: Cannot read property 'x' of undefined" found inside three.min.js.

Even after scouring their wiki and github issues, I couldn't find a resolution. The mesh in question is simply a BoxGeometry, not even a custom one.

Answer №1

Threejs operates on the basis that each face consists of 3 vertices. To illustrate this concept, consider the following example demonstrating how to create a geometry in r71:

 geometry=new THREE.Geometry();

geometry.vertices.push(// several vertices with random coordinates
    new THREE.Vector3(12,15,5),//index:0 -- the numbers represent (x,y,z) coordinates
    new THREE.Vector3(10,15,5),//index:1
    new THREE.Vector3(12,10,2),//index:2
    new THREE.Vector3(10,10,2)//index:3
);

geometry.faces.push(
    new THREE.Face3(0,1,2),//these values are indices of the vertices in the array above
    new THREE.Face3(0,3,2)
);

geometry.computeFaceNormals();// this step is not crucial for our discussion here

(The specific shape resulting from these values is unspecified due to lack of precise data)

This process involves constructing two arrays: vertices and faces. During rendering, each frame depicts the faces based on the positions of their vertices.

The issue arises when a vertex is deleted from the geometry.vertices array. Consider removing the second vertex mentioned earlier - the updated array would appear as follows:

 geometry.vertices=[
    THREE.Vector3(12,15,5),//index:0
    THREE.Vector3(12,10,2),//new index:1
    THREE.Vector3(10,10,2)//new index:2
];

With the deletion, vertex at index 3 is no longer present. Consequently, during the subsequent frame render, if a face references this removed vertex (as seen in the second face), an attempt to access its coordinates will lead to an error message indicating inability to read x of undefined.

This explanation underscores the impact of vertex deletion on the array structure, causing inaccuracies in the faces' shapes and normal vectors. Moreover, any necessary buffer modifications are restricted, as emphasized in resources such as:

Dynamically Adding Vertices to a Line in Three.js

Adding geometry to a three.js mesh after render

To rectify this issue, various strategies can be employed, including adjusting vertex coordinates or concealing faces. The approach taken depends on the specific requirements of the project.

If the scene contains only a limited number of vertices, another solution may involve discarding the existing mesh and generating a new one with modified geometry lacking the problematic vertex and corrected face array.

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

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

Inject the error into the Router in Express.js, utilizing Node.js

Is it possible to pass an error into an express.js Router? The express.js documentation does not provide a clear answer regarding passing errors in relation to middleware, routers, and error handling (I am unable to include links as I lack reputation). I ...

JavaScript form with radio buttons

I'm completely new to JavaScript and I'm attempting to create a basic script that will show one form when a radio button is checked, and another form when the second radio button is clicked (with no form displayed when neither is selected). I kno ...

Exploring the power of Knockout Js and Typeahead libraries

https://i.stack.imgur.com/38iZc.png Hello experts in Knockout and typeahead, I am receiving suggestions from the typeahead js as shown above. I have my data supplied in an array format var itemsRandom= ['Apple', 'Ball','Ape&apos ...

Angular 2 is not recognizing the element 'router-outlet'

I am currently utilizing universal-cli... This is how my app.node.module.ts appears: /** * This file and `main.browser.ts` are quite similar, for now! * By separating these, you can create logic, imports, etc that are "Platform" specific. * If you wis ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Error encountered: Required closing JSX tag for <CCol> was missing

Encountered a strange bug in vscode...while developing an app with react.js. Initially, the tags are displaying correctly in the code file. However, upon saving, the code format changes causing errors during runtime. For instance, here is an example of the ...

How to Dynamically Set AngularJS Filter (like date or currency) Using Variables

When working with Angular, it's possible to easily apply filters to format variables, like so: {{ myDate | date }} {{ myMoney | currency }} But, is there a way to dynamically set the filter type in a more flexible manner as shown below? // controll ...

Obtaining an element through its id using an expression in an Angular directive

Here's a complex question that needs to be broken down. I'm trying to mimic the behavior of the native <label> for <input>. Since nesting is not an option, I use a style like this: <input type="checkbox" id="test" /> Some other ...

A guide on leveraging render props in React to reveal details on a component's state

I have researched render props extensively on the official React documentation and various other sources. However, I am currently struggling to understand how Tailwind implements this pattern in their components to expose state information. Take for examp ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

The most effective method for calculating overhead is through the utilization of synchronous techniques

I'm currently developing a nodeJS app that heavily relies on synchronous methods, particularly for file operations and spawning child processes. I am looking to assess the impact of these blocking main thread activities in terms of overhead. What woul ...

sending parameters to package.json scripts

Currently, I am utilizing nodejs and in my package json file, I am required to define a test in the following manner: "test:mine": "cross-env NODE_ENV=test nyc mocha \"./tests/**/objectStore.test.ts\" ", When I execute npm run test, only that s ...

An easy way to pass props to a component using useNavigate in React Router

Is it possible to send props directly to a component in React? const goToProjectPage = useNavigate(); useEffect(()=>{ ..... goToProjectPage("/projectpage"); //send props here },[]); ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Unraveling complex JSON structures

JSON data is available on a specific URL: { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?limit=10", "time":18, "links": { "self": { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?offset=0&am ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...

Demonstration of Concurrent Page Processing in Flask

Currently, I am working on an application that heavily utilizes graphics using libraries such as Raphael and graphdracula. The main functionality of the application involves drawing various graphs across different pages named graph1, graph2, and graph3. L ...

Tips for Utilizing CSS Overflow: Hidden to Prevent the Parent Container from Expanding

I have a fixed width column and a fluid column. In the fluid column, I want to display a string with nowrap so that it does not overflow the container. Here is an illustration of how I want the text to appear: --------------------------------------------- ...