Ways to retrieve a glb model without the loader in Three.js

Currently, I am utilizing a GLTFLoader in threejs along with a glb model initialization. My main objective is to extract the model from the loader for use outside of it. Despite researching numerous topics on this matter, none have provided a solution to my issue.

For reference, I am following this example: sculpt.js

Below is the relevant code snippet:


init();
render();

// reset the sculpt mesh
function reset() {
  // clear the existing mesh
  if (targetMesh) {
    targetMesh.geometry.dispose();
    targetMesh.material.dispose();
    scene.remove(targetMesh);
  }

  // combine vertices as needed
  const loader = new GLTFLoader();

  // Load a glTF resource
  loader.load(
    // resource URL
    "teeth.glb",
    // handle loaded resource
    function (glb) {
      scene.add(glb.scene);

      glb.animations; // Array<THREE.AnimationClip>
      glb.scene; // THREE.Group
      glb.scenes; // Array<THREE.Group>
      glb.cameras; // Array<THREE.Camera>
      glb.asset; // Object
    },
    // track loading progress
    function (xhr) {
      console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
    },
    // report loading errors
    function (error) {
      console.log("An error occurred");
    }
  );
  geometry.deleteAttribute("uv");
  geometry = BufferGeometryUtils.mergeVertices(geometry);
  geometry.attributes.position.setUsage(THREE.DynamicDrawUsage);
  geometry.attributes.normal.setUsage(THREE.DynamicDrawUsage);
  geometry.computeBoundsTree({ setBoundingBox: false });

  // disable frustum culling for vertex updates
  targetMesh = new THREE.Mesh(geometry, material);
  targetMesh.frustumCulled = false;
  scene.add(targetMesh);

  // initialize bvh helper
  if (!bvhHelper) {
    bvhHelper = new MeshBVHHelper(targetMesh, params.depth);
    if (params.displayHelper) {
      scene.add(bvhHelper);
    }
  }

  bvhHelper.mesh = targetMesh;
  bvhHelper.update();
}


I specifically require assistance within the reset function to enable the loader to export the model outside its boundaries as geometry.

Your help and insights are greatly appreciated.

Answer №1

The issue you are encountering stems from the fact that the GLTFLoader.load() function operates asynchronously. As a result, any reset actions are completed before your file.glb is fully loaded. One approach to address this is to perform the remaining operations within the callback of GLTFLoader.load() (onLoad).

If you only wish to access the geometries of a loaded scene, you can utilize the traverse() method on the scene, verifying each object as a Mesh, and then retrieving its geometry, like so:

glb.scene.traverse(obj => {
   if (obj.isMesh) {
     console.log(obj.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

Clicking the 'Go back to previous page' link will take you back to the previous window

Is there a way for me to have an "about" link on my homepage that, when clicked, opens in a new browser tab? And then, how can I return to the previous page (homepage) by closing the newly opened about-page browser tab? <a href="#" onclick="location.hr ...

Step-by-step guide on displaying elements within an array of objects

Upon receiving an object from a website, I discovered that it includes an array of objects along with other parameters. When I use console.log(req.body.cart), the output is [ { title: 'iphone 6', cost: '650' } ], but I only require the ...

Populate the textbox with data from the database when the dropdown selection changes

I am looking to automatically populate the text box with a value from the database when a selection is made from a drop-down list using php When an option is chosen from the drop-down list, the text box should display a corresponding record based on the s ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

Steps for modifying the CSS style of a div element following an onclick event:

<html> <head> <style type="text/css"> .step_box { border: 1.0px solid rgb(204, 204, 204); border-radius: 10.0px 10.0px 10.0px 10.0px; } .step_box:hover{ background: rgb(184, 225, 252); } .selected { background-color : #fff000; ...

What is the reason for the absence of CORS restriction in this code snippet?

I've tested this code across various browsers and it seems to be working perfectly fine. Can someone explain why this is happening? What am I overlooking here? <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/jq ...

"Exploring JSON data with jQuery: A guide to efficient search techniques

I have a local file containing JSON data which I successfully loaded using jQuery. My current task is to specifically find the pId with the value of "foo1". The JSON data { "1":{ "id": "one", "pId": "foo1", "cId": "bar1" }, "2":{ ...

Having trouble submitting ajax form data through nodemailer

Hey there, Recently, I created a web app using node.js and express. Everything seems to be working fine except for one issue - I am struggling to get the JSON data sent by AJAX into Nodemailer. Despite confirming that my AJAX is successfully sending the ...

When Three.js is calculating the elapsed time, it fails to render

My goal is to display a rotating cube with a consistent rotation speed across different machines. In order to achieve this, I calculate the timespan between each frame and use this elapsed value in the rotation process. Here's the basic code snippet: ...

AngularJS implementation that disables a button when the input field is empty

As I delve into learning angular JS, I am facing a challenge. I want to disable the button using the "ng-disabled" attribute while my input fields for "login" and "password" are empty. However, the default text in the login input is "LOGIN" and in the pass ...

Utilizing Chart.js to extract and display specific data values from an external JSON file

I am currently engaged in a journey of self-exploration where I aim to create a chart depicting the number of anime shows with comedy or fantasy genres. The data for my chart will be sourced from an external JSON file (anime.json) on my computer. Initially ...

Encountering a type error when making an Ajax request in JavaScript/jQuery

Encountering an error while trying to extract a value within a loop using jQuery. The error message is displayed below. Uncaught TypeError: Cannot read property 'no_of_optional' of undefined Below is the code I am working with. var data = $.pa ...

Angular ngFor Directive Failing to Display Menu Item Information on Right-Click Context Menu

Currently encountering an issue with implementing a right-click function in my context menu. The menu items are not appearing due to the second ngFor="let row" condition... however, I require the selected row object from a right click to pass in a JSON val ...

Looking to identify the maximum and minimum values within an array using user prompts

For our latest assignment, my teacher tasked us with creating a program to determine the highest and lowest marks among a group of up to 15 students. This means that we can input fewer than 15 students if needed. The user has to enter each student's n ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Navigating to a different URL in a remoteMethod with Loopback and Express

Can anyone provide any guidance on how to redirect to a URL within a model function or remoteMethod? I've been struggling to find documentation on this. Here is the code snippet for reference: Model Function (Exposes /catch endpoint) Form.catch = func ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Detecting a click on the background div in Angular without capturing clicks on child divs

Over at ollynural.github.io, I've been working on creating a pop-up div in the portfolio page that provides additional information about the project you select. To close the pop-up, I have implemented an ng-click feature so that clicking on the main p ...

Is Storybook webpack stuck in a loop, rebuilding and reloading constantly?

While working on a NextJS project with Storybook, I am encountering a recurring issue where the webpack keeps rebuilding continuously without stopping. This relentless rebuilding process puts a strain on my CPU and drains the battery of my device. Even aft ...

Tips on reducing the number of "$routeProvider.when" statements in a complex application

Is there a more efficient way to handle routing in AngularJS, specifically for loading html templates based on $location.path? My current approach involves a long list of "Whens" that will become unmanageable as my application grows. .config(['$rout ...