Implementing shaders in Three.js

Lately, I've been experimenting with the three.js library and shaders, but I'm facing a challenge when trying to implement a shader on my 3D model. I came across an intriguing example on pixelshaders.com that I would like to incorporate into my threejs model.

The specific example I am referring to is located at the bottom of the page, and I'm struggling to integrate it into my project.

I am attempting to apply this shader to the 3D model accessible through the following link:

However, whenever I add the code from the example, the 3D model disappears, making it challenging to identify the issue.

This is the shader code that works, although not with the intended effect:

<script id="fragmentShader" type="x-shader/x-fragment">
    varying vec2 vUv;

    uniform float time;
    uniform vec2 resolution;
    precision mediump float;

    void main( void ) {

        vec2 position = 2.0 + 2.0 * vUv;

        float red = abs( sin( position.x / position.y + time / 5.0 ) );
        float green = ab...
        
</script>

Whenever I attempt to implement the shader from the pixelshader.com example, my 3D model vanishes.

Is there anyone familiar with how to integrate the shader from the pixelshaders.com example onto the model in my project?

Alternatively, does anyone have any suggestions or tips on what I could try to successfully incorporate the desired shader into my project?

Answer №1

Replacing your fragment shader with the code from pixelshaders.com resulted in a console error being reported:

> THREE.WebGLProgram: shader error: 0 gl.VALIDATE_STATUS false
> gl.getPRogramInfoLog Varyings with the same name but different type,
> or statically used varyings in fragment shader are not declared in
> vertex shader: position

A varying variable serves as an interface between the vertex shader and the fragment shader. This particular error indicates that position is declared in the fragment shader but not in the vertex shader.

The necessary variable was actually present in your vertex shader, albeit under the name vUv. The solution involved ensuring consistency in variable names.

Here is the modified source code (the scaling off the time in the render() function has also been removed):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - materials - shaders [custom]</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                color: #ffffff;
                font-family:Monospace;
                font-size:13px;
                text-align:center;
                font-weight: bold;

                background-color: #050505;
                margin: 0px;
                overflow: hidden;
            }
            a {
                color: #ffffff;
            }
            #oldie a { color:#da0 }
        </style>
    </head>
    <body>

        <div id="container"></div>
        <div id="info"><a href="http://threejs.org" target="_blank">three.js</a> - shader material demo. featuring <a href="http://www.pouet.net/prod.php?which=52761" target="_blank">Monjori by Mic</a></div>


    <link rel="stylesheet" href="css/skeleton.css">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/codemirror.css">
    <script src="js/lib/three.min.js"></script>
    <script src="js/lib/Detector.js"></script>
    <script src="js/geo.js"></script>

        <script id="fragmentShader" type="x-shader/x-fragment">
            precision mediump float;

            varying vec2 vUv;
            uniform float time;

            float random(float p) {
              return fract(sin(p)*10000.);
            }

            float noise(vec2 p) {
              return random(p.x + p.y*10000.);
            }

            vec2 sw(vec2 p) {return vec2( floor(p.x) , floor(p.y) );}
            vec2 se(vec2 p) {return vec2( ceil(p.x)  , floor(p.y) );}
            vec2 nw(vec2 p) {return vec2( floor(p.x) , ceil(p.y)  );}
            vec2 ne(vec2 p) {return vec2( ceil(p.x)  , ceil(p.y)  );}

            float smoothNoise(vec2 p) {
              vec2 inter = smoothstep(0., 1., fract(p));
              float s = mix(noise(sw(p)), noise(se(p)), inter.x);
              float n = mix(noise(nw(p)), noise(ne(p)), inter.x);
              return mix(s, n, inter.y);
              return noise(nw(p));
            }

            float movingNoise(vec2 p) {
              float total = 0.0;
              total += smoothNoise(p     - time);
              total += smoothNoise(p*2.  + time) / 2.;
              total += smoothNoise(p*4.  - time) / 4.;
              total += smoothNoise(p*8.  + time) / 8.;
              total += smoothNoise(p*16. - time) / 16.;
              total /= 1. + 1./2. + 1./4. + 1./8. + 1./16.;
              return total;
            }

            float nestedNoise(vec2 p) {
              float x = movingNoise(p);
              float y = movingNoise(p + 100.);
              return movingNoise(p + vec2(x, y));
            }

            void main() {
              vec2 p = vUv * 6.;
              float brightness = nestedNoise(p);
              gl_FragColor.rgb = vec3(brightness);
              gl_FragColor.a = 1.;
            }

        </script>



        <script id="vertexShader" type="x-shader/x-vertex">
        varying vec2 vUv;

            void main()
            {
                vUv = uv;
                vec4 mvPosition = modelViewMatrix * vec4( position, 1.0);
                gl_Position = projectionMatrix * mvPosition;
            }

        </script>

        <script>

            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var container;
            var camera, controls, scene, renderer;
            var uniforms;
            var clock = new THREE.Clock();

            init();
            animate();

            function init() {

                container = document.getElementById( 'container' );

                camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 3000 );
                camera.position.z = 2;

                scene = new THREE.Scene();

                var geometry = new THREE.BoxGeometry( 0.5, 0.5, 0.5 );

                uniforms = {
                    time: { type: "f", value: 1.0 },
                    resolution: { type: "v2", value: new THREE.Vector3() }
                };              

                var material = new THREE.ShaderMaterial({
                    uniforms: uniforms,
                    vertexShader: document.getElementById( 'vertexShader' ).textContent,
                    fragmentShader: document.getElementById( 'fragmentShader').textContent
                });

                var mesh = new THREE.Mesh( geometry, material );
                scene.add( mesh );


                renderer = new THREE.WebGLRenderer();
                renderer.setPixelRatio( window.devicePixelRatio );
                container.appendChild( renderer.domElement );


                onWindowResize();

                window.addEventListener( 'resize', onWindowResize, false );

            }

            function onWindowResize( event ) {

                uniforms.resolution.value.x = window.innerWidth;
                uniforms.resolution.value.y = window.innerHeight;

                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();

                renderer.setSize( window.innerWidth, window.innerHeight );

            }

            function animate() {
                requestAnimationFrame( animate );
                render();
            }

            function render() {

                var delta = clock.getDelta();

                uniforms.time.value += delta;

                renderer.render( scene, camera );

            }

        </script>

    </body>
</html>

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

Ways to navigate by percentage in react

I'm working on a flexbox that scrolls horizontally with boxes set to 25% width. Currently, I have it scrolling by 420px which is causing responsive issues. Is there a way to implement the scroll using percentages instead of fixed pixel values in React ...

When the page changes or refreshes, the .html() function fails to work

Whenever a new notification arrives, my JavaScript code plays a notification sound as intended. The issue arises because the script is written on the MasterPage, causing the <asp:Label.../> to get cleared upon page refresh or navigation, resulting in ...

Implementing easy-fit in an AngularJS application without the need for requirejs

I am currently exploring the use of an interesting JavaScript library called easy-fit (https://github.com/pierremtb/easy-fit) within an AngularJS application (https://github.com/khertan/forrunners). Easy-fit relies on gulp and babel. My goal is to transpi ...

Transform a column containing objects into a row containing an array of objects

My data is organized in an object with column names such as name, age, and gender, each assigned values for those columns. { 'name': { 0: 'Alpha', 1: 'Beta', 2: 'Gamma' }, 'age': { 0: ...

Step-by-step guide to showing the contents of every file in a directory on the console using node.js or express

Having trouble retrieving file contents from a folder using Node.js I can successfully retrieve the contents of one file using the read function, but unable to retrieve contents of all files at once. ...

Getting the ajax response by utilizing a custom attribute within a php loop is definitely a handy trick

Currently working on integrating ajax with php. I have a set of buttons within a loop, and I am trying to display or fetch data (number) in the correct place/div using the "attr" method in jQuery. However, it seems that it is not functioning as expected on ...

Prestashop: Eliminate user uploaded files with AJAX for seamless experience

By default, a user uploaded image will display with a small black X indicating it can be deleted: <a href="path/to/yourproduct?deletePicture=1" title="Delete" > When the user clicks on this button, the page 'reloads' and the uploaded file ...

Having trouble compiling your React app after adding 'node-sass'? Here's how to resolve the "Module not found" error

After successfully building a react.js app, I encountered an issue upon installing 'node-sass' using npm install. While the app works seamlessly in the production build, it fails to compile in the development build when using npm start. Surprisi ...

Is it possible to set custom spacing for specific breakpoints in a Material-ui theme?

Currently, I am in the process of ensuring that my Material-ui + React dashboard is responsive and well-styled for various screen sizes. Within my custom theme, I have set the spacing to 8: import { createMuiTheme } from '@material-ui/core/styles&ap ...

JavaScript function fails to execute when attempting to call it after opening email client with attachment

//deliver the email to the recipient in eml format Response.ClearHeaders(); Response.Clear(); Response.Buffer = true; Response.ContentType = "message/rfc822"; Response.AddHeader("content-length", bin.Length.ToString()); Response.AddHead ...

Steps to turn off fancybox for mobile and show the full image instead

In this scenario... I am seeking a way to deactivate fancybox functionality on mobile devices. I have already discovered one method to disable it... And now I want to directly show the large image in the a href="xxx_large.jpg" instead of using the img src= ...

Encountering the issue of receiving an "undefined" object while trying to parse JSON

Trying to extract data from the AccuWeather API using a Node.js application. I managed to parse the response using the JSON.parse() method. However, when attempting to access certain nested objects, I encounter an undefined value. Being relatively new to t ...

Tips for successfully including a positive sign character in string values within JSON in the URL's hash fragment

I am facing an issue with my JS (Angular) app where I load parameters from the URL fragment after the # sign. These parameters contain JSON objects, like this example: ...#filters={"Course":["ST_12.+13.12.2016 [Basel]"]} The aim is to open a data-grid an ...

Setting dropdown options dynamically within an ng-repeat loop

I am currently encountering an issue with my Angular code, particularly when populating the dropdown within an HTML table (Code provided below). Could someone kindly assist me in determining what actions need to be taken inside modify() in order to populat ...

Ways to Enhance the Display of Comments in a Chat Box Using JavaScript and PHP

I have created a chat box, but I am facing an issue when trying to delete an unwanted comment. The problem lies in the delete function associated with an onclick event for each inserted comment. The comments are stored in a database. var refreshMsg = setI ...

ajax - Text not appearing in Google's cached version

My website retrieves content using MS AJAX from an ASP.NET webservice. However, when I check the cached version on Google, I notice that the initial text is not displayed. I am wondering what would be the most effective method to ensure the website's ...

Delete the current code within the specified div element

Objective: The goal is to ensure that any HTML syntax code or data inside the specified <div id="feedEntries"></div> element is removed, leaving it empty. Issue: What specific syntax is required to remove all content within <div id="fe ...

The initial click does not trigger a Vue DOM update, but subsequent clicks do initiate the update

I developed a Vue application for a dynamic form with two buttons, and I need to indicate which button was clicked in the request. To achieve this, I update the value of a hidden input field and then submit the form using jQuery. However, when I click on t ...

What could be the reason for the error message when using rs.send with a string input?

I'm a beginner in node and express, and I was trying to create an HTML form that takes two numbers and displays the result using "express" and "node". However, when I use rs.send(result), I encounter the following error: https://i.sstatic.net/FcUNJ.p ...

ReactJS Hook call is not valid

Currently, I am delving into learning ReactJS and went through a helpful tutorial that provided me with a solid foundation in utilizing firebase for authentication and authorization on a webpage. I am now incorporating a Sign-In page template from material ...