Import objects into THREE.js using OBJLoader, convert to Geometry, apply transformations, and finally convert to BufferGeometry

Trying to figure out why the geometry loaded with OBJLoader cannot be smoothly shaded.

var loader = new THREE.OBJLoader(manager);
loader.load('/manmodel/js/man.obj', function (object, materials) {
    console.log(object);
    console.log(materials);
    man = object;
    man.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
            child.geometry.computeFaceNormals();
            child.geometry.computeVertexNormals( true );
            child.material = new THREE.MeshPhongMaterial({
                color: 'white',
                shading: THREE.SmoothShading // <-----------  THIS IS THE PROBLEM
            });
        }
    });
    man.position.y = -10;
    scene.add(man);
});

This is what I found:

If I remove the line computeFaceNormals(), the model renders the same. If I remove computeVertexNormals( true ), the object renders with no lighting (black) - indicating it is having an effect.

Changing the color attribute of the MeshPhongMaterial in this code does change the color, so that functionality works.

Attempts to use vertex and normal helpers failed because faces and vertices are not stored as arrays in BufferGeometry.

Modifying the man.obj file by changing 's' values from 'off' to 1 had no impact.

Since I will be loading multiple .obj files for different human figures generated in Blender, each around 2MB, I prefer to handle shading on the browser rather than increasing file size by "baking" it into the file.

THE QUESTION(s): Am I overlooking something here? OR, Is there a way to load the .obj file as standard Geometry, compute normals, apply shading, and then save as BufferGeometry?

ps. Normals may also be needed for ray tracing in the future.

Answer №1

The latest iteration of ObjLoader now converts the .obj file into a BufferGeometry for improved performance. If you check the GitHub repository's history, you'll come across the previous version that converted it into Geometry:

https://github.com/mrdoob/three.js/blob/a321ba05f02ae3a1586a4060a53f5ad63b90729b/examples/js/loaders/OBJLoader.js

To load your .obj file using this method, manipulate the Geometry until it meets your requirements, then create a new BufferGeometry and transfer the Geometry data into it using BufferGeometry.fromGeometry(geometry) to enhance performance. I have successfully implemented this technique.

Answer №2

To utilize the latest loader (r73), we can transform the BufferGeometry into a Geometry, and then reverse the process!

The only catch is that I had to combine the vertices prior to calculating the vertex normals. It seems that converting from buffers may affect the triangles, so it's necessary to merge them beforehand.

 var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
 geometry.computeFaceNormals();
 geometry.mergeVertices();
 geometry.computeVertexNormals();
 child.geometry = new THREE.BufferGeometry().fromGeometry( geometry );

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

Swap out a button for another using JavaScript

I am facing a challenge where I need to replace an active button with a deactivate button. The issue is that when I click on the active button, it does change to the deactivate button as expected. However, clicking again does not switch it back to the acti ...

Error encountered in Pokemon API: Trying to access property '0' of undefined

My current challenge involves accessing the abilities of my Pokemon, but I keep encountering a recurring error. In my project development using React hooks, I fetched data from the Pokemon API and stored it in setWildPokemon. Utilizing wildPokemon.name suc ...

What is the best method to modify the accurate phone number within my script?

I need help with a text format script. link HTML CODE: <label for="primary_phone">Primary Phone Number<span class="star">*</span></label> <br> <input type="text" name="primary_phone" id="primary_phone" class="_phone requ ...

What is the best way to implement a calendar view for selecting time periods on an HTML page?

Is there a way to implement a calendar view when clicking on the input box within an HTML page? I am looking to create a function where users can select a time period to generate a file. How can this be accomplished? If possible, could you share some samp ...

Turn off the scrolling bars and only allow scrolling using the mouse wheel or touch scrolling

Is there a way to only enable scrolling through a webpage using the mouse wheel or touch scrolling on mobile devices, while disabling browser scroll bars? This would allow users to navigate up and down through div elements. Here is the concept: HTML: &l ...

Tips for embedding multiple video players on a single HTML page

I'm currently experiencing an issue with the YouTube API. I am in the process of developing a website where I want a video to automatically play when I open its corresponding image. The code I used initially worked successfully: <script> // 2. ...

Error with REST service and browser history in ReactJS

I am currently developing my first Java application, which is a REST service built with Spring Boot. It utilizes technologies such as WEB, REST, JPA, Thymeleaf, and MySQL. The API is fully functional, but I wanted to enhance it with a user interface. After ...

The logical operator malfunctions following a computation

var sub_response_type = {"survey_question":["Test lable"],"responseTypeText":"Exit label","select_param_type":[">","<"],"questions_id":["7","8"],"select_param_value":["12","34"],"radio_type":["&&"]}; var order = ['questions_id' ...

Utilizing Google Analytics within an Angular Single Page Application

After implementing Google Analytics (GA) in my Angular single page application and placing the tracking code at the bottom of the main index.html, I encountered an issue regarding incorrect pageview results. <script> (function(i,s,o,g,r,a,m){i["Go ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Iterate over the object to verify if the field contains an empty array, then output null

Looking for help with handling empty arrays in an object: productDetails: { cislife: [], prime: [] } Is there a way to have null returned instead of an empty array if no values are available? For example, I'd like to determine if either t ...

The progress bar in Next JS 13 seems to be malfunctioning and is not displaying any

After transitioning to the new Next JS 13 app directory, I encountered an issue where the progress bar at the top does not function when the page loads. In the previous version, Next JS 12, there was a package named nprogress and nextNprogress that simpli ...

Tips on sending the total value of a form to a PHP script

Looking for help with a PHP script to calculate the sum of checked checkboxes with corresponding numeric values. For example, if checkbox 1 = 80; checkbox 2 = 21; and checkbox 3 = 15, and the user checks checkboxes 2 and 3, the PHP should output 36. I hav ...

Saving an Image from HTML5 <canvas> using Java Servlet

Despite the numerous StackOverflow questions on this topic, I have gone through many of them without success. Now, I am reaching out with my own question. My objective is to save an image from an HTML5 <canvas> on my webpage to a file on my server u ...

Wait until all information has been entered into the database before replying to the request

I have been exploring a way to insert multiple data in one call and only trigger a response after all the data has been inserted. Here is my current implementation: create: function(req, res) { var response = {}; var num = req.body.num; var re ...

Retrieve an array from a JSON object by accessing the corresponding key/value pair using the utility library underscore

I have a dataset in JSON format (as shown below) and I am attempting to use the _.where method to extract specific values from within the dataset. JSON File "data": [{ "singles_ranking": [116], "matches_lost": ["90"], "singles_high_rank": [79 ...

Using async/await in an Express route handler

Currently, I am facing an issue with my node/express route. The route collects information through url parameters and then uses these parameters to trigger a separate function that takes some time to execute. Despite using async/await to pause the executio ...

Trouble with Vue 3 watch not persisting after page refresh

Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language. Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in b ...

Transferring information between AngularJS and Express/Node without using AJAX

My application is built using AngularJS on a node/express backend, with user authentication handled by passport. After a user signs in or signs up, the communication between my Angular controllers and express is done through $http ajax/xhr calls. The form ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...