Mesh normalization in three.js is the process of standardizing the vertices

After loading a mesh from an obj file, I attempted to normalize it. Unfortunately, the results are not what I expected. Below is the code snippet for loading and centering the mesh:

const manager = new THREE.LoadingManager();
const loader = new THREE.OBJLoader(manager);
loader.load('http://mywebsite.com/bunny.obj', function(object) {
  object.traverse(function(child) {
    if(child instanceof THREE.Mesh)
    {
      const geometry = child.geometry;
      const verts = geometry.vertices;
      const ctr = new THREE.Vector3(0.0, 0.0, 0.0);

      for(let i = 0; i < verts.length; ++i)
        ctr.add(verts[i]);

      ctr.divideScalar(verts.length);

      for(let i = 0; i < verts.length; ++i)
        verts[i].sub(ctr);
    }
  });

  scene.add(object);
});

The intention of this code was to center the mesh based on the average of vertex positions. However, an unexpected effect is being produced. For further details and visualization, please visit my website:

I'm currently unable to identify the cause of this issue. The ctr variable holds a valid vector, and subtracting a vector from all vertices should only reposition them.

Answer №1

Instances of identical vertices can be found throughout the model, resulting in ctr being deducted from those vertices on multiple occasions due to repetition in the javascript object.

To resolve this issue, consider merging the vertices at the beginning of your traversal function, like so:

var geometry = child.geometry;
geometry.mergeVertices();

This optimization will improve the speed of your code by reducing the number of vertices that need to be processed.

Answer №2

To easily center your entire mesh in the middle of the scene at (0,0,0), you can utilize the GeometryUtils.center() function. For a deeper understanding, take a look at the source code of this function: https://github.com/mrdoob/three.js/blob/master/src/extras/GeometryUtils.js Studying this should provide valuable insights on how to tackle your issue effectively.

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 reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

Combining values and eliminating duplicates from an external API: A step-by-step guide

My API provides soccer game results in this format: results:[ { Group:"A" Home: "Fc Barcelona", Away: "Fc Porto" Score: { Home: 0, Away: 0 }, { Group:"A" Home: "AC Milan", Away: "Fc Barcelona" Score: { Home: 0, Away: 1 }, { Group:"A" Home: "FC Barcelona" ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

The onsubmit function is not successfully executing the JavaScript function

This code contains a form for creating a new user login. Upon pressing the 'continue' button, it is supposed to call the 'validateForm()' function which checks the values entered in the form. However, even when there are errors such as ...

Tips for changing the content of a td element to an input field and removing the displayed value

I am facing an issue with a dynamic table that displays names and input fields. When a name is displayed in a table row, the user has the option to delete that name. I am able to remove the value from a specific table row, but I am struggling to replace th ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

The Protractor tool (node:9208) threw an UnhandledPromiseRejectionWarning due to an ElementNotVisibleError, indicating that the element is not interactable. Despite this

I am attempting to interact with an element using protractor but encountering the following error (node:9208) UnhandledPromiseRejectionWarning: ElementNotVisibleError: element not interactable (Session information: chrome=69.0.3497.92) (Driver informa ...

What is the method for applying a distinct texture to each face of a DodecahedronGeometry?

I have just started exploring three js and successfully created a polyhedron with a single texture. However, incorporating multiple textures along with captions seems to be more advanced. ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

Implementing a scrolling feature in the autocomplete textbox to handle lengthy data

I successfully implemented an autocomplete multiselect textbox functionality that is working well. However, I am facing an issue with a long list of values appearing when I have 3000 records and type A in the textbox. Please refer to the screenshot below: ...

Tips for managing NaN values within mathjs.evaluate

console.log(mathjs.evaluate("(goodCount/(goodCount+reject_count))>0.99", { goodCount: 0, reject_count: 0, Total_Planned_time: 10 })) I am facing an issue where if both goodCount and reject_count are zero, this function returns NaN. Howe ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

Adding data to each span and div using JavaScript is a simple task that can be achieved easily

What is the best way to add information to each span and div element using JavaScript? $(document).on("click",".selection-state",function(){ stateid = $(this).attr("rel"); $("#my_tooltip").html(data); } e ...

Modify iframe form action URL dynamically upon user visiting the URL with a specified parameter

Below you will find a code example: The page URL is: <html> <body> <h1>main page</h1> <iframe src="http://example2.com"> <form id="test" action="http://example3.com?id=1"> ... </form&g ...

`Adjusting function calls based on the specific situation`

On my webpage, I have implemented a tab system where clicking on a tab displays the corresponding content below. This functionality is controlled by a JavaScript/jQuery function called 'changeTab'. Now, I want to set up individual JavaScript fun ...

Is it important that the end date does not exceed the start date?

In my request, the end date cannot be later than the start date. For example, if the start date is 24/4/2017 and the end date is 23/4/2017, the search function should be disabled for the calendar date 23/4/2017. Only dates from 24/4/2017 onwards should be ...

Getting a list of connected users on a PeerJS server using Express is simple and straightforward. Follow these steps to

Trying to incorporate PeerJS, a webRTC library, into a game and utilizing their server for user discovery has proven challenging. The goal is to manage a list of connected users, but grappling with the PeerJS server has been difficult. The documentation s ...

jspm is having trouble locating the globalResources for a 'feature' plugin in an Aurelia application

Looking for guidance on setting up and utilizing a feature plugin with Aurelia docs? Find detailed instructions at I encountered an issue where paths to resources were being transformed by jspm or Aurelia. Upon specifying the current path as .aurelia.use. ...