Having trouble loading HDRI image as environment using Three.js

I recently started using Three.js and am currently tackling a project that involves utilizing an HDRI file for environmental mapping for lighting and reflection purposes. I've been experimenting with loading HDRI files using the HDRCubeTextureLoader and RGBELoader, but unfortunately, I have been encountering difficulties. Specifically, I keep getting a "bad file format" error in the Chrome console:

main.js:214 Error: THREE.RGBELoader: Bad File Format: bad initial token
    at rgbe_error (RGBELoader.js:39:36)
    at RGBE_ReadHeader (RGBELoader.js:139:6)
    at RGBELoader.parse (RGBELoader.js:354:28)
    at Object.onLoad (three.module.js:44430:21)

The error points to the line in main.js where

.load(hdrPath, function (texture) {
is located:

const hdrPath = '/Users/.../ocean_hdri/royal_esplanade_1k.hdr';
...
function loadHDRI() {
    new RGBELoader()
        .setDataType(THREE.UnsignedByteType)
        .load(hdrPath, function (texture) {
            const hdrRenderTarget = pmremGenerator.fromEquirectangular(texture);
            scene.environment = hdrRenderTarget.texture;
            scene.background = hdrRenderTarget.texture;

            textMeshes.forEach(mesh => {
                mesh.material.envMap = hdrRenderTarget.texture;
                mesh.material.needsUpdate = true;
            });

            texture.dispose();
            pmremGenerator.dispose();

            console.log("HDRI environment loaded");
        });
}

I have double-checked that the .hdr files are valid and even tried replicating the HDR texture loader example using the same HDR files, but the error persists.

Just to provide more context, I am using Webpack for my build setup, alongside NPX and Vite.

I would greatly appreciate any suggestions or guidance on how to resolve this issue.

Thank you in advance!

Answer №1

Before proceeding, ensure that you have imported the necessary loader in your code. If it's missing, you can add it by following this import statement, especially if you are working with Three.js.

import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';

If the error persists, double-check your webpack.config.js for any potential issues.

module.exports = {
   // …
    module: {
        rules: [
            {
                test: /\.(hdr)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'assets/hdr/[name].[ext]',
                        },
                    },
                ],
            },
        ],
    },
};

Similarly, review your vite.config.js to ensure proper configuration.

export default defineConfig({
    plugins: [
        staticCopy({
            targets: [
                {
                    src: 'src/assets/hdr/*.hdr',
                    dest: 'assets/hdr'
                }
            ]
        })
    ]
});

Many asset loading issues stem from incorrect file paths. Verify that the file path is accurately referenced. The provided path seems a bit suspicious...

'/Users/.../ocean_hdri/royal_esplanade_1k.hdr'

If needed, consider moving the HDR file to the public folder for better accessibility.

Answer №2

If you are seeing the current error message (THREE.RGBELoader: Bad File Format: bad initial token), it typically means that the HDRI file is not being read correctly.

I recommend verifying that your build tools are set up to handle HDR files properly.

Alternatively, you could attempt to troubleshoot by adding logging for debugging purposes.

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 causing my Vue leave transition to malfunction?

Currently, I am utilizing vee validate for my form validation. Specifically, I have implemented vue transition to handle the display of validation errors in the following manner: <input type="text" name="name" v-validate="'required'"> < ...

I want the name to be retained in storage to prevent the item from being mistakenly renamed when deleted based on its index

After pressing the "add layer" button in the box shadow generator, a new layer is added. For example, let's say I have added 3 layers (Layer 1, Layer 2, Layer 3) and then deleted Layer 2. After deletion, the remaining Layers are Layer 1 and Layer 3, b ...

Is there a way to extract data from the Redux state in a React component?

Seeking assistance with making an API request from Redux, followed by saving the data in my React state (arrdata). Although the API call is successful, I am facing challenges updating the App.js state based on the Redux API call. Any suggestions or insig ...

Improprove the Express Router in a Node.js application

Is there a way to avoid repeating the isUserAuth and isAdminAuth middleware on each endpoint? Can I apply them just once so they work for all routes without having to specify them individually? const { createBranch, getAllBranch, getBranch } = require(&apo ...

The failure of numerous asynchronous calls in the JavaScript Facebook API is causing issues

Utilizing Facebook's Javascript API in my jquery mobile website to fetch albums and photos from a Facebook public page and display them on my website has been quite seamless. The API provides clear instructions on how to accomplish this, and I was ab ...

Understanding JavaScript Regular Expressions

To ensure that no HTML tags are entered into a textarea, I am utilizing the following regex for validation. If any HTML tags are detected in the textarea, I need to display a validation message. The regex being used is: /<(\w+)((?:\s+\w ...

Error: Could not locate local grunt on Windows 7 Professional

When attempting to initiate grunt, an error message is displayed: c:\repositories\kunde_1\themes-projekt_1\projekt_1-responsive\source>grunt grunt-cli: The grunt command line interface. (v0.1.13) Fatal error: Unable to find lo ...

Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token. The issue arises with the second script, as it only logs the initial token received and does not update with any new values ...

How can you retrieve attributes from a specific element within a dropdown menu?

I came across this intriguing HTML code snippet: <select id="selectSomething"> <option id="4" data-name="tomato" data-email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfbba0a2aebba08fbbe1aca0a2">[email ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

Variable missing in the ExpressJs view

Hey there! I'm new to Nodejs and currently experimenting with it. I've been trying to convert some of my basic Python codes to JavaScript. In one of my projects, I am sending a get request to the YouTube API and receiving 50 results in JSON forma ...

Looking for insights on reading and presenting XML files from a URL? Learn how to achieve this effortlessly with the power

Currently, I'm in the process of developing an innovative Android application using PhoneGap. My main objective is to dynamically present the data stored within a customized XML file hosted on my website that follows the .php format. Do you happen to ...

An easy CSS conundrum when hovering

Looking for some assistance with CSS. I want to display the text "Featured Page" with a picture appearing on the right side upon hovering (mouseover). Currently, the picture shows up under the text using the following CSS, but I need it to be larger and pl ...

Delightful Popup for Successful Woocommerce Additions

I have created a plugin that transforms Wordpress Woocommerce variations into a table layout. I made significant changes to the code and now I'm attempting to integrate Sweet Alerts 2 in place of the current alerts displayed when a user adds a product ...

Sort the data - a selection menu is included in each row of the table

My issue involves a datatable where each row must have a select item with multiple options to choose from. The goal is to filter the rows based on the selected option when using the default search bar located above the table. However, I've encountered ...

Updating lists using PHP and Ajax: a dynamic approach

I am currently using a chat service that relies on polling every 20 seconds for new user data in the chat room. I am looking to improve this process by only downloading information for new users who have just joined, rather than re-downloading old data f ...

Using Jquery colorbox to redirect or forward within the current colorbox container

I am facing a challenge with a colorbox that is currently loaded. I am looking for a way to redirect or forward to another page within the existing colorbox. window.location = href; does not seem to be effective in this situation. EDIT: To be more precis ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Having trouble getting the Grid class to work in Tailwind with NextJs, any suggestions on why it might not be

Having some trouble with the grid classes in Tailwind not functioning as expected in my code, even though other classes like mt-10 and flex are working perfectly. I've tried applying flex to the parent container and removing it, but the closest I&apo ...

Currently, I am expanding my knowledge of PHP and MySQL by working on a dynamic form that utilizes arrays. As I progress through the project,

One of my recent projects involved creating dynamic rows in a form using code. I managed to save the data in an array and display it using a foreach loop, but I'm facing challenges when trying to insert this data into a database. Here's a glimps ...