Utilizing Three.js Texture with shaderMaterial

I'm encountering an issue where I can't seem to load a texture onto my shader material, resulting in just black dots appearing. Here's the code snippet from my shader.js:

THREE.ShaderLib['cloud'] = {

    uniforms: {
        texture: { type: "t", value: THREE.ImageUtils.loadTexture("img/cloud.png") }
    },

    vertexShader: [
        "varying vec2 vUv;",
        "void main() {",
            "vUv = uv;",
            "gl_PointSize = 8.0;",
            "gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
        "}",
    ].join("\n"),

    fragmentShader: [
            "varying vec2 vUv;",
            "uniform sampler2D texture;",
            "void main() {",
                "gl_FragColor = texture2D(texture, vUv);",
            "}",
    ].join("\n")
};

Here is my attempt at loading and utilizing it:

var cloudShader = THREE.ShaderLib["cloud"];
var uniforms = THREE.UniformsUtils.clone(cloudShader.uniforms);

var texture = THREE.ImageUtils.loadTexture("img/cloud.png", undefined, function () {

   uniforms.texture.value = texture;
   texture.needsUpdate = true;

   var _material = new THREE.ShaderMaterial({
      fragmentShader: cloudShader.fragmentShader,
      vertexShader: cloudShader.vertexShader,
      uniforms: uniforms                   
   });                    
   _material.uniforms.texture.value.needsUpdate = true;
   var _geometry = new THREE.Geometry();
   _geometry.vertices.push(new THREE.Vector3(0, 0, 0));
   var _mesh = new THREE.Points(_geometry, _material);
   scene.add(_mesh);

 });

Despite setting the texture update twice - before and after creating the material, I'm still experiencing issues without any error messages in the debug console. I've opted for using the THREE.Points class to create cloud particle groups.

Any assistance would be greatly appreciated. Thank you!

Answer №1

After spending some time on it, I finally cracked the code for this particular issue. The key was to transfer my uniforms from shader.js directly to where I'm creating the shader material. This simple adjustment fixed the problem with the texture, although I'm still puzzled as to why the previous code didn't work. The updated shader material now appears like this:

 var _material = new THREE.ShaderMaterial({
      fragmentShader: cloudShader.fragmentShader,
      vertexShader: cloudShader.vertexShader,
      uniforms: {
        texture: { type: "t", value: THREE.ImageUtils.loadTexture("img/cloud.png") }
      },
 });   

Answer №2

   "varying vec2 vUv;",
        "uniform sampler2D textureMap;",
        "void main() {",
            "gl_FragColor = texture2D(textureMap, vUv);", // found here
        "}",

In 2024, this specific line leads to an error due to the conflict with another function utilizing the name "texture" in threejs's shader material.

Answer №3

If you're running into a similar problem at the moment, the issue with this code not functioning lies in more than just the fact that texture is considered a reserved keyword in GLSL 4.

When working with particles in ThreeJS, specifically with the THREE.Points class, it's essential to provide gl_PointCoord as the second argument to texture2D instead of using uv coordinates.

A correct implementation would look like this:

THREE.ShaderLib['cloud'] = {
    
        uniforms: {
            uTexture: { type: "t", value: THREE.ImageUtils.loadTexture("img/cloud.png") }
        },
    
        vertexShader: [
            "void main() {",
                "gl_PointSize = 8.0;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
            "}",
        ].join("\n"),
    
        fragmentShader: [
                "uniform sampler2D uTexture;",
                "void main() {",
                    "gl_FragColor = texture2D(uTexture, gl_PointCoord);",
                "}",
        ].join("\n")
    };

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

Express along with Cheerio and JSDOM

I'm currently exploring the integration of Cheerio with Express to enable server-side DOM manipulation. I haven't had much luck beyond basic web scraping techniques. There are specific requirements I need to meet for this project. Currently, I ...

"Is there a virtual keyboard available that supports multiple inputs and automatically switches to the next input when the maximum length

Looking to build a virtual keyboard with multiple inputs that automatically switch to the next input field after reaching the maximum length. Currently having an issue where I can only fill the first input and not the second one. Any assistance in resolvin ...

Is the ng-style not displaying the background image with the interpolated value?

I have been attempting to update the background image of a div using angular ng-style. Below is the code I am working with: <div class="cover-image" ng-style="{'background-image' : 'url({{data.image}})'}"></div> However, ...

ReactJS import duplication problem arising from utilizing npm link for component testing prior to npm package release

I have a basic component structured like this. import React, {useState} from 'react'; function MyComponentWithState(props) { const [value, setValue] = useState(0); return ( <p>My value is: {value}</p> ) } expo ...

Substitute the temporary text with an actual value in JavaScript/j

Looking to customize my JSP website by duplicating HTML elements and changing their attributes to create a dynamic form. Here is the current JavaScript code snippet I have: function getTemplateHtml(templateType) { <%-- Get current number of element ...

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

The head.js feature similar to "Modernizr" does not recognize ms-edge

It has come to my attention that the head.js script is unable to detect the Microsoft "Edge" browser correctly. In addition, it erroneously adds classes like chrome and chrome55 to the <html> element. Is there a better way to handle this issue? The ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

The functionality for transferring ERC20 claim tokens seems to be malfunctioning

I am facing an issue with my contract while trying to execute the claimFreeToken function. Even though the contract does not have enough tokens, the function does not return an error and the token also does not get received. Can anyone point out where I ...

unable to navigate to next or previous page in react-bootstrap-table2-paginator

I successfully implemented a table with pagination using react-bootstrap-table2-paginator. On each page number click, it calls an API to fetch the table data. However, I encountered issues with the next page, previous page, and last page buttons not workin ...

Expand an image to its full dimensions when it is initially loaded

Currently, I am experimenting with placing images of bubbles randomly on a webpage. To create the illusion of the bubble expanding in size from nothing to its full scale, I have been using CSS and specifically the transform:scale(); property. However, my ...

Ways to retrieve information from JSON

I am currently trying to access the values of an object that is within an array which is inside another object. The data is structured as follows: [{ "id": "99a4e6ef-68b0-4cdc-8f2f-d0337290a9be", "stock_name": "J ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

Seamless animation when collapsing element using angular and css exclusively

I am attempting to incorporate a collapsible feature into my application. Rather than relying on external libraries like jQuery, I want to exclusively utilize Angular. For demonstration purposes, I have created a very basic example here: http://jsfiddle.n ...

Is it possible for nextAll() to exclude a specific parent element and search only for children inside that parent?

Below is the structure of my html ajax form: <form name="vafForm" id="vafForm" method="GET" action="urlfor ajax"> <input type="hidden" value="0" id="vafProduct"> <select class="catSelect {prevLevelsIncluding: 'cat'} c ...

Aggregate information from an array containing multiple nested arrays

With regards to marking this as answered by another question, please take note that this is not a flat array but an array of arrays. Additionally, the numbers provided are just examples for visual representation. I am attempting to iterate through an arra ...

Need to `come back` multiple times

I am facing an issue where I want to return multiple lines, but only the first line is being returned. I attempted to create a function specifically for returning the line, but encountered errors because I couldn't figure out where to place it. Does ...

Express.js app does not seem to properly handle app.use(express.raw()) functionality

I am in the process of creating an Express application that is designed to handle binary post data. The code snippet below showcases my progress so far: Server-side: var express = require('express'); var app = express(); var PORT = 3000; app.us ...

Passing JSON information through PatternLab

Incorporating an atomic pattern and passing data from a JSON array is my goal. Below are the code snippets and JSON file. anchor-link.mustache <a href="{{ url }}" class="{{ class }}">{{ label }}</a> footer-nav.mustache <ul class="menu ve ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...