How can I transform this to an ES6 module in JavaScript?

Currently, I am dissecting the ShaderGlow example found on this GitHub link in order to integrate it into my node application.

The original author utilized <script> tags within the HTML document, while my entire application is structured within app.js and imports ES6 modules from helper files.

In its initial state, the shader functions as follows:

var customMaterial = new THREE.ShaderMaterial(
{
    uniforms:
    {
        "c":   { type: "f", value: 1.0 },
        "p":   { type: "f", value: 1.4 },
        glowColor: { type: "c", value: new THREE.Color(0xffff00) },
        viewVector: { type: "v3", value: camera.position }
    },
    vertexShader:   document.getElementById('vertexShader').textContent,
    fragmentShader: document.getElementById('fragmentShader').textContent,
    side: THREE.FrontSide,
    blending: THREE.AdditiveBlending,
    transparent: true
});

Where the fragment and vertex shaders are enclosed within their respective <script> elements:

<script id="vertexShader" type="x-shader/x-vertex">
uniform vec3 viewVector;
uniform float c;
uniform float p;
varying float intensity;
void main() 
{
    vec3 vNormal = normalize(normalMatrix * normal);
    vec3 vNormel = normalize(normalMatrix * viewVector);
    intensity = pow(c - dot(vNormal, vNormel), p);

    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
</script>

<script id="fragmentShader" type="x-shader/x-vertex"> 
uniform vec3 glowColor;
varying float intensity;
void main() 
{
    vec3 glow = glowColor * intensity;
    gl_FragColor = vec4(glow, 1.0);
}
</script>

My attempt involved importing these shaders like so:

import fragmentShader from './elements/GlowShaders.js';
import vertexShader from './elements/GlowShaders.js';

var customMaterial = new THREE.ShaderMaterial(
{
    uniforms:
    {
        "c":   { type: "f", value: 1.0 },
        "p":   { type: "f", value: 1.4 },
        glowColor: { type: "c", value: new THREE.Color(0xffff00) },
        viewVector: { type: "v3", value: this.camera.position }
    },
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
    side: THREE.FrontSide,
    blending: THREE.AdditiveBlending,
    transparent: true
});

The GlowShader.js file was structured as follows:

export default class vertexShader {
  uniform vec3 viewVector;
  uniform float c;
  uniform float p;
  varying float intensity;
  void main()
  {
      vec3 vNormal = normalize(normalMatrix * normal);
    vec3 vNormel = normalize(normalMatrix * viewVector);
    intensity = pow(c - dot(vNormal, vNormel), p);

      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  }
}

export default class fragmentShader {
  uniform vec3 glowColor;
  varying float intensity;
  constructor() {
    vec3 glow = glowColor * intensity;
      gl_FragColor = vec4(glow, 1.0);
  }
}

As a novice with modules, this approach did not yield the desired results. How can I modularize these specific shader blocks or incorporate them effectively within my app.js script?

Answer №1

Is it possible for you to provide a solution that involves converting the code block into JSON.stringify or any other format that is compatible with JavaScript? Simply pasting it directly into the parameter does not yield the desired result.

const vertexShader = `
uniform vec3 viewVector;
uniform float c;
uniform float p;
varying float intensity;
void main() 
{
    vec3 vNormal = normalize( normalMatrix * normal );
    vec3 vNormel = normalize( normalMatrix * viewVector );
    intensity = pow( c - dot(vNormal, vNormel), p );

    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`;

const fragmentShader = `
uniform vec3 glowColor;
varying float intensity;
void main() 
{
    vec3 glow = glowColor * intensity;
    gl_FragColor = vec4( glow, 1.0 );
}`;

var customMaterial = new THREE.ShaderMaterial({
    uniforms:
    {
        "c":   { type: "f", value: 1.0 },
        "p":   { type: "f", value: 1.4 },
        glowColor: { type: "c", value: new THREE.Color(0xffff00) },
        viewVector: { type: "v3", value: camera.position }
    },
    vertexShader,
    fragmentShader,
    side: THREE.FrontSide,
    blending: THREE.AdditiveBlending,
    transparent: true
});

or

var customMaterial = new THREE.ShaderMaterial({
    uniforms:
    {
        "c":   { type: "f", value: 1.0 },
        "p":   { type: "f", value: 1.4 },
        glowColor: { type: "c", value: new THREE.Color(0xffff00) },
        viewVector: { type: "v3", value: camera.position }
    },
    vertexShader: "uniform vec3 viewVector;\nuniform float c;\nuniform float p;\nvarying float intensity;\nvoid main() \n{\n    vec3 vNormal = normalize( normalMatrix * normal );\n    vec3 vNormel = normalize( normalMatrix * viewVector );\n    intensity = pow( c - dot(vNormal, vNormel), p );\n\n    gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",
    fragmentShader: "uniform vec3 glowColor;\nvarying float intensity;\nvoid main() \n{\n    vec3 glow = glowColor * intensity;\n    gl_FragColor = vec4( glow, 1.0 );\n}",
    side: THREE.FrontSide,
    blending: THREE.AdditiveBlending,
    transparent: true
});

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

As the user types, the DD/MM/YYYY format will automatically be recognized in the

In my React component, I have an input box meant for entering a date of birth. The requirement is to automatically insert a / after each relevant section, like 30/03/2017 I am looking for something similar to this concept, but for date of birth instead of ...

Transferring information through Ajax to PHP

When using AJAX to send a string via the GET method, I've noticed that punctuation characters sometimes don't appear when echoed in PHP. For instance, sending "sub + 12" results in PHP echoing "sub 12", and sending "&()*" echoes an empty str ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

Issue with z-index causing the image to not display when navigating through an image gallery with previous and next buttons using

$(document).ready(function(){ $(".divs div.panel").each(function(e) { if (e > 2) $(this).hide(); console.log(e); }); $("#next").click(function(){ if ($ ...

AngularJS dynamic data table for interactive and flexible data presentation

I am looking to implement a dynamic data table using AngularJS, with the first column containing checkboxes. The data will be in JSON format as shown below, $scope.items = [ { "id": "1", "lastName": "Test1", "firstName": "Test", "email": "<a hr ...

Display the X button solely once text has been inputted into the textbox

I have integrated a text clearing plugin from here in my project to allow users to clear the input field by clicking on an X button. However, I want to modify the code so that the X button only appears when there is text entered in the textbox. I attempt ...

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

Configuring Google Chart LineChart settings by utilizing the series attribute

I am looking to modify the options for my line chart. However, when I define the options as shown below, the first series setting gets ignored and only the second series property is applied. var options = { title: 'Temperature Graph ( sampling ev ...

Selecting specific elements from an array in JavaScript can be achieved by using various methods and techniques

Currently working on a quiz incentive system where users earn rewards based on the number of correct answers they input. The example array below shows the possible range of correct answers: var rightAnswers = ['a', 'b', 'c' ...

JavaScript filter method returns a new array with all elements that

I have an Array of Objects with nested Arrays and Objects. Here's an example: data = [{ "id": 10022, "date": "2017-12-31T03:44:19.963808Z", "bought_beats": [{ "id": 10034, "beat": { "id": 6334, "nam ...

Prevent rendering HTML elements in React by utilizing the react-lazyload feature

After incorporating react-lazyload into my component, I encountered a specific scenario where the "lazy load" functionality is not required. Despite thoroughly examining the react-lazyload documentation, I was unable to identify any prop that could deactiv ...

How can I rotate an object around its own center using Three.js instead of the world center?

I have encountered an issue with rotating objects in my scene. The cube rotates around its own center, which is what I expected. However, the shoe model's rotation axis is along the world's y-axis. In my original code, I had: cube.rotation.y += ...

The ajax function does not provide a response

Can you help me figure out why this JavaScript function keeps returning 'undefined'? I really need it to return either true or false. I've included my code below: function Ajax() { var XML; if(window.XMLHttpRequest) XML=new ...

What is the best method for inserting the HTML content from a specific div into a textarea?

Everything seems to be working fine, but once I insert the HTML into the textarea, an issue arises where the div gets wrapped within another div, causing the layout to break. var urls = []; $('body').on('click', '.btn_video&apos ...

The JavaScript code is not functioning properly on the server after the ajax request

I have a situation where an ajax request is sending data to a PHP file, and then the PHP file is generating HTML content with some JavaScript code. The JavaScript code includes Google's chart library, but unfortunately the chart is not working as inte ...

Is it possible to automatically reload the previous link when the back button of the browser is clicked?

I am working on a website where the main content is loaded using jQuery Ajax based on the selected menu item. When a menu item is selected, the URL changes according to this pattern: http://host/domain/index.php?pageid=page In this scenario, the 'p ...

Incorporating AJAX in jQuery mobile to transmit data to a controller in CodeIgniter

I'm currently facing an issue where despite successfully retrieving the latitude and longitude values from the geolocation feature in Google Chrome, I am unable to pass these values to the index function within the controller named Add. When attemptin ...

Triggering the browser to prompt the "Save As" dialog box when initiating a file download

After researching extensively on this particular topic, I have come to realize that none of the solutions available meet my requirements. What I am trying to achieve is to instruct my WinCE 6.0 board to generate a backup file via an AJAX request and then s ...

Deciphering the intricacies of using middleware in Express -

As a novice, I find it challenging to interpret documentation, but I can grasp the code's meaning once I see it in action. Take app.use([path,] callback [, callback...]), for example. I know how to utilize this method, yet I still struggle with unde ...

Exploring ways to compare and update values in an array of objects using JavaScript

I have a situation where I need to compare the names and values of two arrays filled with objects. const array1 = [ { name: 'Sarah', value: null }, { name: 'Michael', value: null } ] const array2 = [ { na ...