Importing textures and loading mtl files in Three.js from various web addresses

Something strange is happening with my Roblox API integration. I'm trying to retrieve the OBJ file, MTL file, and Texture file using the API. The main API link I have is

https://t2.rbxcdn.com/ef63c826300347dde39b499e56bc874b
, which leads me to two crucial URLs: the obj file
https://t4.rbxcdn.com/4844b24bb4b6696ccbafda0c79d2c406
and the mtl file
https://t1.rbxcdn.com/58f8c8dfcad7ad36d17e1773a698223e
. The issue arises because the MTL file loads from the subdomain t1, while the texture loads from
https://t0.rbxcdn.com/21e00b04dc20ddc07659af859d4c1eaa
under the subdomain t0. Here's where it gets complicated:

Check out the ThreeJs obj loader below:

mtlLoader.load('https://t1.rbxcdn.com/58f8c8dfcad7ad36d17e1773a698223e', async (mtl) => {
    await mtl.preload();
    const objLoader = new THREE.OBJLoader();
    objLoader2.load('https://t4.rbxcdn.com/4844b24bb4b6696ccbafda0c79d2c406', (root) => {
        scene.add(root);
        root.children[0].material.transparent = false

        function init() {
            requestAnimationFrame(init)
            root.rotateY(0.03)
            renderer.render(scene, camera);
        }
        init()
    });
    await objLoader2.setMaterials(mtl);
});

The MTL loader attempts to load the texture as

https://t1.rbxcdn.com/21e00b04dc20ddc07659af859d4c1eaa
. However, the texture should be loaded from the subdomain t0 and not t1. How can I change the subdomain between the MTL file and the textures?

Here's the complete HTML file:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.js">
  </script>
  <script src="https://threejs.org/examples/js/loaders/OBJLoader.js">
  </script>
  <script src="https://threejs.org/examples/js/loaders/MTLLoader.js">
  </script>
  <script>
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

    const renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0xffffff, 1);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    let root2

    const mtlLoader = new THREE.MTLLoader();
    const objLoader2 = new THREE.OBJLoader();

    mtlLoader.load('https://t1.rbxcdn.com/58f8c8dfcad7ad36d17e1773a698223e', async(mtl) => {
      await mtl.preload();
      const objLoader = new THREE.OBJLoader();
      objLoader2.load('https://t4.rbxcdn.com/4844b24bb4b6696ccbafda0c79d2c406', (root) => {
        scene.add(root);
        console.log(root)
        root.children[0].material.transparent = false

        function init() {
          requestAnimationFrame(init)
          root.rotateY(0.03)
          renderer.render(scene, camera);
        }
        init()
      });
      await objLoader2.setMaterials(mtl);

    });


    const color = 0xFFFFFF;
    const intensity = 0.5;
    const light = new THREE.AmbientLight(color, intensity);
    scene.add(light);
    camera.position.set(0, 103, -5)
    camera.rotateY(-180 * Math.PI / 180)

    const light2 = new THREE.PointLight(0xffffff, 2, 1000, 100);

    light2.position.set(0, 110, -5);
    light2.lookAt(new THREE.Vector3(0, 103, -5))
    scene.add(light2);
  </script>
</body>

</html>

Answer №1

Hey there, I managed to figure this out and wanted to share my solution in case it helps anyone else. Keep in mind that my approach may be seen as a bit unconventional. While looking into the MTL loader, I discovered,

    loadTexture( url, mapping, onLoad, onProgress, onError ) {

            const manager = this.manager !== undefined ? this.manager : THREE.DefaultLoadingManager;
            let loader = manager.getHandler( url );

            if ( loader === null ) {

                loader = new THREE.TextureLoader( manager );

            }

            if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
            const texture = loader.load( url, onLoad, onProgress, onError );
            if ( mapping !== undefined ) texture.mapping = mapping;
            return texture;

        }

and within the load texture function, I simply added

url = url.replace('t1','t0')

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

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

Triggering jQuery accordion when clicked

I have a challenge to tackle - I want to create an accordion system that can display and hide quotes at various points on the page. My desired outcome is to have one quote displayed per accordion panel. When I expand an accordion, I want to show the cont ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

PhantomJS fails to trigger function within page.evaluate

My current project involves scraping data from a Facebook page using the PhantomJS node module (https://github.com/sgentle/phantomjs-node). However, I am facing an issue where the function I pass to evaluate the page is not being executed. Interestingly, w ...

Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or ...

Upon clicking the link, the JavaScript functionality failed to activate

When I click on a link and try to add a class, it's not working. I want to create a "modal" div. Here is the PHP/HTML code: <?php if(isset($_GET['ido'])) { ?> <div id="modal" class="modal" style="background: blue; width: 1 ...

How to Process a Stripe Payment using jQuery AJAX (JavaScript Only)

I'm in the process of creating a custom payment form for Stripe and I want to manually initiate the AJAX call to connect with Stripe. Instead of relying on a typical submit event. Unfortunately, it seems like I might be sending the request to the inc ...

Perform time update every second

Is it feasible to have my timeupdate function run every second? (Using VUE CLI) @timeupdate="videoSecond" videoSecond(){ let Second = this.player.currentTime(); let CaptureList = this.capturesList; CaptureList.forEach(element => ...

Retrieve the expansive offset label for a time zone utilizing moment-timezone

The luxon library enhances the ability to retrieve the offsetNameLong based on the timezone ianaName, which gives a localized translated zone name. For example: DateTime.local().setLocale("en-US").setZone("America/Los_Angeles").offsetNa ...

Embed a React component seamlessly within HTML code

Hey there! I have a situation where I'm pulling valid HTML content from the database and I need to replace merge tags with working React components. The HTML is generated using a WYSIWYG editor. Let me give you an example: const link = <a onClick= ...

When using navigator.mediaDevices.getUserMedia on an iPhone, the webcam is activated in fullscreen mode

I'm facing an issue with the webcam functionality on my app. It works perfectly on Android and Windows, but when I try to use it on iPhone, the webcam opens in a separate full-screen view. Any ideas on how to resolve this? Thank you for your help in a ...

Dynamically update a directive array in Vue.js based on real-time changes

In my Vue project, I have an array defined in the data() method that is populated through a custom directive in its bind hook. Here's the code snippet: import Vue from 'vue' export default { el: '#showingFilters', name: "Filte ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

Is the node certificate store limited to reading only from a predefined list of certificates?

Is there a way to add a new certificate to the list of certificates node trusts, even after some struggle? It appears that Node only trusts certificates hardcoded in its list located here: https://github.com/nodejs/node/blob/master/src/node_root_certs.h ...

The canvas loadFromJson function fails to implement the font-family property

I have implemented the following code to display Google font and update the canvas: /* on change of font, load the preview and update the canvas */ $('#font').on('change', function () { $('.font_preview').show ...

Utilize Vue: Bring in the router within a helper class and navigate to a specific

I'm new to utilizing Vue, and I am currently attempting to import my existing router instance into a JavaScript class where I manage the Authentication. This is the content of my router file: import Vue from 'vue'; import Router from &apos ...

Generating dynamic arrays in JavaScript

View the working code here: http://jsfiddle.net/sXbRK/ I have multiple line segments with unique IDs, and I know which ones intersect. My goal is to create new arrays that only contain the IDs of the overlapping line segments. I do not need the IDs of l ...

What is the best way to find a match for {0} while still allowing for proper

I am working on developing a text templating system that allows for defining placeholders using {0}, similar to the functionality of .Net's string.format method. Here is an example of what I am aiming for: format("{0}", 42), // output ...

What would cause this to result in a blank array?

I have a main component that contains multiple sub-components, which I navigate between by clicking on different elements. These sub-components are all Vue files. What I am trying to achieve is to dynamically highlight the active component when it is bein ...