``Are you looking to unlock the power of vertex and fragment shaders within your three.js projects

Recently, I delved into the world of WebGL by starting to work through a book titled "WebGL: Up and Running". This book utilizes my preferred rendering solution, THREE.js, for creating 3D objects in web browsers. One section of the book caught my attention - it introduced shaders to create a dynamic, lit sun. However, when I attempted to replicate this using the provided shader code, all I ended up with was a black sphere. Surprisingly, when I switched to a simpler shader like a Lambert shader, everything worked as expected. It seems that the issue lies within the implementation of the complex shader.

I'm scratching my head trying to figure out where I went wrong. Here is the JavaScript code snippet I used to set up the scene:

var renderer, scene, camera, sunMesh, clock, uniforms;

$(function(){          

    //set scene size
    var WIDTH = 1200,
            HEIGHT = 800;

    //set some camera attributes
    var VIEW_ANGLE = 45,
        ASPECT = WIDTH / HEIGHT,
        NEAR = 0.1,
        FAR = 10000;

    // get the DOM element to attach to
    // - assume we've got jQuery to hand
    var $container = $('#container');

    // create a WebGL renderer, camera
    // and a scene
    renderer = new THREE.WebGLRenderer();
    camera = new THREE.PerspectiveCamera(  VIEW_ANGLE,
                                    ASPECT,
                                    NEAR,
                                    FAR  );
    scene = new THREE.Scene();

    // the camera starts at 0,0,0 so pull it back
    camera.position.z = 300;

    // start the renderer
    renderer.setSize(WIDTH, HEIGHT);

    // attach the render-supplied DOM element
    $container.append(renderer.domElement);

    // Create a group to hold our sun mesh and light
    var sunGroup = new THREE.Object3D();
    var SUNMAP = "./images/lavatile.jpg";
    var NOISEMAP = "./images/cloud.png";
    uniforms = {
            time: { type: "f", value: 1.0 },
            texture1: { type: "t", value: 0, texture: THREE.ImageUtils.loadTexture( NOISEMAP ) },
            texture2: { type: "t", value: 1, texture: THREE.ImageUtils.loadTexture( SUNMAP ) }
    };

    uniforms.texture1.texture.wrapS = uniforms.texture1.texture.wrapT = THREE.Repeat;
    uniforms.texture2.texture.wrapS = uniforms.texture2.texture.wrapT = THREE.Repeat;
    var material = new THREE.ShaderMaterial( {
            uniforms: uniforms,
            vertexShader: document.getElementById( 'vertexShader' ).textContent,
            fragmentShader: document.getElementById( 'fragmentShader' ).textContent
    } );


    var geometry = new THREE.SphereGeometry(50, 64, 64);
    sunMesh = new THREE.Mesh( geometry, material );

    clock = new THREE.Clock();

    var light = new THREE.PointLight( 0xffffff );
    light.position.set(0,0,100);
    sunGroup.add(sunMesh);
    sunGroup.add(light);
    scene.add(sunGroup);
    scene.add(camera);

    renderer.render(scene, camera);

    setInterval(gameloop, 50);     

});

function gameloop() {  
    var delta = clock.getDelta();
    uniforms.time.value += delta;
    renderer.render(scene, camera);
}

I have uploaded the full HTML code here, which includes the shaders obtained from the WebGL book source. While there is a chance that these shaders are incorrect, I am leaning towards the possibility that my usage of the shaders might be flawed. My expectation was to see a sun with textures changing based on a noise occlusion map, accompanied by movement in the vertex position to emulate a pulsating effect. Unfortunately, all I can see is an unlit, black sphere.

Any insights on where I might have made a mistake?

Answer №1

What a disappointment. This book seems to be outdated already.

Three.js is still in alpha stage and evolving quickly. Make sure to refer to the three.js examples for accurate information. They are always up-to-date.

Take a look at the Migration Wiki for assistance in transitioning to the latest version.

There are some clear errors in your code:

texture1: { type: "t", value: 0, texture: THREE.ImageUtils.loadTexture( NOISEMAP ) },

should be

texture1: { type: "t", value: THREE.ImageUtils.loadTexture( NOISEMAP ) },

THREE.Repeat should be changed to THREE.RepeatWrapping, while uniforms.texture1.texture should be uniforms.texture1.value.

I'm sorry if there are any other issues, but I can only provide assistance based on the current version of three.js.

three.js r.54

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'"> < ...

Issue with Textarea not updating when props change in a React component

I am facing an issue with updating the default value of a textarea based on props passed from a parent component. Strangely, the update works when using 'value' but not when using 'defaultValue'. However, I need the textarea to be edita ...

Unable to display notifications within the modal using Notistack MUI in React JS

Hey there, I'm currently utilizing react in combination with MUI. To display notifications, I've integrated a library called notistack. My goal is to show an error message in a dialog if there's a failure in the API response. Here's the ...

"Positioned at the top of the page is the alert box, with the

I'm looking to add an alert at the top of my webpage containing a form for visitors to enter their phone number. Currently, I have a "alert alert-info" div with the form inside it placed at the top of my body tag, which works perfectly. However, when ...

Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } } I want to transform this string into JSON structure like below: { "DataError": { "user_id": [ [Object] ] } } Is there a potential method to achieve this outcome from incorrectly formatted JSON string? ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

The property of Three.js Quaternion is immutable and cannot be reassigned

I'm attempting to develop a class (using three.js) that utilizes an array containing vector names to compare with an array containing a set of 3D vectors in order to generate a mesh of a flat face. However, I am encountering an error. Uncaught TypeEr ...

Refreshing the PHP variable without needing to refresh the page

Recently, I've delved into the world of JSON and PHP programming. I am currently working on a web page that displays data from a file called file.py. This data is intended to be visualized on a gauge that updates every second. var gauge1; var x = ...

Exploring Symfony2: Enhancing user experience with dynamic form submission and dropdown menu updates

Starting from the beginning. I have a tab-panned layout with links. Upon clicking a link, a drop-down checkbox form is injected directly into the HTML through $(".dropdown-toggle").click(function() { var projectId = $("#permission-form").attr("data-p ...

Differences between referencing and valuing in arrays in JavaScript

I have noticed an interesting behavior when passing arrays to functions by reference. Even after modifying the array inside a function, the changes do not reflect when logging the array outside the function. For example: let arr = [1, 2]; console.log(arr ...

Turn off the observeChanges feature for the update query

I am trying to disable the observeChanges method on a collection when updating it. Does anyone have a solution for this? I came across the Meteor Docs which mentioned using reactive: false for the .find() method. Is there a similar option for the .update( ...

Create a sinusoidal wave and stream it through the web browser

I'm looking for a code snippet that can: create a sine wave (an array of samples) play the wave This should all be accomplished in a web browser using an HTML5 API in JavaScript. (I've tagged this with web-audio, but I'm not entirely ...

Safari is encountering a 'Invalid Date' error in Javascript

Help me solve this issue with my script: var date = new Date("19871104071535".replace( /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/, '$4:$5:$6 $2/$3/$1' )); alert(date); The script run ...

Defeat the all-powerful !important tag and enable dialog customization for positioning

I am currently developing a browser extension and I am encountering an issue with using JQueryUI to display a modal dialog. The problem arises when certain websites, for example espn.com, also utilize JQueryUI but do not properly scope their own elements. ...

Best practices for authenticating methods with Google signin in Angular projects

I have made significant progress towards getting the Google signin feature to work, reaching 95% completion. However, I am currently facing two issues with the code. Here is a simplified version of my current implementation: loginWithGoogle(): void { //t ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Is it possible to utilize React hooks within a conditional statement?

My current situation involves an object serving as a state, complete with various properties. Now, I am looking to update this state within a specific condition using a hook. However, this update seems to trigger an infinite loop. The question at hand is ...

Verify the correctness of two password fields using jQuery

I need help finding a script that can actively check if the passwords entered in two password fields match while typing. The script should indicate if the passwords do not match without needing to click the Submit button. Below are the two password fields ...

Learn how to retrieve data prior to rendering with Vue 3 and the composition api

Is there a way to fetch data from an API and populate my store (such as user info) before the entire page and components load? I have been struggling to find a solution. I recently came across the beforeRouteEnter method that can be used with the options ...

Tips for integrating Laravel's blade syntax with Vuejs

Can you guide me on integrating the following Laravel syntax into a Vue.js component? @if(!Auth::guest()) @if(Auth::user()->id === $post->user->id) <a href=#>edit</a> @endif @endif ...