Import and Showcase Collada Models with Textures using Three.js and file inputs

Currently, I am faced with a challenge involving loading a Collada file along with textures from file inputs. Specifically, I have set up 2 inputs, one for the geometry (.dae) file, and another for textures (.png/.jpg). When these file inputs change, two separate functions are triggered:

  • loadCollada(): This function utilizes THREE.ColladaLoader to load the geometry file and stores it in a global variable named loadedCollada
  • loadTextures(): This function uses THREE.TextureLoader to load the textures and stores them in a global variable named loadedTextures

Once these functions have done their job, a third function, loadModel() is executed. While I have managed to get the model to display, the textures are not correctly applied and if the model's up axis is not Y_UP, it is displayed at the wrong angle. Here is an outline of what loadModel() entails:

  • Geometries are extracted from the loadedCollada variable and stored in an array called geometries
  • The geometries in the array are combined into a single geometry (THREE.Geometry) using the THREE.GeometryUtils.merge() function
  • A final mesh is created from the single geometry and textures stored in loadedTextures
  • The model is then placed into the scene

I would greatly appreciate any assistance on this matter as I have been struggling to find a solution for quite some time. While it would be easier if I didn't have to rely on loading Collada files from the user's machine, it is necessary for the project to work with file inputs. Thank you for any help provided :)

Answer №1

Lately, I've been working on a similar project involving OBJ+MTL files uploaded by users.

This new feature in three.js (r88) https://github.com/mrdoob/three.js/pull/11259 lets you specify resource URLs (pulled from uploaded files).

I came across this example https://github.com/mrdoob/three.js/pull/12591 that guided me in loading OBJ+MTL files. It should work for various model loaders as long as they utilize the loadingManager. This approach streamlines selecting both the model and textures simultaneously with just one file input (including drag and drop functionality).

So, I created a fiddle based on the above collada format example: https://jsfiddle.net/Lhrvna7a/45/

The key segments are highlighted below:

$('.inputfile').change(function (e) {

var files = e.currentTarget.files;
var dae_path;

var extraFiles = {}, file;
for (var i = 0; i < files.length; i++) {
  file = files[i];
  extraFiles[file.name] = file;

  //Filename ends in .dae/.DAE
  if (files[i].name.match(/\w*.dae\b/i)) {
    dae_path = files[i].name;
  }
}

const manager = new THREE.LoadingManager();
manager.setURLModifier(function (url, path) {       

  url = url.split('/');
  url = url[url.length - 1];

  if (extraFiles[url] !== undefined) {

    var blobURL = URL.createObjectURL(extraFiles[url]);
    console.log(blobURL); //Blob location created from files selected from file input
    return blobURL;     

  }
  return url;
});

var loader = new THREE.ColladaLoader(manager);
loader.load(dae_path, function (collada) {

  console.log(collada);
  var dae = collada.scene;

  scene.add(dae);

});                 
  });
}   

Once the model loads, I suppose the same procedures for actions like merging can be carried out as when loading a model conventionally.

Concerning the model's orientation, it's possible that the software used to create the model employs a different coordinate system than three.js. It might not be feasible to determine the model's rotation in advance in collada (I could be mistaken on this), but setting dae.rotation.set(0, 0, 0); before adding the model to the scene could suffice.

Hopefully, this information proves useful to you.

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

I am working with a JSON Object in JavaScript and need to retrieve a key using a String variable

Working with a JSON Object in JavaScript can be tricky, especially when trying to access keys stored as Strings using the dot operator. Consider this example of JSON code: "values" : [ { "prop0" : "h", "prop1" : "pizza", "prop2" : "2014- ...

What causes the React app to fail in maintaining the login session with the Node.js server?

Greetings, I have a NodeJS server set up in two separate files: app.js and routes.js. The app.js file includes code for setting up the server, error handling, middleware configuration, and routing logic. The routes.js file contains specific route configu ...

Can a variable name be created using a function input?

It seems like my title might be a bit confusing, but oh well. I'm currently working on developing a game and I have several arrays named things like ItemsInG5Array, ItemsInB2Array. These names correspond to different nodes on the map. What I'm ai ...

Is it possible to extract a div from a third-party domain and showcase it on my website?

Trying to integrate content from my Veetle.com channel onto my personal website has proven to be quite the challenge. Initially, I attempted to modify an iframe with CSS to display only the schedule information, but encountered limitations due to using 3rd ...

jquery unbinding events can lead to faster performance

I'm in the process of creating a content-heavy slideshow page that heavily relies on event triggers, with about half of them utilizing the livequery plugin. I'm curious if unloading these events between slides to ensure only the active slide has ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Node.js Mistake - 'Attempting to import outside of a module is not allowed'

I’m currently immersed in a React project, and my focus is... Firebase.js import firebase from 'firebase/app' import 'firebase/database' import 'firebase/auth' const firebaseConfig = { apiKey: process.env.FIREBASE_AP ...

Javascript error in formatting

Currently, I am utilizing an inner join operation on three tables and displaying the resulting table using XML. <SQLInformation> <Table>tblechecklistprogramworkpackagexref prwpxref</Table> <TableJoins> INNER JOI ...

Experiencing trouble with implementing multiple textboxes based on option selection using javascript

My JavaScript code is supposed to display multiple textboxes based on the user's selection, but for some reason, I can only select one textbox at a time. I'm not sure what's wrong with my code. Here's the snippet of the code: <ht ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

The replaceWith() function in jQuery is able to transform PHP code into an HTML comment

How can I change a div element in a click event handler, while ensuring that PHP code inside the element remains intact and does not get moved into an HTML comment? You can find my code snippet below: $("#replaceCat1").click(function(){ $("div.boxconte ...

Using Vue to dynamically upload multiple files simultaneously

Although this question has been asked frequently, most of the answers do not address a key issue - how to upload multiple images while knowing which image belongs to which data. Attempting to bind v-model to input file doesn't work as expected, and ev ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

I am interested in delivering a blended, divided response containing JSON and a string using Express

I am currently in the process of integrating ChatGPT into my Node/Express project and I have a specific requirement. I would like to initially send some metadata in JSON format to the client before streaming the response from ChatGPT as it comes in. Every ...

Can you explain the contrast between using require('d3') and require('d3-selection')?

While working on a nodejs application with javascript, I encountered an interesting issue. In my code, I am passing a d3 selection to a function as shown below. // mymodule.js exports.myfunc = function(ele){ if(ele instanceof d3.selection){ // do so ...

Obtaining a file from Firestore using cloud functions

I have experimented with various approaches, like: const admin = require("firebase-admin"); admin.initializeApp(); const db = admin.firestore(); const docRef = db.collection("users").doc(dynamicDocID).get() const docRef = db.collectio ...

Best locations for placing files when integrating Javascript into Wordpress

I have been struggling to make JavaScript work and determine the correct location to place the files. After attempting various methods, I am now wondering what the most logical approach would be. Despite spending a week on this task, the lack of a tutoria ...

Include a sub-component N times within the main component, depending on the current state value

I need assistance in adding a child component called ColorBox to the parent component named ColorBoxContainer based on the value stored in state as noOfBoxes: 16. I've tried using a for-loop but it seems like my code is incorrect. Can someone guide me ...

Activate scroll event when image src changes in Angular using jQuery

Seeking assistance with utilizing jQuery to scroll to a specific thumbnail inside a modal when left/right arrows are pressed. The modal should appear when the user clicks on an image. I've managed to implement scrolling upon clicking a thumbnail, but ...

Extract the input value from the bootstrap-datepicker using JavaScript

I'm working on a Ruby-on-Rails project and I want to include a string from the bootstrap datepicker into a hidden field. However, I am unsure of how to reference an input class in this process. Below is the structure of my form: <%= simple_form_f ...